Merge branch 'traff/run-module'

This commit is contained in:
Dmitry Trofimov
2017-10-05 15:28:10 +02:00
12 changed files with 817 additions and 94 deletions
@@ -0,0 +1,591 @@
"""Utilities to support packages."""
# NOTE: This module must remain compatible with Python 2.3, as it is shared
# by setuptools for distribution with Python 2.3 and up.
import imp
import os
import os.path
import sys
from types import ModuleType
__all__ = [
'get_importer', 'iter_importers', 'get_loader', 'find_loader',
'walk_packages', 'iter_modules', 'get_data',
'ImpImporter', 'ImpLoader', 'read_code', 'extend_path',
]
def read_code(stream):
# This helper is needed in order for the PEP 302 emulation to
# correctly handle compiled files
import marshal
magic = stream.read(4)
if magic != imp.get_magic():
return None
stream.read(4) # Skip timestamp
return marshal.load(stream)
def simplegeneric(func):
"""Make a trivial single-dispatch generic function"""
registry = {}
def wrapper(*args, **kw):
ob = args[0]
try:
cls = ob.__class__
except AttributeError:
cls = type(ob)
try:
mro = cls.__mro__
except AttributeError:
try:
class cls(cls, object):
pass
mro = cls.__mro__[1:]
except TypeError:
mro = object, # must be an ExtensionClass or some such :(
for t in mro:
if t in registry:
return registry[t](*args, **kw)
else:
return func(*args, **kw)
try:
wrapper.__name__ = func.__name__
except (TypeError, AttributeError):
pass # Python 2.3 doesn't allow functions to be renamed
def register(typ, func=None):
if func is None:
return lambda f: register(typ, f)
registry[typ] = func
return func
wrapper.__dict__ = func.__dict__
wrapper.__doc__ = func.__doc__
wrapper.register = register
return wrapper
def walk_packages(path=None, prefix='', onerror=None):
"""Yields (module_loader, name, ispkg) for all modules recursively
on path, or, if path is None, all accessible modules.
'path' should be either None or a list of paths to look for
modules in.
'prefix' is a string to output on the front of every module name
on output.
Note that this function must import all *packages* (NOT all
modules!) on the given path, in order to access the __path__
attribute to find submodules.
'onerror' is a function which gets called with one argument (the
name of the package which was being imported) if any exception
occurs while trying to import a package. If no onerror function is
supplied, ImportErrors are caught and ignored, while all other
exceptions are propagated, terminating the search.
Examples:
# list all modules python can access
walk_packages()
# list all submodules of ctypes
walk_packages(ctypes.__path__, ctypes.__name__+'.')
"""
def seen(p, m={}):
if p in m:
return True
m[p] = True
for importer, name, ispkg in iter_modules(path, prefix):
yield importer, name, ispkg
if ispkg:
try:
__import__(name)
except ImportError:
if onerror is not None:
onerror(name)
except Exception:
if onerror is not None:
onerror(name)
else:
raise
else:
path = getattr(sys.modules[name], '__path__', None) or []
# don't traverse path items we've seen before
path = [p for p in path if not seen(p)]
for item in walk_packages(path, name+'.', onerror):
yield item
def iter_modules(path=None, prefix=''):
"""Yields (module_loader, name, ispkg) for all submodules on path,
or, if path is None, all top-level modules on sys.path.
'path' should be either None or a list of paths to look for
modules in.
'prefix' is a string to output on the front of every module name
on output.
"""
if path is None:
importers = iter_importers()
else:
importers = map(get_importer, path)
yielded = {}
for i in importers:
for name, ispkg in iter_importer_modules(i, prefix):
if name not in yielded:
yielded[name] = 1
yield i, name, ispkg
#@simplegeneric
def iter_importer_modules(importer, prefix=''):
if not hasattr(importer, 'iter_modules'):
return []
return importer.iter_modules(prefix)
iter_importer_modules = simplegeneric(iter_importer_modules)
class ImpImporter:
"""PEP 302 Importer that wraps Python's "classic" import algorithm
ImpImporter(dirname) produces a PEP 302 importer that searches that
directory. ImpImporter(None) produces a PEP 302 importer that searches
the current sys.path, plus any modules that are frozen or built-in.
Note that ImpImporter does not currently support being used by placement
on sys.meta_path.
"""
def __init__(self, path=None):
self.path = path
def find_module(self, fullname, path=None):
# Note: we ignore 'path' argument since it is only used via meta_path
subname = fullname.split(".")[-1]
if subname != fullname and self.path is None:
return None
if self.path is None:
path = None
else:
path = [os.path.realpath(self.path)]
try:
file, filename, etc = imp.find_module(subname, path)
except ImportError:
return None
return ImpLoader(fullname, file, filename, etc)
def iter_modules(self, prefix=''):
if self.path is None or not os.path.isdir(self.path):
return
yielded = {}
import inspect
try:
filenames = os.listdir(self.path)
except OSError:
# ignore unreadable directories like import does
filenames = []
filenames.sort() # handle packages before same-named modules
for fn in filenames:
modname = inspect.getmodulename(fn)
if modname=='__init__' or modname in yielded:
continue
path = os.path.join(self.path, fn)
ispkg = False
if not modname and os.path.isdir(path) and '.' not in fn:
modname = fn
try:
dircontents = os.listdir(path)
except OSError:
# ignore unreadable directories like import does
dircontents = []
for fn in dircontents:
subname = inspect.getmodulename(fn)
if subname=='__init__':
ispkg = True
break
else:
continue # not a package
if modname and '.' not in modname:
yielded[modname] = 1
yield prefix + modname, ispkg
class ImpLoader:
"""PEP 302 Loader that wraps Python's "classic" import algorithm
"""
code = source = None
def __init__(self, fullname, file, filename, etc):
self.file = file
self.filename = filename
self.fullname = fullname
self.etc = etc
def load_module(self, fullname):
self._reopen()
try:
mod = imp.load_module(fullname, self.file, self.filename, self.etc)
finally:
if self.file:
self.file.close()
# Note: we don't set __loader__ because we want the module to look
# normal; i.e. this is just a wrapper for standard import machinery
return mod
def get_data(self, pathname):
return open(pathname, "rb").read()
def _reopen(self):
if self.file and self.file.closed:
mod_type = self.etc[2]
if mod_type==imp.PY_SOURCE:
self.file = open(self.filename, 'rU')
elif mod_type in (imp.PY_COMPILED, imp.C_EXTENSION):
self.file = open(self.filename, 'rb')
def _fix_name(self, fullname):
if fullname is None:
fullname = self.fullname
elif fullname != self.fullname:
raise ImportError("Loader for module %s cannot handle "
"module %s" % (self.fullname, fullname))
return fullname
def is_package(self, fullname):
fullname = self._fix_name(fullname)
return self.etc[2]==imp.PKG_DIRECTORY
def get_code(self, fullname=None):
fullname = self._fix_name(fullname)
if self.code is None:
mod_type = self.etc[2]
if mod_type==imp.PY_SOURCE:
source = self.get_source(fullname)
self.code = compile(source, self.filename, 'exec')
elif mod_type==imp.PY_COMPILED:
self._reopen()
try:
self.code = read_code(self.file)
finally:
self.file.close()
elif mod_type==imp.PKG_DIRECTORY:
self.code = self._get_delegate().get_code()
return self.code
def get_source(self, fullname=None):
fullname = self._fix_name(fullname)
if self.source is None:
mod_type = self.etc[2]
if mod_type==imp.PY_SOURCE:
self._reopen()
try:
self.source = self.file.read()
finally:
self.file.close()
elif mod_type==imp.PY_COMPILED:
if os.path.exists(self.filename[:-1]):
f = open(self.filename[:-1], 'rU')
self.source = f.read()
f.close()
elif mod_type==imp.PKG_DIRECTORY:
self.source = self._get_delegate().get_source()
return self.source
def _get_delegate(self):
return ImpImporter(self.filename).find_module('__init__')
def get_filename(self, fullname=None):
fullname = self._fix_name(fullname)
mod_type = self.etc[2]
if self.etc[2]==imp.PKG_DIRECTORY:
return self._get_delegate().get_filename()
elif self.etc[2] in (imp.PY_SOURCE, imp.PY_COMPILED, imp.C_EXTENSION):
return self.filename
return None
try:
import zipimport
from zipimport import zipimporter
def iter_zipimport_modules(importer, prefix=''):
dirlist = zipimport._zip_directory_cache[importer.archive].keys()
dirlist.sort()
_prefix = importer.prefix
plen = len(_prefix)
yielded = {}
import inspect
for fn in dirlist:
if not fn.startswith(_prefix):
continue
fn = fn[plen:].split(os.sep)
if len(fn)==2 and fn[1].startswith('__init__.py'):
if fn[0] not in yielded:
yielded[fn[0]] = 1
yield fn[0], True
if len(fn)!=1:
continue
modname = inspect.getmodulename(fn[0])
if modname=='__init__':
continue
if modname and '.' not in modname and modname not in yielded:
yielded[modname] = 1
yield prefix + modname, False
iter_importer_modules.register(zipimporter, iter_zipimport_modules)
except ImportError:
pass
def get_importer(path_item):
"""Retrieve a PEP 302 importer for the given path item
The returned importer is cached in sys.path_importer_cache
if it was newly created by a path hook.
If there is no importer, a wrapper around the basic import
machinery is returned. This wrapper is never inserted into
the importer cache (None is inserted instead).
The cache (or part of it) can be cleared manually if a
rescan of sys.path_hooks is necessary.
"""
try:
importer = sys.path_importer_cache[path_item]
except KeyError:
for path_hook in sys.path_hooks:
try:
importer = path_hook(path_item)
break
except ImportError:
pass
else:
importer = None
sys.path_importer_cache.setdefault(path_item, importer)
if importer is None:
try:
importer = ImpImporter(path_item)
except ImportError:
importer = None
return importer
def iter_importers(fullname=""):
"""Yield PEP 302 importers for the given module name
If fullname contains a '.', the importers will be for the package
containing fullname, otherwise they will be importers for sys.meta_path,
sys.path, and Python's "classic" import machinery, in that order. If
the named module is in a package, that package is imported as a side
effect of invoking this function.
Non PEP 302 mechanisms (e.g. the Windows registry) used by the
standard import machinery to find files in alternative locations
are partially supported, but are searched AFTER sys.path. Normally,
these locations are searched BEFORE sys.path, preventing sys.path
entries from shadowing them.
For this to cause a visible difference in behaviour, there must
be a module or package name that is accessible via both sys.path
and one of the non PEP 302 file system mechanisms. In this case,
the emulation will find the former version, while the builtin
import mechanism will find the latter.
Items of the following types can be affected by this discrepancy:
imp.C_EXTENSION, imp.PY_SOURCE, imp.PY_COMPILED, imp.PKG_DIRECTORY
"""
if fullname.startswith('.'):
raise ImportError("Relative module names not supported")
if '.' in fullname:
# Get the containing package's __path__
pkg = '.'.join(fullname.split('.')[:-1])
if pkg not in sys.modules:
__import__(pkg)
path = getattr(sys.modules[pkg], '__path__', None) or []
else:
for importer in sys.meta_path:
yield importer
path = sys.path
for item in path:
yield get_importer(item)
if '.' not in fullname:
yield ImpImporter()
def get_loader(module_or_name):
"""Get a PEP 302 "loader" object for module_or_name
If the module or package is accessible via the normal import
mechanism, a wrapper around the relevant part of that machinery
is returned. Returns None if the module cannot be found or imported.
If the named module is not already imported, its containing package
(if any) is imported, in order to establish the package __path__.
This function uses iter_importers(), and is thus subject to the same
limitations regarding platform-specific special import locations such
as the Windows registry.
"""
if module_or_name in sys.modules:
module_or_name = sys.modules[module_or_name]
if isinstance(module_or_name, ModuleType):
module = module_or_name
loader = getattr(module, '__loader__', None)
if loader is not None:
return loader
fullname = module.__name__
else:
fullname = module_or_name
return find_loader(fullname)
def find_loader(fullname):
"""Find a PEP 302 "loader" object for fullname
If fullname contains dots, path must be the containing package's __path__.
Returns None if the module cannot be found or imported. This function uses
iter_importers(), and is thus subject to the same limitations regarding
platform-specific special import locations such as the Windows registry.
"""
for importer in iter_importers(fullname):
loader = importer.find_module(fullname)
if loader is not None:
return loader
return None
def extend_path(path, name):
"""Extend a package's path.
Intended use is to place the following code in a package's __init__.py:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
This will add to the package's __path__ all subdirectories of
directories on sys.path named after the package. This is useful
if one wants to distribute different parts of a single logical
package as multiple directories.
It also looks for *.pkg files beginning where * matches the name
argument. This feature is similar to *.pth files (see site.py),
except that it doesn't special-case lines starting with 'import'.
A *.pkg file is trusted at face value: apart from checking for
duplicates, all entries found in a *.pkg file are added to the
path, regardless of whether they are exist the filesystem. (This
is a feature.)
If the input path is not a list (as is the case for frozen
packages) it is returned unchanged. The input path is not
modified; an extended copy is returned. Items are only appended
to the copy at the end.
It is assumed that sys.path is a sequence. Items of sys.path that
are not (unicode or 8-bit) strings referring to existing
directories are ignored. Unicode items of sys.path that cause
errors when used as filenames may cause this function to raise an
exception (in line with os.path.isdir() behavior).
"""
if not isinstance(path, list):
# This could happen e.g. when this is called from inside a
# frozen package. Return the path unchanged in that case.
return path
pname = os.path.join(*name.split('.')) # Reconstitute as relative path
# Just in case os.extsep != '.'
sname = os.extsep.join(name.split('.'))
sname_pkg = sname + os.extsep + "pkg"
init_py = "__init__" + os.extsep + "py"
path = path[:] # Start with a copy of the existing path
for dir in sys.path:
if not isinstance(dir, basestring) or not os.path.isdir(dir):
continue
subdir = os.path.join(dir, pname)
# XXX This may still add duplicate entries to path on
# case-insensitive filesystems
initfile = os.path.join(subdir, init_py)
if subdir not in path and os.path.isfile(initfile):
path.append(subdir)
# XXX Is this the right thing for subpackages like zope.app?
# It looks for a file named "zope.app.pkg"
pkgfile = os.path.join(dir, sname_pkg)
if os.path.isfile(pkgfile):
try:
f = open(pkgfile)
except IOError, msg:
sys.stderr.write("Can't open %s: %s\n" %
(pkgfile, msg))
else:
for line in f:
line = line.rstrip('\n')
if not line or line.startswith('#'):
continue
path.append(line) # Don't check for existence!
f.close()
return path
def get_data(package, resource):
"""Get a resource from a package.
This is a wrapper round the PEP 302 loader get_data API. The package
argument should be the name of a package, in standard module format
(foo.bar). The resource argument should be in the form of a relative
filename, using '/' as the path separator. The parent directory name '..'
is not allowed, and nor is a rooted name (starting with a '/').
The function returns a binary string, which is the contents of the
specified resource.
For packages located in the filesystem, which have already been imported,
this is the rough equivalent of
d = os.path.dirname(sys.modules[package].__file__)
data = open(os.path.join(d, resource), 'rb').read()
If the package cannot be located or loaded, or it uses a PEP 302 loader
which does not support get_data(), then None is returned.
"""
loader = get_loader(package)
if loader is None or not hasattr(loader, 'get_data'):
return None
mod = sys.modules.get(package) or loader.load_module(package)
if mod is None or not hasattr(mod, '__file__'):
return None
# Modify the resource name to be compatible with the loader.get_data
# signature - an os.path format "filename" starting with the dirname of
# the package's __file__
parts = resource.split('/')
parts.insert(0, os.path.dirname(mod.__file__))
resource_name = os.path.join(*parts)
return loader.get_data(resource_name)
+6 -1
View File
@@ -1,5 +1,5 @@
import sys
import os
import sys
IS_PY3K = False
@@ -34,3 +34,8 @@ def deserialize(base,
base.read(protocol)
return base
if IS_PY3K:
pass
else:
pass
+15 -2
View File
@@ -1,10 +1,11 @@
__author__ = 'traff'
import threading
import os
import sys
import tempfile
from _prof_imports import Stats, FuncStat, Function
import threading
from _prof_imports import pkgutil, Stats, FuncStat, Function
try:
execfile=execfile #Not in Py3k
@@ -42,6 +43,18 @@ def save_main_module(file, module_name):
return m
def get_fullname(mod_name):
try:
loader = pkgutil.get_loader(mod_name)
except:
return None
if loader is not None:
for attr in ("get_filename", "_get_filename"):
meth = getattr(loader, attr, None)
if meth is not None:
return meth(mod_name)
return None
class ProfDaemonThread(threading.Thread):
def __init__(self):
+10 -1
View File
@@ -8,7 +8,7 @@ from socket import socket
from _prof_imports import ProfilerResponse
from prof_io import ProfWriter, ProfReader
from prof_util import generate_snapshot_filepath, stats_to_response, get_snapshot_basepath, save_main_module, execfile
from prof_util import generate_snapshot_filepath, stats_to_response, get_snapshot_basepath, save_main_module, execfile, get_fullname
base_snapshot_path = os.getenv('PYCHARM_SNAPSHOT_PATH')
remote_run = bool(os.getenv('PYCHARM_REMOTE_RUN', ''))
@@ -145,6 +145,15 @@ if __name__ == '__main__':
port = int(sys.argv[2])
file = sys.argv[3]
if file == '-m':
module_name = sys.argv[4]
filename = get_fullname(module_name)
if filename is None:
sys.stderr.write("No module named %s\n" % module_name)
sys.exit(1)
else:
file = filename
del sys.argv[0]
del sys.argv[0]
del sys.argv[0]
@@ -34,5 +34,8 @@ public interface PythonRunConfigurationParams {
boolean emulateTerminal();
void setEmulateTerminal(boolean emulateTerminal);
boolean isModuleMode();
void setModuleMode(boolean moduleMode);
}
@@ -827,6 +827,7 @@ runcfg.test.description=Python frameworks supported by PyCharm
runcfg.unittest.display_name=Unittests
runcfg.unittest.description=Python's unittest run configuration
runcfg.unittest.no_script_name=Please specify script name
runcfg.unittest.no_module_name=Please specify module name
runcfg.unittest.no_class_name=Please specify class name
runcfg.unittest.no_method_name=Please specify method name
runcfg.unittest.no_folder_name=Please specify folder with tests
@@ -850,7 +851,7 @@ runcfg.unittest.dlg.select.folder.path=Select folder path:
runcfg.unittest.dlg.select.script.path=Select script path:
runcfg.unittest.dlg.interpreter_options_title=Interpreter options:
runcfg.unittest.dlg.messages.working.dir=Working directory:
runcfg.labels.script_parameters=Script &parameters:
runcfg.labels.script_parameters=&Parameters:
runcfg.labels.script=&Script:
runcfg.labels.environment_variables=&Environment variables:
runcfg.labels.interpreter=&Use specified interpreter:
@@ -1049,4 +1050,5 @@ smartKeys.insert.backslash.in.statement.on.enter=Insert backslash when pressing
smartKeys.insert.self.in.method=Insert 'self' when defining a method
smartKeys.insert.type.placeholder.in.docstring.stub=Insert type placeholders in the documentation comment stub
show.expression.type.no.expression.found=No expression found
show.expression.type.no.expression.found=No expression found
runcfg.labels.module=Module:
@@ -232,34 +232,22 @@ public class PyDebugRunner extends GenericProgramRunner {
}
public CommandLinePatcher[] createCommandLinePatchers(final Project project, final PythonCommandLineState state,
RunProfile profile,
final int serverLocalPort) {
RunProfile profile,
final int serverLocalPort) {
return new CommandLinePatcher[]{createDebugServerPatcher(project, state, serverLocalPort), createRunConfigPatcher(state, profile)};
}
private CommandLinePatcher createDebugServerPatcher(final Project project,
final PythonCommandLineState pyState,
final int serverLocalPort) {
final PythonCommandLineState pyState,
final int serverLocalPort) {
return new CommandLinePatcher() {
private void patchExeParams(ParametersList parametersList) {
// we should remove '-m' parameter, but notify debugger of it
// but we can't remove one parameter from group, so we create new parameters group
ParamsGroup newExeParams = new ParamsGroup(PythonCommandLineState.GROUP_EXE_OPTIONS);
int exeParamsIndex = parametersList.getParamsGroups().indexOf(
parametersList.getParamsGroup(PythonCommandLineState.GROUP_EXE_OPTIONS));
ParamsGroup exeParamsOld = parametersList.removeParamsGroup(exeParamsIndex);
isModule = false;
for (String param : exeParamsOld.getParameters()) {
if (!param.equals("-m")) {
newExeParams.addParameter(param);
}
else {
isModule = true;
}
}
parametersList.addParamsGroupAt(exeParamsIndex, newExeParams);
handleModuleMode(parametersList, PythonCommandLineState.GROUP_SCRIPT);
}
@@ -290,6 +278,24 @@ public class PyDebugRunner extends GenericProgramRunner {
};
}
private void handleModuleMode(ParametersList parametersList, String groupId) {
ParamsGroup newExeParams = new ParamsGroup(groupId);
int exeParamsIndex = parametersList.getParamsGroups().indexOf(
parametersList.getParamsGroup(groupId));
ParamsGroup exeParamsOld = parametersList.removeParamsGroup(exeParamsIndex);
for (String param : exeParamsOld.getParameters()) {
if (!param.equals("-m")) {
newExeParams.addParameter(param);
}
else {
isModule = true;
}
}
parametersList.addParamsGroupAt(exeParamsIndex, newExeParams);
}
private void fillDebugParameters(@NotNull Project project,
@NotNull ParamsGroup debugParams,
int serverLocalPort,
@@ -47,11 +47,13 @@ public class PythonRunConfiguration extends AbstractPythonRunConfiguration
public static final String MULTIPROCESS = "MULTIPROCESS";
public static final String SHOW_COMMAND_LINE = "SHOW_COMMAND_LINE";
public static final String EMULATE_TERMINAL = "EMULATE_TERMINAL";
public static final String MODULE_MODE = "MODULE_MODE";
private String myScriptName;
private String myScriptParameters;
private boolean myShowCommandLineAfterwards = false;
private boolean myEmulateTerminal = false;
private boolean myModuleMode = false;
protected PythonRunConfiguration(Project project, ConfigurationFactory configurationFactory) {
super(project, configurationFactory);
@@ -71,7 +73,8 @@ public class PythonRunConfiguration extends AbstractPythonRunConfiguration
super.checkConfiguration();
if (StringUtil.isEmptyOrSpaces(myScriptName)) {
throw new RuntimeConfigurationException(PyBundle.message("runcfg.unittest.no_script_name"));
throw new RuntimeConfigurationException(
PyBundle.message(isModuleMode() ? "runcfg.unittest.no_module_name" : "runcfg.unittest.no_script_name"));
}
}
@@ -125,6 +128,7 @@ public class PythonRunConfiguration extends AbstractPythonRunConfiguration
myScriptParameters = JDOMExternalizerUtil.readField(element, PARAMETERS);
myShowCommandLineAfterwards = Boolean.parseBoolean(JDOMExternalizerUtil.readField(element, SHOW_COMMAND_LINE, "false"));
myEmulateTerminal = Boolean.parseBoolean(JDOMExternalizerUtil.readField(element, EMULATE_TERMINAL, "false"));
myModuleMode = Boolean.parseBoolean(JDOMExternalizerUtil.readField(element, MODULE_MODE, "false"));
}
public void writeExternal(Element element) throws WriteExternalException {
@@ -133,6 +137,7 @@ public class PythonRunConfiguration extends AbstractPythonRunConfiguration
JDOMExternalizerUtil.writeField(element, PARAMETERS, myScriptParameters);
JDOMExternalizerUtil.writeField(element, SHOW_COMMAND_LINE, Boolean.toString(myShowCommandLineAfterwards));
JDOMExternalizerUtil.writeField(element, EMULATE_TERMINAL, Boolean.toString(myEmulateTerminal));
JDOMExternalizerUtil.writeField(element, MODULE_MODE, Boolean.toString(myModuleMode));
}
public AbstractPythonRunConfigurationParams getBaseParams() {
@@ -141,6 +146,7 @@ public class PythonRunConfiguration extends AbstractPythonRunConfiguration
public static void copyParams(PythonRunConfigurationParams source, PythonRunConfigurationParams target) {
AbstractPythonRunConfiguration.copyParams(source.getBaseParams(), target.getBaseParams());
target.setModuleMode(source.isModuleMode());
target.setScriptName(source.getScriptName());
target.setScriptParameters(source.getScriptParameters());
target.setShowCommandLineAfterwards(source.showCommandLineAfterwards());
@@ -175,4 +181,14 @@ public class PythonRunConfiguration extends AbstractPythonRunConfiguration
}
return null;
}
@Override
public boolean isModuleMode() {
return myModuleMode;
}
@Override
public void setModuleMode(boolean moduleMode) {
myModuleMode = moduleMode;
}
}
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="com.jetbrains.python.run.PythonRunConfigurationForm">
<grid id="27dc6" binding="myRootPanel" layout-manager="GridLayoutManager" row-count="7" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<grid id="27dc6" binding="myRootPanel" layout-manager="GridLayoutManager" row-count="8" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="20" y="20" width="507" height="400"/>
@@ -8,32 +8,96 @@
<properties/>
<border type="none"/>
<children>
<component id="20d07" class="javax.swing.JLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="com/jetbrains/python/PyBundle" key="runcfg.labels.script"/>
</properties>
</component>
<component id="ae354" class="com.intellij.ui.components.JBLabel" binding="myScriptParametersLabel">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
<grid row="2" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<labelFor value=""/>
<text resource-bundle="com/jetbrains/python/PyBundle" key="runcfg.labels.script_parameters"/>
</properties>
</component>
<component id="4b96a" class="com.intellij.openapi.ui.TextFieldWithBrowseButton" binding="myScriptTextField">
<vspacer id="f8c96">
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="1" hsize-policy="7" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
<grid row="7" column="1" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
</vspacer>
<grid id="9b4b8" binding="myCommonOptionsPlaceholder" layout-manager="BorderLayout" hgap="0" vgap="0">
<constraints>
<grid row="3" column="0" row-span="1" col-span="2" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children/>
</grid>
<grid id="89eba" layout-manager="BorderLayout" hgap="0" vgap="0">
<constraints>
<grid row="4" column="0" row-span="1" col-span="2" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children/>
</grid>
<component id="d70ad" class="com.intellij.ui.components.JBCheckBox" binding="myEmulateTerminalCheckbox">
<constraints>
<grid row="5" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<selected value="true"/>
<text value="Emulate terminal in output console"/>
</properties>
</component>
<component id="99b13" class="com.intellij.ui.components.JBCheckBox" binding="myShowCommandLineCheckbox">
<constraints>
<grid row="6" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<selected value="true"/>
<text value="Show command line afterwards"/>
</properties>
</component>
<component id="f3803" class="com.intellij.openapi.ui.ComboBox" binding="myTargetComboBox">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="2" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<model>
<item value="Script path"/>
<item value="Module name"/>
</model>
</properties>
</component>
<grid id="e2419" layout-manager="GridLayoutManager" row-count="2" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="4b96a" class="com.intellij.openapi.ui.TextFieldWithBrowseButton" binding="myScriptTextField">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="1" hsize-policy="7" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
</component>
<component id="4bd06" class="com.intellij.ui.RawCommandLineEditor" binding="myModuleField">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
<preferred-size width="150" height="-1"/>
</grid>
</constraints>
<properties>
<dialogCaption resource-bundle="com/jetbrains/python/PyBundle" key="runcfg.captions.script_parameters_dialog"/>
<text value=""/>
<visible value="false"/>
</properties>
</component>
</children>
</grid>
<component id="9c0aa" class="com.intellij.ui.RawCommandLineEditor" binding="myScriptParametersTextField">
<constraints>
<grid row="1" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
<grid row="2" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
<preferred-size width="150" height="-1"/>
</grid>
</constraints>
@@ -42,45 +106,6 @@
<text value=""/>
</properties>
</component>
<vspacer id="f8c96">
<constraints>
<grid row="6" column="1" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
</vspacer>
<grid id="9b4b8" binding="myCommonOptionsPlaceholder" layout-manager="BorderLayout" hgap="0" vgap="0">
<constraints>
<grid row="2" column="0" row-span="1" col-span="2" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children/>
</grid>
<grid id="89eba" layout-manager="BorderLayout" hgap="0" vgap="0">
<constraints>
<grid row="3" column="0" row-span="1" col-span="2" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children/>
</grid>
<component id="99b13" class="com.intellij.ui.components.JBCheckBox" binding="myShowCommandLineCheckbox">
<constraints>
<grid row="5" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<selected value="true"/>
<text value="Show command line afterwards"/>
</properties>
</component>
<component id="d70ad" class="com.intellij.ui.components.JBCheckBox" binding="myEmulateTerminalCheckbox">
<constraints>
<grid row="4" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<selected value="true"/>
<text value="Emulate terminal in output console"/>
</properties>
</component>
</children>
</grid>
</form>
@@ -17,12 +17,14 @@ package com.jetbrains.python.run;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.ui.ComponentWithBrowseButton;
import com.intellij.openapi.ui.TextComponentAccessor;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.PanelWithAnchor;
import com.intellij.ui.RawCommandLineEditor;
@@ -33,7 +35,6 @@ import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
/**
@@ -50,6 +51,9 @@ public class PythonRunConfigurationForm implements PythonRunConfigurationParams,
private final Project myProject;
private JBCheckBox myShowCommandLineCheckbox;
private JBCheckBox myEmulateTerminalCheckbox;
private RawCommandLineEditor myModuleField;
private ComboBox myTargetComboBox;
private boolean myModuleMode;
public PythonRunConfigurationForm(PythonRunConfiguration configuration) {
myCommonOptionsForm = PyCommonOptionsFormFactory.getInstance().createForm(configuration.getCommonOptionsFormData());
@@ -86,16 +90,32 @@ public class PythonRunConfigurationForm implements PythonRunConfigurationParams,
emulateTerminalEnabled(false);
}
myTargetComboBox.setSelectedIndex(0);
myEmulateTerminalCheckbox.setSelected(false);
myEmulateTerminalCheckbox.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
updateShowCommandLineEnabled();
}
});
myEmulateTerminalCheckbox.addChangeListener(
(ChangeEvent e) -> updateShowCommandLineEnabled());
setAnchor(myCommonOptionsForm.getAnchor());
myTargetComboBox.addActionListener(e -> updateRunModuleMode());
}
private void updateRunModuleMode() {
boolean mode = myTargetComboBox.getSelectedIndex() == 1;
checkTargetComboConsistency(mode);
setModuleModeInternal(mode);
}
private void checkTargetComboConsistency(boolean mode) {
Object item = myTargetComboBox.getSelectedItem();
if (item == null) {
throw new IllegalArgumentException("item is null");
}
else //noinspection StringToUpperCaseOrToLowerCaseWithoutLocale
if (mode && !item.toString().toLowerCase().contains("module")) {
throw new IllegalArgumentException("This option should refer to a module");
}
}
private void updateShowCommandLineEnabled() {
@@ -118,12 +138,22 @@ public class PythonRunConfigurationForm implements PythonRunConfigurationParams,
@Override
public String getScriptName() {
return FileUtil.toSystemIndependentName(myScriptTextField.getText().trim());
if (isModuleMode()) {
return myModuleField.getText().trim();
}
else {
return FileUtil.toSystemIndependentName(myScriptTextField.getText().trim());
}
}
@Override
public void setScriptName(String scriptName) {
myScriptTextField.setText(scriptName == null ? "" : FileUtil.toSystemDependentName(scriptName));
if (isModuleMode()) {
myModuleField.setText(StringUtil.notNullize(scriptName));
}
else {
myScriptTextField.setText(scriptName == null ? "" : FileUtil.toSystemDependentName(scriptName));
}
}
@Override
@@ -156,6 +186,11 @@ public class PythonRunConfigurationForm implements PythonRunConfigurationParams,
myEmulateTerminalCheckbox.setSelected(emulateTerminal);
}
@Override
public boolean isModuleMode() {
return myModuleMode;
}
@Override
public JComponent getAnchor() {
return anchor;
@@ -174,4 +209,17 @@ public class PythonRunConfigurationForm implements PythonRunConfigurationParams,
myScriptParametersLabel.setAnchor(anchor);
myCommonOptionsForm.setAnchor(anchor);
}
@Override
public void setModuleMode(boolean moduleMode) {
myTargetComboBox.setSelectedIndex(moduleMode ? 1 : 0);
checkTargetComboConsistency(moduleMode);
}
private void setModuleModeInternal(boolean moduleMode) {
myModuleMode = moduleMode;
myScriptTextField.setVisible(!moduleMode);
myModuleField.setVisible(moduleMode);
}
}
@@ -156,18 +156,23 @@ public class PythonScriptCommandLineState extends PythonCommandLineState {
@Override
protected void buildCommandLineParameters(GeneralCommandLine commandLine) {
ParametersList parametersList = commandLine.getParametersList();
ParamsGroup exe_options = parametersList.getParamsGroup(GROUP_EXE_OPTIONS);
assert exe_options != null;
exe_options.addParametersString(myConfig.getInterpreterOptions());
ParamsGroup exeOptions = parametersList.getParamsGroup(GROUP_EXE_OPTIONS);
assert exeOptions != null;
exeOptions.addParametersString(myConfig.getInterpreterOptions());
ParamsGroup script_parameters = parametersList.getParamsGroup(GROUP_SCRIPT);
assert script_parameters != null;
if (!StringUtil.isEmptyOrSpaces(myConfig.getScriptName())) {
script_parameters.addParameter(myConfig.getScriptName());
ParamsGroup scriptParameters = parametersList.getParamsGroup(GROUP_SCRIPT);
assert scriptParameters != null;
if (myConfig.isModuleMode()) {
scriptParameters.addParameter("-m");
}
final String script_options_string = myConfig.getScriptParameters();
if (script_options_string != null) script_parameters.addParametersString(script_options_string);
if (!StringUtil.isEmptyOrSpaces(myConfig.getScriptName())) {
scriptParameters.addParameter(myConfig.getScriptName());
}
final String scriptOptionsString = myConfig.getScriptParameters();
if (scriptOptionsString != null) scriptParameters.addParametersString(scriptOptionsString);
if (!StringUtil.isEmptyOrSpaces(myConfig.getWorkingDirectory())) {
commandLine.setWorkDirectory(myConfig.getWorkingDirectory());