mirror of
https://github.com/xonsh/xonsh.git
synced 2025-03-04 08:24:40 +01:00
Run black
on all bundled xontribs
This commit is contained in:
parent
943db337e5
commit
258c2fc610
9 changed files with 235 additions and 156 deletions
|
@ -14,10 +14,10 @@ __all__ = ()
|
|||
@events.on_transform_command
|
||||
def bash_preproc(cmd, **kw):
|
||||
bang_previous = {
|
||||
'!': lambda x: x,
|
||||
'$': lambda x: shlex.split(x)[-1],
|
||||
'^': lambda x: shlex.split(x)[0],
|
||||
'*': lambda x: ' '.join(shlex.split(x)[1:]),
|
||||
"!": lambda x: x,
|
||||
"$": lambda x: shlex.split(x)[-1],
|
||||
"^": lambda x: shlex.split(x)[0],
|
||||
"*": lambda x: " ".join(shlex.split(x)[1:]),
|
||||
}
|
||||
|
||||
def replace_bang(m):
|
||||
|
@ -30,7 +30,7 @@ def bash_preproc(cmd, **kw):
|
|||
return bang_previous[arg](inputs[-1])
|
||||
except IndexError:
|
||||
print("xonsh: no history for '!{}'".format(arg))
|
||||
return ''
|
||||
return ""
|
||||
|
||||
# Look back in history for a matching command.
|
||||
else:
|
||||
|
@ -38,14 +38,14 @@ def bash_preproc(cmd, **kw):
|
|||
return next((x for x in reversed(inputs) if x.startswith(arg)))
|
||||
except StopIteration:
|
||||
print("xonsh: no previous commands match '!{}'".format(arg))
|
||||
return ''
|
||||
return ""
|
||||
|
||||
return re.sub(r'!([!$^*]|[\w]+)', replace_bang, cmd.strip())
|
||||
return re.sub(r"!([!$^*]|[\w]+)", replace_bang, cmd.strip())
|
||||
|
||||
|
||||
@events.on_ptk_create
|
||||
def custom_keybindings(bindings, **kw):
|
||||
if ptk_shell_type() == 'prompt_toolkit2':
|
||||
if ptk_shell_type() == "prompt_toolkit2":
|
||||
handler = bindings.add
|
||||
else:
|
||||
handler = bindings.registry.add_binding
|
||||
|
@ -56,7 +56,7 @@ def custom_keybindings(bindings, **kw):
|
|||
def last_command_exists():
|
||||
return len(__xonsh__.history) > 0
|
||||
|
||||
@handler(Keys.Escape, '.', filter=last_command_exists & insert_mode)
|
||||
@handler(Keys.Escape, ".", filter=last_command_exists & insert_mode)
|
||||
def recall_last_arg(event):
|
||||
arg = __xonsh__.history[-1].cmd.split()[-1]
|
||||
event.current_buffer.insert_text(arg)
|
||||
|
@ -67,21 +67,21 @@ def alias(args, stdin=None):
|
|||
|
||||
if args:
|
||||
for arg in args:
|
||||
if '=' in arg:
|
||||
if "=" in arg:
|
||||
# shlex.split to remove quotes, e.g. "foo='echo hey'" into
|
||||
# "foo=echo hey"
|
||||
name, cmd = shlex.split(arg)[0].split('=', 1)
|
||||
name, cmd = shlex.split(arg)[0].split("=", 1)
|
||||
aliases[name] = shlex.split(cmd)
|
||||
elif arg in aliases:
|
||||
print('{}={}'.format(arg, aliases[arg]))
|
||||
print("{}={}".format(arg, aliases[arg]))
|
||||
else:
|
||||
print("alias: {}: not found".format(arg), file=sys.stderr)
|
||||
ret = 1
|
||||
else:
|
||||
for alias, cmd in aliases.items():
|
||||
print('{}={}'.format(alias, cmd))
|
||||
print("{}={}".format(alias, cmd))
|
||||
|
||||
return ret
|
||||
|
||||
|
||||
aliases['alias'] = alias
|
||||
aliases["alias"] = alias
|
||||
|
|
|
@ -22,9 +22,9 @@ from xonsh.xoreutils.yes import yes
|
|||
|
||||
__all__ = ()
|
||||
|
||||
aliases['cat'] = cat
|
||||
aliases['echo'] = echo
|
||||
aliases['pwd'] = pwd
|
||||
aliases['tee'] = tee
|
||||
aliases['tty'] = tty
|
||||
aliases['yes'] = yes
|
||||
aliases["cat"] = cat
|
||||
aliases["echo"] = echo
|
||||
aliases["pwd"] = pwd
|
||||
aliases["tee"] = tee
|
||||
aliases["tty"] = tty
|
||||
aliases["yes"] = yes
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
"""Hooks for the distributed parallel computing library."""
|
||||
from xonsh.contexts import Functor
|
||||
|
||||
__all__ = 'DSubmitter', 'dsubmit'
|
||||
__all__ = "DSubmitter", "dsubmit"
|
||||
|
||||
|
||||
def dworker(args, stdin=None):
|
||||
|
@ -9,10 +9,11 @@ def dworker(args, stdin=None):
|
|||
workers that also have access to xonsh builtins.
|
||||
"""
|
||||
from distributed.cli import dworker
|
||||
dworker.main.main(args=args, prog_name='dworker', standalone_mode=False)
|
||||
|
||||
dworker.main.main(args=args, prog_name="dworker", standalone_mode=False)
|
||||
|
||||
|
||||
aliases['dworker'] = dworker
|
||||
aliases["dworker"] = dworker
|
||||
|
||||
|
||||
class DSubmitter(Functor):
|
||||
|
@ -44,7 +45,7 @@ class DSubmitter(Functor):
|
|||
return res
|
||||
|
||||
|
||||
def dsubmit(*a, args=(), kwargs=None, rtn='', **kw):
|
||||
def dsubmit(*a, args=(), kwargs=None, rtn="", **kw):
|
||||
"""Returns a distributed submission context manager, DSubmitter(),
|
||||
with a new executor instance.
|
||||
|
||||
|
@ -66,6 +67,7 @@ def dsubmit(*a, args=(), kwargs=None, rtn='', **kw):
|
|||
An instance of the DSubmitter context manager.
|
||||
"""
|
||||
from distributed import Executor
|
||||
|
||||
e = Executor(*a, **kw)
|
||||
dsub = DSubmitter(e, args=args, kwargs=kwargs, rtn=rtn)
|
||||
return dsub
|
||||
|
|
|
@ -36,13 +36,14 @@ def _cwd_release_wrapper(func):
|
|||
the workdir to the users home directory.
|
||||
"""
|
||||
env = builtins.__xonsh__.env
|
||||
if env.get('UPDATE_PROMPT_ON_KEYPRESS'):
|
||||
return func if not hasattr(func, '_orgfunc') else func._orgfunc
|
||||
if env.get("UPDATE_PROMPT_ON_KEYPRESS"):
|
||||
return func if not hasattr(func, "_orgfunc") else func._orgfunc
|
||||
|
||||
if hasattr(func, '_orgfunc'):
|
||||
if hasattr(func, "_orgfunc"):
|
||||
# Already wrapped
|
||||
return func
|
||||
else:
|
||||
|
||||
@functools.wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
anchor = Path(os.getcwd()).anchor
|
||||
|
@ -51,14 +52,15 @@ def _cwd_release_wrapper(func):
|
|||
out = func(*args, **kwargs)
|
||||
finally:
|
||||
try:
|
||||
pwd = env.get('PWD', anchor)
|
||||
pwd = env.get("PWD", anchor)
|
||||
os.chdir(pwd)
|
||||
except (FileNotFoundError, NotADirectoryError):
|
||||
print_exception()
|
||||
newpath = _chdir_up(pwd)
|
||||
builtins.__xonsh__.env['PWD'] = newpath
|
||||
builtins.__xonsh__.env["PWD"] = newpath
|
||||
raise KeyboardInterrupt
|
||||
return out
|
||||
|
||||
wrapper._orgfunc = func
|
||||
return wrapper
|
||||
|
||||
|
@ -69,20 +71,22 @@ def _cwd_restore_wrapper(func):
|
|||
prompt_toolkit or readline.
|
||||
"""
|
||||
env = builtins.__xonsh__.env
|
||||
if env.get('UPDATE_PROMPT_ON_KEYPRESS'):
|
||||
return func if not hasattr(func, '_orgfunc') else func._orgfunc
|
||||
if env.get("UPDATE_PROMPT_ON_KEYPRESS"):
|
||||
return func if not hasattr(func, "_orgfunc") else func._orgfunc
|
||||
|
||||
if hasattr(func, '_orgfunc'):
|
||||
if hasattr(func, "_orgfunc"):
|
||||
# Already wrapped
|
||||
return func
|
||||
else:
|
||||
|
||||
@functools.wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
workdir = os.getcwd()
|
||||
_chdir_up(env.get('PWD', workdir))
|
||||
_chdir_up(env.get("PWD", workdir))
|
||||
out = func(*args, **kwargs)
|
||||
_chdir_up(workdir)
|
||||
return out
|
||||
|
||||
wrapper._orgfunc = func
|
||||
return wrapper
|
||||
|
||||
|
@ -93,4 +97,6 @@ def setup_release_cwd_hook(prompter, history, completer, bindings, **kw):
|
|||
prompter.prompt = _cwd_release_wrapper(prompter.prompt)
|
||||
if completer.completer:
|
||||
# Temporarily restore cwd for callbacks to the completer
|
||||
completer.completer.complete = _cwd_restore_wrapper(completer.completer.complete)
|
||||
completer.completer.complete = _cwd_restore_wrapper(
|
||||
completer.completer.complete
|
||||
)
|
||||
|
|
|
@ -13,10 +13,11 @@ __all__ = ()
|
|||
def mpl(args, stdin=None):
|
||||
"""Hooks to matplotlib"""
|
||||
from xontrib.mplhooks import show
|
||||
|
||||
show()
|
||||
|
||||
|
||||
aliases['mpl'] = mpl
|
||||
aliases["mpl"] = mpl
|
||||
|
||||
|
||||
@lazyobject
|
||||
|
@ -31,8 +32,9 @@ def pylab_helpers():
|
|||
@events.on_import_post_exec_module
|
||||
def interactive_pyplot(module=None, **kwargs):
|
||||
"""This puts pyplot in interactive mode once it is imported."""
|
||||
if module.__name__ != 'matplotlib.pyplot' or \
|
||||
not __xonsh__.env.get('XONSH_INTERACTIVE'):
|
||||
if module.__name__ != "matplotlib.pyplot" or not __xonsh__.env.get(
|
||||
"XONSH_INTERACTIVE"
|
||||
):
|
||||
return
|
||||
# Since we are in interactive mode, let's monkey-patch plt.show
|
||||
# to try to never block.
|
||||
|
|
|
@ -46,7 +46,9 @@ def figure_to_rgb_array(fig, shape=None):
|
|||
|
||||
Note: the method will throw an exception if the given shape is wrong.
|
||||
"""
|
||||
array = np.frombuffer(_get_buffer(fig, dpi=fig.dpi, format='raw').read(), dtype='uint8')
|
||||
array = np.frombuffer(
|
||||
_get_buffer(fig, dpi=fig.dpi, format="raw").read(), dtype="uint8"
|
||||
)
|
||||
if shape is None:
|
||||
w, h = fig.canvas.get_width_height()
|
||||
shape = (h, w, 4)
|
||||
|
@ -81,7 +83,7 @@ def figure_to_tight_array(fig, width, height, minimal=True):
|
|||
dpi = dpi_fig
|
||||
subplotpars = {
|
||||
k: getattr(fig.subplotpars, k)
|
||||
for k in ['wspace', 'hspace', 'bottom', 'top', 'left', 'right']
|
||||
for k in ["wspace", "hspace", "bottom", "top", "left", "right"]
|
||||
}
|
||||
|
||||
# set the figure dimensions to the terminal size
|
||||
|
@ -95,8 +97,8 @@ def figure_to_tight_array(fig, width, height, minimal=True):
|
|||
fig.subplots_adjust(bottom=1 / height, top=1 - 1 / height, left=0, right=1)
|
||||
|
||||
# reduce font size in order to reduce text impact on the image
|
||||
font_size = matplotlib.rcParams['font.size']
|
||||
matplotlib.rcParams.update({'font.size': 0})
|
||||
font_size = matplotlib.rcParams["font.size"]
|
||||
matplotlib.rcParams.update({"font.size": 0})
|
||||
else:
|
||||
dpi = min([width * fig.dpi // w, height * fig.dpi // h])
|
||||
fig.dpi = dpi
|
||||
|
@ -108,7 +110,7 @@ def figure_to_tight_array(fig, width, height, minimal=True):
|
|||
if minimal:
|
||||
# cleanup after tight layout
|
||||
# clean up rcParams
|
||||
matplotlib.rcParams.update({'font.size': font_size})
|
||||
matplotlib.rcParams.update({"font.size": font_size})
|
||||
|
||||
# reset the axis positions and figure dimensions
|
||||
fig.set_size_inches(w / dpi, h / dpi, forward=True)
|
||||
|
@ -121,8 +123,8 @@ def figure_to_tight_array(fig, width, height, minimal=True):
|
|||
|
||||
def buf_to_color_str(buf):
|
||||
"""Converts an RGB array to a xonsh color string."""
|
||||
space = ' '
|
||||
pix = '{{bg#{0:02x}{1:02x}{2:02x}}} '
|
||||
space = " "
|
||||
pix = "{{bg#{0:02x}{1:02x}{2:02x}}} "
|
||||
pixels = []
|
||||
for h in range(buf.shape[0]):
|
||||
last = None
|
||||
|
@ -133,9 +135,9 @@ def buf_to_color_str(buf):
|
|||
else:
|
||||
pixels.append(pix.format(*rgb))
|
||||
last = rgb
|
||||
pixels.append('{NO_COLOR}\n')
|
||||
pixels.append("{NO_COLOR}\n")
|
||||
pixels[-1] = pixels[-1].rstrip()
|
||||
return ''.join(pixels)
|
||||
return "".join(pixels)
|
||||
|
||||
|
||||
def display_figure_with_iterm2(fig):
|
||||
|
@ -146,13 +148,13 @@ def display_figure_with_iterm2(fig):
|
|||
fig : matplotlib.figure.Figure
|
||||
the figure to be plotted
|
||||
"""
|
||||
print(display_image_bytes(_get_buffer(fig, format='png', dpi=fig.dpi).read()))
|
||||
print(display_image_bytes(_get_buffer(fig, format="png", dpi=fig.dpi).read()))
|
||||
|
||||
|
||||
def show():
|
||||
'''Run the mpl display sequence by printing the most recent figure to console'''
|
||||
"""Run the mpl display sequence by printing the most recent figure to console"""
|
||||
try:
|
||||
minimal = __xonsh__.env['XONTRIB_MPL_MINIMAL']
|
||||
minimal = __xonsh__.env["XONTRIB_MPL_MINIMAL"]
|
||||
except KeyError:
|
||||
minimal = XONTRIB_MPL_MINIMAL_DEFAULT
|
||||
fig = plt.gcf()
|
||||
|
|
169
xontrib/vox.py
169
xontrib/vox.py
|
@ -13,20 +13,25 @@ class VoxHandler:
|
|||
|
||||
def parser():
|
||||
from argparse import ArgumentParser
|
||||
parser = ArgumentParser(prog='vox', description=__doc__)
|
||||
subparsers = parser.add_subparsers(dest='command')
|
||||
|
||||
parser = ArgumentParser(prog="vox", description=__doc__)
|
||||
subparsers = parser.add_subparsers(dest="command")
|
||||
|
||||
create = subparsers.add_parser(
|
||||
'new', aliases=['create'],
|
||||
help='Create a new virtual environment in $VIRTUALENV_HOME'
|
||||
"new",
|
||||
aliases=["create"],
|
||||
help="Create a new virtual environment in $VIRTUALENV_HOME",
|
||||
)
|
||||
create.add_argument('name', metavar='ENV',
|
||||
help='The environments to create')
|
||||
create.add_argument("name", metavar="ENV", help="The environments to create")
|
||||
|
||||
create.add_argument('--system-site-packages', default=False,
|
||||
action='store_true', dest='system_site_packages',
|
||||
help='Give the virtual environment access to the '
|
||||
'system site-packages dir.')
|
||||
create.add_argument(
|
||||
"--system-site-packages",
|
||||
default=False,
|
||||
action="store_true",
|
||||
dest="system_site_packages",
|
||||
help="Give the virtual environment access to the "
|
||||
"system site-packages dir.",
|
||||
)
|
||||
|
||||
create.add_argument(
|
||||
"-p",
|
||||
|
@ -41,54 +46,85 @@ class VoxHandler:
|
|||
)
|
||||
|
||||
from xonsh.platform import ON_WINDOWS
|
||||
|
||||
group = create.add_mutually_exclusive_group()
|
||||
group.add_argument('--symlinks', default=not ON_WINDOWS,
|
||||
action='store_true', dest='symlinks',
|
||||
help='Try to use symlinks rather than copies, '
|
||||
'when symlinks are not the default for '
|
||||
'the platform.')
|
||||
group.add_argument('--copies', default=ON_WINDOWS,
|
||||
action='store_false', dest='symlinks',
|
||||
help='Try to use copies rather than symlinks, '
|
||||
'even when symlinks are the default for '
|
||||
'the platform.')
|
||||
create.add_argument('--without-pip', dest='with_pip',
|
||||
default=True, action='store_false',
|
||||
help='Skips installing or upgrading pip in the '
|
||||
'virtual environment (pip is bootstrapped '
|
||||
'by default)')
|
||||
group.add_argument(
|
||||
"--symlinks",
|
||||
default=not ON_WINDOWS,
|
||||
action="store_true",
|
||||
dest="symlinks",
|
||||
help="Try to use symlinks rather than copies, "
|
||||
"when symlinks are not the default for "
|
||||
"the platform.",
|
||||
)
|
||||
group.add_argument(
|
||||
"--copies",
|
||||
default=ON_WINDOWS,
|
||||
action="store_false",
|
||||
dest="symlinks",
|
||||
help="Try to use copies rather than symlinks, "
|
||||
"even when symlinks are the default for "
|
||||
"the platform.",
|
||||
)
|
||||
create.add_argument(
|
||||
"--without-pip",
|
||||
dest="with_pip",
|
||||
default=True,
|
||||
action="store_false",
|
||||
help="Skips installing or upgrading pip in the "
|
||||
"virtual environment (pip is bootstrapped "
|
||||
"by default)",
|
||||
)
|
||||
|
||||
activate = subparsers.add_parser(
|
||||
'activate', aliases=['workon', 'enter'],
|
||||
help='Activate virtual environment'
|
||||
"activate", aliases=["workon", "enter"], help="Activate virtual environment"
|
||||
)
|
||||
activate.add_argument('name', metavar='ENV',
|
||||
help=('The environment to activate. ENV can be '
|
||||
'either a name from the venvs shown by vox'
|
||||
'list or the path to an arbitrary venv'))
|
||||
subparsers.add_parser('deactivate', aliases=['exit'], help='Deactivate current virtual environment')
|
||||
subparsers.add_parser('list', aliases=['ls'],
|
||||
help=('List environments available in '
|
||||
'$VIRTUALENV_HOME'))
|
||||
remove = subparsers.add_parser('remove', aliases=['rm', 'delete', 'del'], help='Remove virtual environment')
|
||||
remove.add_argument('names', metavar='ENV', nargs='+',
|
||||
help=('The environments to remove. ENV can be '
|
||||
'either a name from the venvs shown by vox'
|
||||
'list or the path to an arbitrary venv'))
|
||||
subparsers.add_parser('help', help='Show this help message')
|
||||
activate.add_argument(
|
||||
"name",
|
||||
metavar="ENV",
|
||||
help=(
|
||||
"The environment to activate. ENV can be "
|
||||
"either a name from the venvs shown by vox"
|
||||
"list or the path to an arbitrary venv"
|
||||
),
|
||||
)
|
||||
subparsers.add_parser(
|
||||
"deactivate",
|
||||
aliases=["exit"],
|
||||
help="Deactivate current virtual environment",
|
||||
)
|
||||
subparsers.add_parser(
|
||||
"list",
|
||||
aliases=["ls"],
|
||||
help=("List environments available in " "$VIRTUALENV_HOME"),
|
||||
)
|
||||
remove = subparsers.add_parser(
|
||||
"remove", aliases=["rm", "delete", "del"], help="Remove virtual environment"
|
||||
)
|
||||
remove.add_argument(
|
||||
"names",
|
||||
metavar="ENV",
|
||||
nargs="+",
|
||||
help=(
|
||||
"The environments to remove. ENV can be "
|
||||
"either a name from the venvs shown by vox"
|
||||
"list or the path to an arbitrary venv"
|
||||
),
|
||||
)
|
||||
subparsers.add_parser("help", help="Show this help message")
|
||||
return parser
|
||||
|
||||
parser = lazyasd.LazyObject(parser, locals(), 'parser')
|
||||
parser = lazyasd.LazyObject(parser, locals(), "parser")
|
||||
|
||||
aliases = {
|
||||
'create': 'new',
|
||||
'workon': 'activate',
|
||||
'enter': 'activate',
|
||||
'exit': 'deactivate',
|
||||
'ls': 'list',
|
||||
'rm': 'remove',
|
||||
'delete': 'remove',
|
||||
'del': 'remove',
|
||||
"create": "new",
|
||||
"workon": "activate",
|
||||
"enter": "activate",
|
||||
"exit": "deactivate",
|
||||
"ls": "list",
|
||||
"rm": "remove",
|
||||
"delete": "remove",
|
||||
"del": "remove",
|
||||
}
|
||||
|
||||
def __init__(self):
|
||||
|
@ -102,7 +138,7 @@ class VoxHandler:
|
|||
if cmd is None:
|
||||
self.parser.print_usage()
|
||||
else:
|
||||
getattr(self, 'cmd_' + cmd)(args, stdin)
|
||||
getattr(self, "cmd_" + cmd)(args, stdin)
|
||||
|
||||
def cmd_new(self, args, stdin=None):
|
||||
"""Create a virtual environment in $VIRTUALENV_HOME with python3's ``venv``.
|
||||
|
@ -125,7 +161,11 @@ class VoxHandler:
|
|||
try:
|
||||
self.vox.activate(args.name)
|
||||
except KeyError:
|
||||
print('This environment doesn\'t exist. Create it with "vox new %s".\n' % args.name, file=sys.stderr)
|
||||
print(
|
||||
'This environment doesn\'t exist. Create it with "vox new %s".\n'
|
||||
% args.name,
|
||||
file=sys.stderr,
|
||||
)
|
||||
return None
|
||||
else:
|
||||
print('Activated "%s".\n' % args.name)
|
||||
|
@ -134,7 +174,10 @@ class VoxHandler:
|
|||
"""Deactivate the active virtual environment."""
|
||||
|
||||
if self.vox.active() is None:
|
||||
print('No environment currently active. Activate one with "vox activate".\n', file=sys.stderr)
|
||||
print(
|
||||
'No environment currently active. Activate one with "vox activate".\n',
|
||||
file=sys.stderr,
|
||||
)
|
||||
return None
|
||||
env_name = self.vox.deactivate()
|
||||
print('Deactivated "%s".\n' % env_name)
|
||||
|
@ -145,15 +188,18 @@ class VoxHandler:
|
|||
try:
|
||||
envs = sorted(self.vox.keys())
|
||||
except PermissionError:
|
||||
print('No permissions on VIRTUALENV_HOME')
|
||||
print("No permissions on VIRTUALENV_HOME")
|
||||
return None
|
||||
|
||||
if not envs:
|
||||
print('No environments available. Create one with "vox new".\n', file=sys.stderr)
|
||||
print(
|
||||
'No environments available. Create one with "vox new".\n',
|
||||
file=sys.stderr,
|
||||
)
|
||||
return None
|
||||
|
||||
print('Available environments:')
|
||||
print('\n'.join(envs))
|
||||
print("Available environments:")
|
||||
print("\n".join(envs))
|
||||
|
||||
def cmd_remove(self, args, stdin=None):
|
||||
"""Remove virtual environments.
|
||||
|
@ -162,8 +208,11 @@ class VoxHandler:
|
|||
try:
|
||||
del self.vox[name]
|
||||
except voxapi.EnvironmentInUse:
|
||||
print('The "%s" environment is currently active. In order to remove it, deactivate it first with "vox deactivate %s".\n' % (name, name),
|
||||
file=sys.stderr)
|
||||
print(
|
||||
'The "%s" environment is currently active. In order to remove it, deactivate it first with "vox deactivate %s".\n'
|
||||
% (name, name),
|
||||
file=sys.stderr,
|
||||
)
|
||||
return
|
||||
else:
|
||||
print('Environment "%s" removed.' % name)
|
||||
|
@ -179,4 +228,4 @@ class VoxHandler:
|
|||
return vox(args, stdin=stdin)
|
||||
|
||||
|
||||
aliases['vox'] = VoxHandler.handle
|
||||
aliases["vox"] = VoxHandler.handle
|
||||
|
|
|
@ -25,32 +25,46 @@ from xonsh.fs import PathLike, fspath
|
|||
from xonsh.events import events
|
||||
|
||||
|
||||
events.doc('vox_on_create', """
|
||||
events.doc(
|
||||
"vox_on_create",
|
||||
"""
|
||||
vox_on_create(env: str) -> None
|
||||
|
||||
Fired after an environment is created.
|
||||
""")
|
||||
""",
|
||||
)
|
||||
|
||||
events.doc('vox_on_activate', """
|
||||
events.doc(
|
||||
"vox_on_activate",
|
||||
"""
|
||||
vox_on_activate(env: str) -> None
|
||||
|
||||
Fired after an environment is activated.
|
||||
""")
|
||||
""",
|
||||
)
|
||||
|
||||
events.doc('vox_on_deactivate', """
|
||||
events.doc(
|
||||
"vox_on_deactivate",
|
||||
"""
|
||||
vox_on_deactivate(env: str) -> None
|
||||
|
||||
Fired after an environment is deactivated.
|
||||
""")
|
||||
""",
|
||||
)
|
||||
|
||||
events.doc('vox_on_delete', """
|
||||
events.doc(
|
||||
"vox_on_delete",
|
||||
"""
|
||||
vox_on_delete(env: str) -> None
|
||||
|
||||
Fired after an environment is deleted (through vox).
|
||||
""")
|
||||
""",
|
||||
)
|
||||
|
||||
|
||||
VirtualEnvironment = collections.namedtuple('VirtualEnvironment', ['env', 'bin', 'lib', 'inc'])
|
||||
VirtualEnvironment = collections.namedtuple(
|
||||
"VirtualEnvironment", ["env", "bin", "lib", "inc"]
|
||||
)
|
||||
|
||||
|
||||
def _subdir_names():
|
||||
|
@ -61,11 +75,11 @@ def _subdir_names():
|
|||
may additional logic to get to useful places.
|
||||
"""
|
||||
if ON_WINDOWS:
|
||||
return 'Scripts', 'Lib', 'Include'
|
||||
return "Scripts", "Lib", "Include"
|
||||
elif ON_POSIX:
|
||||
return 'bin', 'lib', 'include'
|
||||
return "bin", "lib", "include"
|
||||
else:
|
||||
raise OSError('This OS is not supported.')
|
||||
raise OSError("This OS is not supported.")
|
||||
|
||||
|
||||
def _mkvenv(env_dir):
|
||||
|
@ -76,17 +90,17 @@ def _mkvenv(env_dir):
|
|||
"""
|
||||
env_dir = os.path.normpath(env_dir)
|
||||
if ON_WINDOWS:
|
||||
binname = os.path.join(env_dir, 'Scripts')
|
||||
incpath = os.path.join(env_dir, 'Include')
|
||||
libpath = os.path.join(env_dir, 'Lib', 'site-packages')
|
||||
binname = os.path.join(env_dir, "Scripts")
|
||||
incpath = os.path.join(env_dir, "Include")
|
||||
libpath = os.path.join(env_dir, "Lib", "site-packages")
|
||||
elif ON_POSIX:
|
||||
binname = os.path.join(env_dir, 'bin')
|
||||
incpath = os.path.join(env_dir, 'include')
|
||||
libpath = os.path.join(env_dir, 'lib',
|
||||
'python%d.%d' % sys.version_info[:2],
|
||||
'site-packages')
|
||||
binname = os.path.join(env_dir, "bin")
|
||||
incpath = os.path.join(env_dir, "include")
|
||||
libpath = os.path.join(
|
||||
env_dir, "lib", "python%d.%d" % sys.version_info[:2], "site-packages"
|
||||
)
|
||||
else:
|
||||
raise OSError('This OS is not supported.')
|
||||
raise OSError("This OS is not supported.")
|
||||
|
||||
return VirtualEnvironment(env_dir, binname, libpath, incpath)
|
||||
|
||||
|
@ -109,12 +123,12 @@ class Vox(collections.abc.Mapping):
|
|||
"""
|
||||
|
||||
def __init__(self):
|
||||
if not builtins.__xonsh__.env.get('VIRTUALENV_HOME'):
|
||||
home_path = os.path.expanduser('~')
|
||||
self.venvdir = os.path.join(home_path, '.virtualenvs')
|
||||
builtins.__xonsh__.env['VIRTUALENV_HOME'] = self.venvdir
|
||||
if not builtins.__xonsh__.env.get("VIRTUALENV_HOME"):
|
||||
home_path = os.path.expanduser("~")
|
||||
self.venvdir = os.path.join(home_path, ".virtualenvs")
|
||||
builtins.__xonsh__.env["VIRTUALENV_HOME"] = self.venvdir
|
||||
else:
|
||||
self.venvdir = builtins.__xonsh__.env['VIRTUALENV_HOME']
|
||||
self.venvdir = builtins.__xonsh__.env["VIRTUALENV_HOME"]
|
||||
|
||||
def create(
|
||||
self,
|
||||
|
@ -244,7 +258,9 @@ class Vox(collections.abc.Mapping):
|
|||
|
||||
@staticmethod
|
||||
def _check_reserved(name):
|
||||
return os.path.basename(name) not in _subdir_names() # FIXME: Check the middle components, too
|
||||
return (
|
||||
os.path.basename(name) not in _subdir_names()
|
||||
) # FIXME: Check the middle components, too
|
||||
|
||||
def __getitem__(self, name):
|
||||
"""Get information about a virtual environment.
|
||||
|
@ -256,7 +272,7 @@ class Vox(collections.abc.Mapping):
|
|||
the current one (throws a KeyError if there isn't one).
|
||||
"""
|
||||
if name is ...:
|
||||
env_paths = [builtins.__xonsh__.env['VIRTUAL_ENV']]
|
||||
env_paths = [builtins.__xonsh__.env["VIRTUAL_ENV"]]
|
||||
elif isinstance(name, PathLike):
|
||||
env_paths = [fspath(name)]
|
||||
else:
|
||||
|
@ -294,11 +310,11 @@ class Vox(collections.abc.Mapping):
|
|||
"""
|
||||
bin_, lib, inc = _subdir_names()
|
||||
for dirpath, dirnames, filenames in os.walk(self.venvdir):
|
||||
python_exec = os.path.join(dirpath, bin_, 'python')
|
||||
python_exec = os.path.join(dirpath, bin_, "python")
|
||||
if ON_WINDOWS:
|
||||
python_exec += '.exe'
|
||||
python_exec += ".exe"
|
||||
if os.access(python_exec, os.X_OK):
|
||||
yield dirpath[len(self.venvdir) + 1:] # +1 is to remove the separator
|
||||
yield dirpath[len(self.venvdir) + 1 :] # +1 is to remove the separator
|
||||
dirnames.clear()
|
||||
|
||||
def __len__(self):
|
||||
|
@ -316,12 +332,12 @@ class Vox(collections.abc.Mapping):
|
|||
|
||||
Returns None if no environment is active.
|
||||
"""
|
||||
if 'VIRTUAL_ENV' not in builtins.__xonsh__.env:
|
||||
if "VIRTUAL_ENV" not in builtins.__xonsh__.env:
|
||||
return
|
||||
env_path = builtins.__xonsh__.env['VIRTUAL_ENV']
|
||||
env_path = builtins.__xonsh__.env["VIRTUAL_ENV"]
|
||||
if env_path.startswith(self.venvdir):
|
||||
name = env_path[len(self.venvdir):]
|
||||
if name[0] in '/\\':
|
||||
name = env_path[len(self.venvdir) :]
|
||||
if name[0] in "/\\":
|
||||
name = name[1:]
|
||||
return name
|
||||
else:
|
||||
|
@ -338,14 +354,14 @@ class Vox(collections.abc.Mapping):
|
|||
"""
|
||||
env = builtins.__xonsh__.env
|
||||
ve = self[name]
|
||||
if 'VIRTUAL_ENV' in env:
|
||||
if "VIRTUAL_ENV" in env:
|
||||
self.deactivate()
|
||||
|
||||
type(self).oldvars = {'PATH': list(env['PATH'])}
|
||||
env['PATH'].insert(0, ve.bin)
|
||||
env['VIRTUAL_ENV'] = ve.env
|
||||
if 'PYTHONHOME' in env:
|
||||
type(self).oldvars['PYTHONHOME'] = env.pop('PYTHONHOME')
|
||||
type(self).oldvars = {"PATH": list(env["PATH"])}
|
||||
env["PATH"].insert(0, ve.bin)
|
||||
env["VIRTUAL_ENV"] = ve.env
|
||||
if "PYTHONHOME" in env:
|
||||
type(self).oldvars["PYTHONHOME"] = env.pop("PYTHONHOME")
|
||||
|
||||
events.vox_on_activate.fire(name=name)
|
||||
|
||||
|
@ -354,17 +370,17 @@ class Vox(collections.abc.Mapping):
|
|||
Deactivate the active virtual environment. Returns its name.
|
||||
"""
|
||||
env = builtins.__xonsh__.env
|
||||
if 'VIRTUAL_ENV' not in env:
|
||||
raise NoEnvironmentActive('No environment currently active.')
|
||||
if "VIRTUAL_ENV" not in env:
|
||||
raise NoEnvironmentActive("No environment currently active.")
|
||||
|
||||
env_name = self.active()
|
||||
|
||||
if hasattr(type(self), 'oldvars'):
|
||||
if hasattr(type(self), "oldvars"):
|
||||
for k, v in type(self).oldvars.items():
|
||||
env[k] = v
|
||||
del type(self).oldvars
|
||||
|
||||
env.pop('VIRTUAL_ENV')
|
||||
env.pop("VIRTUAL_ENV")
|
||||
|
||||
events.vox_on_deactivate.fire(name=env_name)
|
||||
return env_name
|
||||
|
@ -381,7 +397,9 @@ class Vox(collections.abc.Mapping):
|
|||
env_path = self[name].env
|
||||
try:
|
||||
if self[...].env == env_path:
|
||||
raise EnvironmentInUse('The "%s" environment is currently active.' % name)
|
||||
raise EnvironmentInUse(
|
||||
'The "%s" environment is currently active.' % name
|
||||
)
|
||||
except KeyError:
|
||||
# No current venv, ... fails
|
||||
pass
|
||||
|
|
|
@ -17,7 +17,7 @@ def custom_keybindings(bindings, **kw):
|
|||
# Alt+Left and Alt+Right still jump over smaller word segments.
|
||||
# See https://github.com/xonsh/xonsh/issues/2403
|
||||
|
||||
if ptk_shell_type() == 'prompt_toolkit2':
|
||||
if ptk_shell_type() == "prompt_toolkit2":
|
||||
handler = bindings.add
|
||||
else:
|
||||
handler = bindings.registry.add_binding
|
||||
|
|
Loading…
Add table
Reference in a new issue