small style changes

This commit is contained in:
Leonardo Santagada 2016-07-18 11:30:57 +02:00
parent 540bfcbc17
commit 61099aab10
40 changed files with 138 additions and 105 deletions

View file

@ -49,6 +49,7 @@ class SourceCache(Mapping):
SOURCES = SourceCache()
def make_node(name, pkg, allowed):
"""Makes a node by parsing a file and traversing its AST."""
raw = SOURCES[pkg, name]
@ -161,6 +162,7 @@ class _LazyModule(_ModuleType):
"""
def get_lineno(node, default=0):
"""Gets the lineno of a node or returns the default."""
return getattr(node, 'lineno', default)
@ -236,7 +238,7 @@ def rewrite_imports(name, pkg, order, imps):
imps.add(imp)
keep.append(imp)
if len(keep) == 0:
s = ', '.join(n.name for n in a.names)
s = ', '.join(n.name for n in a.names)
s = '# amalgamated ' + s + '\n'
else:
s = format_lazy_import(keep)

View file

@ -3,7 +3,7 @@ addopts = --flake8
flake8-max-line-length = 180
flake8-ignore =
# Temporary until we fix all the errors
*.py E301 E302 E303 W391 E402 E127 E128 E201 E731 E701 E271 E265 E266 E225 E202 E502 E231 E228 E227 E203 E122 E251 W291 E124 E261 E125 E111 E222 E272
*.py
__amalgam__.py ALL
# test files should be PEP8 but a ton of errors for now
test_*.py ALL

View file

@ -47,7 +47,8 @@ def clean_tables():
os.environ['XONSH_DEBUG'] = '1'
from xonsh import __version__ as XONSH_VERSION
from xonsh import __version__ as XONSH_VERSION # noqa: E402
def amalagamate_source():
"""Amalgamtes source files."""
@ -81,7 +82,7 @@ def install_jupyter_hook(prefix=None, root=None):
"display_name": "Xonsh",
"language": "xonsh",
"codemirror_mode": "shell",
}
}
with TemporaryDirectory() as d:
os.chmod(d, 0o755) # Starts off as 700, not user readable
if sys.platform == 'win32':
@ -117,7 +118,7 @@ def dirty_version():
_version = _version.decode('ascii')
try:
base, N, sha = _version.strip().split('-')
except ValueError: # on base release
except ValueError: # on base release
open('xonsh/dev.githash', 'w').close()
print('failed to parse git version', file=sys.stderr)
return False
@ -130,6 +131,7 @@ def dirty_version():
ORIGINAL_VERSION_LINE = None
def replace_version(base, N):
"""Replace version in `__init__.py` with devN suffix"""
global ORIGINAL_VERSION_LINE
@ -175,7 +177,6 @@ class xinstall(install):
restore_version()
class xsdist(sdist):
"""Xonsh specialization of setuptools sdist class."""
def make_release_tree(self, basedir, files):
@ -187,7 +188,6 @@ class xsdist(sdist):
restore_version()
#-----------------------------------------------------------------------------
# Hack to overcome pip/setuptools problem on Win 10. See:
# https://github.com/tomduck/pandoc-eqnos/issues/6
# https://github.com/pypa/pip/issues/2783
@ -198,7 +198,7 @@ class install_scripts_quoted_shebang(install_scripts):
def write_script(self, script_name, contents, mode="t", *ignored):
shebang = str(contents.splitlines()[0])
if shebang.startswith('#!') and ' ' in shebang[2:].strip() \
and '"' not in shebang:
and '"' not in shebang:
quoted_shebang = '#!"%s"' % shebang[2:].strip()
contents = contents.replace(shebang, quoted_shebang)
super().write_script(script_name, contents, mode, *ignored)

View file

@ -3,7 +3,7 @@ import subprocess
import os
import argparse
program_description = """Build and run Xonsh in a fresh, controlled
program_description = """Build and run Xonsh in a fresh, controlled
environment using docker """
parser = argparse.ArgumentParser(description=program_description)
@ -13,7 +13,7 @@ parser.add_argument('--python', '-p', default='3.4', metavar='python_version')
parser.add_argument('--ptk', '-t', default='1.00', metavar='ptk_version')
parser.add_argument('--keep', action='store_true')
parser.add_argument('--build', action='store_true')
parser.add_argument('--command', '-c', default='xonsh',
parser.add_argument('--command', '-c', default='xonsh',
metavar='command')
args = parser.parse_args()
@ -29,8 +29,8 @@ WORKDIR /xonsh
ADD ./ ./
RUN python setup.py install
""".format(
python_version = args.python,
ptk_version = args.ptk)
python_version=args.python,
ptk_version=args.ptk)
print('Building and running Xonsh')
print('Using python ', args.python)
@ -41,7 +41,7 @@ with open('./Dockerfile', 'w+') as f:
env_string = ' '.join(args.env)
subprocess.call(['docker', 'build', '-t' , 'xonsh', '.'])
subprocess.call(['docker', 'build', '-t', 'xonsh', '.'])
os.remove('./Dockerfile')
if not args.build:

View file

@ -2,7 +2,7 @@ __version__ = '0.4.3'
# amalgamate exclude jupyter_kernel parser_table parser_test_table pyghooks
# amalgamate exclude winutils wizard
import os as _os
import os as _os # noqa: E402
if _os.getenv('XONSH_DEBUG', ''):
pass
else:

View file

@ -142,7 +142,6 @@ class Aliases(abc.MutableMapping):
p.pretty(dict(self))
def xonsh_exit(args, stdin=None):
"""Sends signal to exit shell."""
if not clean_jobs():
@ -298,8 +297,8 @@ def xexec(args, stdin=None):
@lazyobject
def _BANG_N_PARSER():
parser = argparse.ArgumentParser('!n', usage='!n <n>',
description="Re-runs the nth command as specified in the "
"argument.")
description="Re-runs the nth command as specified in the "
"argument.")
parser.add_argument('n', type=int, help='the command to rerun, may be '
'negative')
return parser
@ -326,6 +325,7 @@ def bang_bang(args, stdin=None):
class AWitchAWitch(argparse.Action):
SUPPRESS = '==SUPPRESS=='
def __init__(self, option_strings, version=None, dest=SUPPRESS,
default=SUPPRESS, **kwargs):
super().__init__(option_strings=option_strings, dest=dest,
@ -348,7 +348,7 @@ def which(args, stdin=None, stdout=None, stderr=None):
parser = argparse.ArgumentParser('which', description=desc)
parser.add_argument('args', type=str, nargs='+',
help='The executables or aliases to search for')
parser.add_argument('-a','--all', action='store_true', dest='all',
parser.add_argument('-a', '--all', action='store_true', dest='all',
help='Show all matches in $PATH and xonsh.aliases')
parser.add_argument('-s', '--skip-alias', action='store_true',
help='Do not search in xonsh.aliases', dest='skip')

View file

@ -340,6 +340,7 @@ RGB_256 = LazyObject(lambda: {
RE_RGB3 = LazyObject(lambda: re.compile(r'(.)(.)(.)'), globals(), 'RE_RGB3')
RE_RGB6 = LazyObject(lambda: re.compile(r'(..)(..)(..)'), globals(), 'RE_RGB6')
def rgb_to_ints(rgb):
"""Converts an RGB string into a tuple of ints."""
if len(rgb) == 6:
@ -366,8 +367,10 @@ def rgb_to_256(rgb):
if s <= part <= b:
s1 = abs(s - part)
b1 = abs(b - part)
if s1 < b1: closest = s
else: closest = b
if s1 < b1:
closest = s
else:
closest = b
res.append(closest)
break
i += 1
@ -530,6 +533,7 @@ def _default_style():
}
return style
def _monokai_style():
style = {
'NO_COLOR': '0',
@ -554,9 +558,9 @@ def _monokai_style():
return style
#############################################################
############# Auto-generated below this line ############
#############################################################
####################################
# Auto-generated below this line #
####################################
def _algol_style():
style = {
@ -605,6 +609,7 @@ def _algol_nu_style():
_ansi_expand_style(style)
return style
def _autumn_style():
style = {
'BLACK': '38;5;18',
@ -628,6 +633,7 @@ def _autumn_style():
_ansi_expand_style(style)
return style
def _borland_style():
style = {
'BLACK': '38;5;16',
@ -771,6 +777,7 @@ def _igor_style():
_ansi_expand_style(style)
return style
def _lovelace_style():
style = {
'BLACK': '38;5;59',
@ -866,6 +873,7 @@ def _native_style():
_ansi_expand_style(style)
return style
def _paraiso_dark_style():
style = {
'BLACK': '38;5;95',
@ -913,6 +921,7 @@ def _paraiso_light_style():
_ansi_expand_style(style)
return style
def _pastie_style():
style = {
'BLACK': '38;5;16',
@ -960,6 +969,7 @@ def _perldoc_style():
_ansi_expand_style(style)
return style
def _rrt_style():
style = {
'BLACK': '38;5;09',

View file

@ -466,7 +466,6 @@ class CtxAwareTransformer(NodeTransformer):
return node
def pdump(s, **kwargs):
"""performs a pretty dump of an AST node."""
if isinstance(s, AST):
@ -476,7 +475,7 @@ def pdump(s, **kwargs):
lens = len(s) + 1
if lens == 1:
return s
i = min([s.find(o)%lens for o in openers])
i = min([s.find(o) % lens for o in openers])
if i == lens - 1:
return s
closer = closers[openers.find(s[i])]

View file

@ -7,7 +7,7 @@ import time
import builtins
from xonsh.tools import (XonshError, escape_windows_cmd_string, print_exception,
DefaultNotGiven)
DefaultNotGiven)
from xonsh.platform import HAS_PYGMENTS, ON_WINDOWS
from xonsh.codecache import (should_use_cache, code_cache_name,
code_cache_check, get_cache_filename,
@ -34,7 +34,7 @@ class _TeeOut(object):
def write(self, data):
"""Writes data to the original stdout and the buffer."""
#data = data.replace('\001', '').replace('\002', '')
# data = data.replace('\001', '').replace('\002', '')
self.stdout.write(data)
self.buffer.write(data)
@ -66,7 +66,7 @@ class _TeeErr(object):
def write(self, data):
"""Writes data to the original stderr and the buffer."""
#data = data.replace('\001', '').replace('\002', '')
# data = data.replace('\001', '').replace('\002', '')
self.stderr.write(data)
self.buffer.write(data)

View file

@ -39,6 +39,7 @@ from xonsh.commands_cache import CommandsCache
BUILTINS_LOADED = False
INSPECTOR = LazyObject(Inspector, globals(), 'INSPECTOR')
@lazyobject
def AT_EXIT_SIGNALS():
sigs = (signal.SIGABRT, signal.SIGFPE, signal.SIGILL, signal.SIGSEGV,
@ -71,6 +72,7 @@ def resetting_signal_handle(sig, f):
once the new handle is finished.
"""
oldh = signal.getsignal(sig)
def newh(s=None, frame=None):
f(s, frame)
signal.signal(sig, oldh)
@ -569,7 +571,7 @@ def run_subproc(cmds, captured=False):
output = output.replace('\r\n', '\n')
else:
hist.last_cmd_out = output
if captured == 'object': # get stderr as well
if captured == 'object': # get stderr as well
named = _stderr_name is not None
unnamed = prev_proc.stderr not in {None, sys.stderr}
if named:

View file

@ -6,6 +6,7 @@ import builtins
from xonsh.lazyasd import lazyobject
def _splitpath(path, sofar=[]):
folder, path = os.path.split(path)
if path == "":
@ -35,6 +36,7 @@ def _make_if_not_exists(dirname):
if not os.path.isdir(dirname):
os.makedirs(dirname)
def should_use_cache(execer, mode):
"""
Return ``True`` if caching has been enabled for this mode (through command
@ -42,7 +44,7 @@ def should_use_cache(execer, mode):
"""
if mode == 'exec':
return ((execer.scriptcache or
execer.cacheall) and
execer.cacheall) and
(builtins.__xonsh_env__['XONSH_CACHE_SCRIPTS'] or
builtins.__xonsh_env__['XONSH_CACHE_EVERYTHING']))
else:

View file

@ -40,15 +40,15 @@ def bold_str_diff(a, b, sm=None):
bline += b[j1:j2]
else:
raise RuntimeError('tag not understood')
return aline + NO_COLOR + '\n' + bline + NO_COLOR +'\n'
return aline + NO_COLOR + '\n' + bline + NO_COLOR + '\n'
def redline(line):
return '{red}- {line}{no_color}\n'.format(red=RED, line=line, no_color=NO_COLOR)
return '{red}- {line}{no_color}\n'.format(red=RED, line=line, no_color=NO_COLOR)
def greenline(line):
return '{green}+ {line}{no_color}\n'.format(green=GREEN, line=line, no_color=NO_COLOR)
return '{green}+ {line}{no_color}\n'.format(green=GREEN, line=line, no_color=NO_COLOR)
def highlighted_ndiff(a, b):
@ -147,7 +147,7 @@ class HistoryDiffer(object):
if len(only_x) == 0:
return ''
if self.verbose:
xstr = ',\n'.join([' {0!r}: {1!r}'.format(key, xenv[key]) \
xstr = ',\n'.join([' {0!r}: {1!r}'.format(key, xenv[key])
for key in only_x])
xstr = '\n' + xstr
else:
@ -193,16 +193,16 @@ class HistoryDiffer(object):
aout = self.a['cmds'][i].get('out', None)
bout = self.b['cmds'][j].get('out', None)
if aout is None and bout is None:
#s += 'Note: neither output stored\n'
# s += 'Note: neither output stored\n'
pass
elif bout is None:
aid = self.a['sessionid']
s += 'Note: only {red}{aid}{no_color} output stored\n'.format(red=RED,
aid=aid, no_color=NO_COLOR)
aid=aid, no_color=NO_COLOR)
elif aout is None:
bid = self.b['sessionid']
s += 'Note: only {green}{bid}{no_color} output stored\n'.format(green=GREEN,
bid=bid, no_color=NO_COLOR)
bid=bid, no_color=NO_COLOR)
elif aout != bout:
s += 'Outputs differ\n'
s += highlighted_ndiff(aout.splitlines(), bout.splitlines())
@ -280,6 +280,7 @@ class HistoryDiffer(object):
_HD_PARSER = None
def _dh_create_parser(p=None):
global _HD_PARSER
p_was_none = (p is None)
@ -309,4 +310,3 @@ def diff_history_main(args=None, stdin=None):
parser = _dh_create_parser()
ns = parser.parse_args(args)
_dh_main_action(ns)

View file

@ -110,7 +110,7 @@ class Execer(object):
return code
def eval(self, input, glbs=None, locs=None, stacklevel=2,
transform=True):
transform=True):
"""Evaluates (and returns) xonsh code."""
if isinstance(input, types.CodeType):
code = input
@ -126,7 +126,7 @@ class Execer(object):
return eval(code, glbs, locs)
def exec(self, input, mode='exec', glbs=None, locs=None, stacklevel=2,
transform=True):
transform=True):
"""Execute xonsh code."""
if isinstance(input, types.CodeType):
code = input
@ -204,7 +204,7 @@ class Execer(object):
# or for some other syntax error
raise original_error
elif sbpline[last_error_col:].startswith('![![') or \
sbpline.lstrip().startswith('![!['):
sbpline.lstrip().startswith('![!['):
# if we have already wrapped this in subproc tokens
# and it still doesn't work, adding more won't help
# anything

View file

@ -12,12 +12,10 @@ import functools
import collections.abc as abc
from collections import Sequence
from xonsh.lazyasd import LazyObject
from xonsh.tools import to_bool, ensure_string
from xonsh.platform import ON_WINDOWS, ON_CYGWIN
COMMAND = """{seterrprevcmd}
{prevcmd}
echo __XONSH_ENV_BEG__
@ -90,55 +88,55 @@ CANON_SHELL_NAMES = LazyObject(lambda: {
'/usr/bin/zsh': 'zsh',
'cmd': 'cmd',
'cmd.exe': 'cmd',
}, globals(), 'CANON_SHELL_NAMES')
}, globals(), 'CANON_SHELL_NAMES')
DEFAULT_ENVCMDS = LazyObject(lambda: {
'bash': 'env',
'zsh': 'env',
'cmd': 'set',
}, globals(), 'DEFAULT_ENVCMDS')
}, globals(), 'DEFAULT_ENVCMDS')
DEFAULT_ALIASCMDS = LazyObject(lambda: {
'bash': 'alias',
'zsh': 'alias -L',
'cmd': '',
}, globals(), 'DEFAULT_ALIASCMDS')
}, globals(), 'DEFAULT_ALIASCMDS')
DEFAULT_FUNCSCMDS = LazyObject(lambda: {
'bash': DEFAULT_BASH_FUNCSCMD,
'zsh': DEFAULT_ZSH_FUNCSCMD,
'cmd': '',
}, globals(), 'DEFAULT_FUNCSCMDS')
}, globals(), 'DEFAULT_FUNCSCMDS')
DEFAULT_SOURCERS = LazyObject(lambda: {
'bash': 'source',
'zsh': 'source',
'cmd': 'call',
}, globals(), 'DEFAULT_SOURCERS')
}, globals(), 'DEFAULT_SOURCERS')
DEFAULT_TMPFILE_EXT = LazyObject(lambda: {
'bash': '.sh',
'zsh': '.zsh',
'cmd': '.bat',
}, globals(), 'DEFAULT_TMPFILE_EXT')
}, globals(), 'DEFAULT_TMPFILE_EXT')
DEFAULT_RUNCMD = LazyObject(lambda: {
'bash': '-c',
'zsh': '-c',
'cmd': '/C',
}, globals(), 'DEFAULT_RUNCMD')
}, globals(), 'DEFAULT_RUNCMD')
DEFAULT_SETERRPREVCMD = LazyObject(lambda: {
'bash': 'set -e',
'zsh': 'set -e',
'cmd': '@echo off',
}, globals(), 'DEFAULT_SETERRPREVCMD')
}, globals(), 'DEFAULT_SETERRPREVCMD')
DEFAULT_SETERRPOSTCMD = LazyObject(lambda: {
'bash': '',
'zsh': '',
'cmd': 'if errorlevel 1 exit 1',
}, globals(), 'DEFAULT_SETERRPOSTCMD')
}, globals(), 'DEFAULT_SETERRPOSTCMD')
@functools.lru_cache()
@ -225,9 +223,9 @@ def foreign_shell_data(shell, interactive=True, login=False, envcmd=None,
tmpfile_ext = DEFAULT_TMPFILE_EXT.get(shkey, 'sh') if tmpfile_ext is None else tmpfile_ext
runcmd = DEFAULT_RUNCMD.get(shkey, '-c') if runcmd is None else runcmd
seterrprevcmd = DEFAULT_SETERRPREVCMD.get(shkey, '') \
if seterrprevcmd is None else seterrprevcmd
if seterrprevcmd is None else seterrprevcmd
seterrpostcmd = DEFAULT_SETERRPOSTCMD.get(shkey, '') \
if seterrpostcmd is None else seterrpostcmd
if seterrpostcmd is None else seterrpostcmd
command = COMMAND.format(envcmd=envcmd, aliascmd=aliascmd, prevcmd=prevcmd,
postcmd=postcmd, funcscmd=funcscmd,
seterrprevcmd=seterrprevcmd,
@ -247,7 +245,7 @@ def foreign_shell_data(shell, interactive=True, login=False, envcmd=None,
try:
s = subprocess.check_output(cmd, stderr=subprocess.PIPE, env=currenv,
# start new session to avoid hangs
#(doesn't work on Cygwin though)
# (doesn't work on Cygwin though)
start_new_session=(not ON_CYGWIN),
universal_newlines=True)
except (subprocess.CalledProcessError, FileNotFoundError):
@ -268,7 +266,7 @@ ENV_RE = LazyObject(lambda: re.compile('__XONSH_ENV_BEG__\n(.*)'
'__XONSH_ENV_END__', flags=re.DOTALL),
globals(), 'ENV_RE')
ENV_SPLIT_RE = LazyObject(lambda: re.compile('^([^=]+)=([^=]*|[^\n]*)$',
flags=re.DOTALL|re.MULTILINE),
flags=re.DOTALL | re.MULTILINE),
globals(), 'ENV_SPLIT_RE')
@ -343,7 +341,7 @@ def parse_funcs(s, shell, sourcer=None):
warnings.warn(msg.format(exc, shell, s, g1), RuntimeWarning)
return {}
sourcer = DEFAULT_SOURCERS.get(shell, 'source') if sourcer is None \
else sourcer
else sourcer
funcs = {}
for funcname, filename in namefiles.items():
if funcname.startswith('_'):
@ -378,7 +376,7 @@ class ForeignShellFunctionAlias(object):
Command to source foreing files with.
"""
sourcer = DEFAULT_SOURCERS.get(shell, 'source') if sourcer is None \
else sourcer
else sourcer
self.name = name
self.shell = shell
self.filename = filename
@ -386,7 +384,7 @@ class ForeignShellFunctionAlias(object):
def __eq__(self, other):
if not hasattr(other, 'name') or not hasattr(other, 'shell') or \
not hasattr(other, 'filename') or not hasattr(other, 'sourcer'):
not hasattr(other, 'filename') or not hasattr(other, 'sourcer'):
return NotImplemented
return (self.name == other.name) and (self.shell == other.shell) and \
(self.filename == other.filename) and (self.sourcer == other.sourcer)
@ -418,10 +416,11 @@ class ForeignShellFunctionAlias(object):
VALID_SHELL_PARAMS = LazyObject(lambda: frozenset([
'shell', 'interactive', 'login', 'envcmd',
'aliascmd', 'extra_args', 'currenv', 'safe',
'prevcmd', 'postcmd', 'funcscmd', 'sourcer',
]), globals(), 'VALID_SHELL_PARAMS')
'shell', 'interactive', 'login', 'envcmd',
'aliascmd', 'extra_args', 'currenv', 'safe',
'prevcmd', 'postcmd', 'funcscmd', 'sourcer',
]), globals(), 'VALID_SHELL_PARAMS')
def ensure_shell(shell):
"""Ensures that a mapping follows the shell specification."""
@ -438,10 +437,10 @@ def ensure_shell(shell):
shell['login'] = to_bool(shell['login'])
if 'envcmd' in shell_keys:
shell['envcmd'] = None if shell['envcmd'] is None \
else ensure_string(shell['envcmd'])
else ensure_string(shell['envcmd'])
if 'aliascmd' in shell_keys:
shell['aliascmd'] = None if shell['aliascmd'] is None \
else ensure_string(shell['aliascmd'])
else ensure_string(shell['aliascmd'])
if 'extra_args' in shell_keys and not isinstance(shell['extra_args'], tuple):
shell['extra_args'] = tuple(map(ensure_string, shell['extra_args']))
if 'currenv' in shell_keys and not isinstance(shell['currenv'], tuple):
@ -461,16 +460,16 @@ def ensure_shell(shell):
shell['postcmd'] = ensure_string(shell['postcmd'])
if 'funcscmd' in shell_keys:
shell['funcscmd'] = None if shell['funcscmd'] is None \
else ensure_string(shell['funcscmd'])
else ensure_string(shell['funcscmd'])
if 'sourcer' in shell_keys:
shell['sourcer'] = None if shell['sourcer'] is None \
else ensure_string(shell['sourcer'])
else ensure_string(shell['sourcer'])
if 'seterrprevcmd' in shell_keys:
shell['seterrprevcmd'] = None if shell['seterrprevcmd'] is None \
else ensure_string(shell['seterrprevcmd'])
else ensure_string(shell['seterrprevcmd'])
if 'seterrpostcmd' in shell_keys:
shell['seterrpostcmd'] = None if shell['seterrpostcmd'] is None \
else ensure_string(shell['seterrpostcmd'])
else ensure_string(shell['seterrpostcmd'])
return shell

View file

@ -441,7 +441,7 @@ def _hist_create_parser():
def _hist_show(ns=None, hist=None, start_index=None, end_index=None,
start_time=None, end_time=None, location=None):
start_time=None, end_time=None, location=None):
"""Show the requested portion of shell history.
Accepts multiple history sources (xonsh, bash, zsh)

View file

@ -307,6 +307,7 @@ if PYTHON_VERSION_INFO < (3, 5, 0):
FrameInfo = collections.namedtuple('FrameInfo', ['frame', 'filename',
'lineno', 'function',
'code_context', 'index'])
def getouterframes(frame, context=1):
"""Wrapper for getouterframes so that it acts like the Python v3.5 version."""
return [FrameInfo(*f) for f in inspect.getouterframes(frame, context=context)]
@ -634,8 +635,8 @@ class Inspector(object):
str_head = 'string_form'
if not detail_level and len(ostr) > string_max:
ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
ostr = ("\n" + " " * len(str_head.expandtabs())).\
join(q.strip() for q in ostr.split("\n"))
ostr = ("\n" + " " * len(str_head.expandtabs())). \
join(q.strip() for q in ostr.split("\n"))
out[str_head] = ostr
except: # pylint:disable=bare-except
pass

View file

@ -129,7 +129,6 @@ else:
_st = None
return _st
# _give_terminal_to is a simplified version of:
# give_terminal_to from bash 4.3 source, jobs.c, line 4030
# this will give the terminal to the process group pgid
@ -164,7 +163,6 @@ else:
os.tcsetpgrp(st, pgid)
signal.pthread_sigmask(signal.SIG_SETMASK, oldmask)
def wait_for_active_job():
"""
Wait for the active job to finish, to be killed by SIGINT, or to be

View file

@ -13,6 +13,7 @@ from xonsh.tools import redirect_stdout, redirect_stderr, swap
MAX_SIZE = 8388608 # 8 Mb
class XonshKernel(Kernel):
"""Xonsh xernal for Jupyter"""
implementation = 'Xonsh ' + version

View file

@ -10,6 +10,7 @@ import importlib
import importlib.util
import collections.abc as abc
class LazyObject(object):
def __init__(self, load, ctx, name):
@ -115,7 +116,6 @@ def lazyobject(f):
return LazyObject(f, f.__globals__, f.__name__)
class LazyDict(abc.MutableMapping):
def __init__(self, loaders, ctx, name):
@ -249,7 +249,7 @@ class BackgroundModuleProxy(types.ModuleType):
}
def __getattribute__(self, name):
passthrough = frozenset({'__dct__','__class__', '__spec__'})
passthrough = frozenset({'__dct__', '__class__', '__spec__'})
if name in passthrough:
return super().__getattribute__(name)
dct = self.__dct__
@ -283,7 +283,7 @@ class BackgroundModuleLoader(threading.Thread):
hist = [-5, -4, -3, -2, -1]
while not all(last == x for x in hist):
time.sleep(0.001)
last = hist[i%5] = len(sys.modules)
last = hist[i % 5] = len(sys.modules)
i += 1
# now import pkg_resources properly
modname = importlib.util.resolve_name(self.name, self.package)

View file

@ -248,4 +248,3 @@ class LazyJSON(LJNode):
def __exit__(self, exc_type, exc_value, traceback):
self.close()

View file

@ -14,8 +14,8 @@ except ImportError:
from xonsh.lazyasd import lazyobject
from xonsh.platform import PYTHON_VERSION_INFO
from xonsh.tokenize import (OP, IOREDIRECT, STRING, DOLLARNAME, NUMBER,
SEARCHPATH, NEWLINE, INDENT, DEDENT, NL, COMMENT, ENCODING,
ENDMARKER, NAME, ERRORTOKEN, tokenize, TokenError)
SEARCHPATH, NEWLINE, INDENT, DEDENT, NL, COMMENT, ENCODING,
ENDMARKER, NAME, ERRORTOKEN, tokenize, TokenError)
@lazyobject
@ -169,6 +169,7 @@ def _make_matcher_handler(tok, typ, pymode, ender, handlers):
matcher = (')' if tok.endswith('(') else
'}' if tok.endswith('{') else
']' if tok.endswith('[') else None)
def _inner_handler(state, token):
state['pymode'].append((pymode, tok, matcher, token.start))
state['last'] = token

View file

@ -23,6 +23,7 @@ cookie_comment_re = LazyObject(
lambda: re.compile(r"^\s*#.*coding[:=]\s*([-\w.]+)", re.UNICODE),
globals(), 'cookie_comment_re')
def source_to_unicode(txt, errors='replace', skip_encoding_cookie=True):
"""Converts a bytes string with python source code to unicode.

View file

@ -3,6 +3,7 @@
from xonsh.lazyasd import lazyobject
from xonsh.platform import PYTHON_VERSION_INFO
@lazyobject
def Parser():
if PYTHON_VERSION_INFO < (3, 5, 0):

View file

@ -21,6 +21,7 @@ from xonsh.lazyasd import LazyObject
RE_SEARCHPATH = LazyObject(lambda: re.compile(SearchPath), globals(),
'RE_SEARCHPATH')
class Location(object):
"""Location in a file."""
@ -274,7 +275,7 @@ class BaseParser(object):
yacc_kwargs['outputdir'] = outputdir
self.parser = None
YaccLoader(self, yacc_kwargs)
#self.parser = yacc.yacc(**yacc_kwargs)
# self.parser = yacc.yacc(**yacc_kwargs)
# Keeps track of the last token given to yacc (the lookahead token)
self._last_yielded_token = None

View file

@ -245,6 +245,7 @@ def windows_bash_command():
# Environment variables defaults
#
@lazyobject
def BASH_COMPLETIONS_DEFAULT():
"""A possibly empty tuple with default paths to Bash completions known for
@ -263,11 +264,11 @@ def BASH_COMPLETIONS_DEFAULT():
'/opt/local/etc/profile.d/bash_completion.sh')
elif ON_WINDOWS and git_for_windows_path():
bcd = (os.path.join(git_for_windows_path(),
'usr\\share\\bash-completion'),
'usr\\share\\bash-completion'),
os.path.join(git_for_windows_path(),
'usr\\share\\bash-completion\\completions'),
'usr\\share\\bash-completion\\completions'),
os.path.join(git_for_windows_path(),
'mingw64\\share\\git\\completion\\git-completion.bash'))
'mingw64\\share\\git\\completion\\git-completion.bash'))
else:
bcd = ()
return bcd
@ -289,7 +290,7 @@ def PATH_DEFAULT():
elif ON_WINDOWS:
import winreg
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment')
r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment')
pd = tuple(winreg.QueryValueEx(key, 'Path')[0].split(os.pathsep))
else:
pd = ()

View file

@ -1,4 +1,5 @@
# must come before ptk / pygments imports
from xonsh.lazyasd import load_module_in_background
load_module_in_background('pkg_resources', debug='XONSH_DEBUG',
replacements={'pygments.plugin': 'pkg_resources'})
replacements={'pygments.plugin': 'pkg_resources'})

View file

@ -50,6 +50,7 @@ class PromptToolkitCompleter(Completer):
h = window.render_info.content_height
r = builtins.__xonsh_env__.get('COMPLETIONS_MENU_ROWS')
size = h + r
def comp_height(cli):
# If there is an autocompletion menu to be shown, make sure that o
# layout has at least a minimal height in order to display it.

View file

@ -49,7 +49,7 @@ def carriage_return(b, cli):
b.newline(copy_margin=True)
elif (b.document.char_before_cursor == '\\' and
not (not builtins.__xonsh_env__.get('FORCE_POSIX_PATHS')
and ON_WINDOWS)):
and ON_WINDOWS)):
b.newline()
elif (b.document.find_next_word_beginning() is not None and
(any(not _is_blank(i)
@ -74,6 +74,7 @@ class TabShouldInsertIndentFilter(Filter):
return bool(before_cursor.isspace())
class BeginningOfLine(Filter):
"""
Check if cursor is at beginning of a line other than the first line
@ -85,6 +86,7 @@ class BeginningOfLine(Filter):
return bool(len(before_cursor) == 0
and not cli.current_buffer.document.on_first_line)
class EndOfLine(Filter):
"""
Check if cursor is at the end of a line other than the last line
@ -177,7 +179,6 @@ def load_xonsh_bindings(key_bindings_manager):
b.cursor_left(count=abs(relative_begin_index))
b.cursor_down(count=1)
@handle(Keys.ControlI, filter=insert_mode)
def generate_completions(event):
"""
@ -203,6 +204,8 @@ def load_xonsh_bindings(key_bindings_manager):
second_tab()
else:
event.cli.start_completion(insert_common_part=True,
select_first=False)
select_first=False)
def _is_blank(l):
return len(l.strip()) == 0

View file

@ -58,9 +58,9 @@ class PromptToolkitShell(BaseShell):
self.styler.style_name = env.get('XONSH_COLOR_STYLE')
completer = None if completions_display == 'none' else self.pt_completer
prompt_tokens = self.prompt_tokens(None)
get_prompt_tokens = lambda cli: prompt_tokens
get_prompt_tokens = lambda cli: prompt_tokens # noqa: E731
rprompt_tokens = self.rprompt_tokens(None)
get_rprompt_tokens = lambda cli: rprompt_tokens
get_rprompt_tokens = lambda cli: rprompt_tokens # noqa: E731
with self.prompter:
prompt_args = {
'mouse_support': mouse_support,

View file

@ -6,7 +6,7 @@ from prompt_toolkit.interface import CommandLineInterface
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.utils import DummyContext
from prompt_toolkit.shortcuts import (create_prompt_application,
create_eventloop, create_asyncio_eventloop, create_output)
create_eventloop, create_asyncio_eventloop, create_output)
from xonsh.platform import ptk_version_info
@ -32,7 +32,7 @@ class Prompter(object):
return self
def __exit__(self, exc_type, exc_value, traceback):
#self.reset()
# self.reset()
pass
def prompt(self, message='', **kwargs):

View file

@ -79,6 +79,7 @@ class Replayer(object):
_REPLAY_PARSER = None
def _rp_create_parser(p=None):
global _REPLAY_PARSER
p_was_none = (p is None)

View file

@ -22,6 +22,7 @@ import threading
from xonsh.lazyasd import LazyObject, lazyobject
from xonsh.platform import ON_WINDOWS
#
# Explicit lazy imports for windows
#
@ -65,6 +66,7 @@ RE_HIDDEN_BYTES = LazyObject(lambda: re.compile(b'(\001.*?\002)'),
RE_COLOR = LazyObject(lambda: re.compile(b'\033\[\d+;?\d*m'),
globals(), 'RE_COLOR')
def _findfirst(s, substrs):
"""Finds whichever of the given substrings occurs first in the given string
and returns that substring, or returns None if no such strings occur.
@ -246,7 +248,7 @@ class TeePTY(object):
def _sanatize_data(self, data):
i, flag = _findfirst(data, ALTERNATE_MODE_FLAGS)
if flag is None and self._in_alt_mode:
return b''
return b''
elif flag is not None:
if flag in START_ALTERNATE_MODE:
# This code is executed when the child process switches the terminal into
@ -354,6 +356,7 @@ class TeePTY(object):
if 0.0 < delay:
time.sleep(delay)
def _teepty_main():
tpty = TeePTY()
tpty.spawn(sys.argv[1:])
@ -363,4 +366,3 @@ def _teepty_main():
print(tpty)
print('-=-'*10)
print('Returned with status {0}'.format(tpty.wcode))

View file

@ -17,6 +17,7 @@ import itertools
from xonsh.lazyasd import lazyobject, lazybool
@lazybool
def _HAVE_RESOURCE():
try:

View file

@ -23,6 +23,7 @@ terminal = LazyObject(lambda: importlib.import_module(
pyghooks = LazyObject(lambda: importlib.import_module('xonsh.pyghooks'),
globals(), 'pyghooks')
class TracerType(object):
"""Represents a xonsh tracer object, which keeps track of all tracing
state. This is a singleton.
@ -165,7 +166,7 @@ def _color(ns, args):
def _tracer_create_parser():
"""Creates tracer argument parser"""
p = argparse.ArgumentParser(prog='trace',
description='tool for tracing xonsh code as it runs.')
description='tool for tracing xonsh code as it runs.')
subp = p.add_subparsers(title='action', dest='action')
onp = subp.add_parser('on', aliases=['start', 'add'],
help='begins tracing selected files.')
@ -200,4 +201,3 @@ def tracermain(args=None):
parser = _tracer_create_parser()
ns = parser.parse_args(args)
return _TRACER_MAIN_ACTIONS[ns.action](ns, args)

View file

@ -140,7 +140,6 @@ class Vox:
print('Available environments:')
print('\n'.join(env_dirs))
@staticmethod
def remove_envs(*names):
"""Remove virtual environments.

View file

@ -74,7 +74,6 @@ class ShellExecuteInfo(ctypes.Structure):
setattr(self, field_name, field_value)
@lazyobject
def ShellExecuteEx():
see = ctypes.windll.Shell32.ShellExecuteExA

View file

@ -9,6 +9,7 @@ import textwrap
from xonsh.tools import to_bool, to_bool_or_break, backup_file, print_color
#
# Nodes themselves
#
@ -167,6 +168,7 @@ class YesNo(Question):
super().__init__(question, responses, converter=to_bool,
path=path)
class TrueFalse(Input):
"""Input node the returns a True or False value."""
@ -279,7 +281,10 @@ def create_truefalse_cond(prompt='yes or no [default: no]? ', path=None):
# Tools for trees of nodes.
#
_lowername = lambda cls: cls.__name__.lower()
def _lowername(cls):
return cls.__name__.lower()
class Visitor(object):
"""Super-class for all classes that should walk over a tree of nodes.
@ -512,6 +517,7 @@ YN = "{GREEN}yes{NO_COLOR} or {RED}no{NO_COLOR} [default: no]? "
YNB = ('{GREEN}yes{NO_COLOR}, {RED}no{NO_COLOR}, or '
'{YELLOW}break{NO_COLOR} [default: no]? ')
class PromptVisitor(StateVisitor):
"""Visits the nodes in the tree via the a command-line prompt."""
@ -569,7 +575,7 @@ class PromptVisitor(StateVisitor):
else:
raise
if node.show_conversion and x is not Unstorable \
and str(x) != raw:
and str(x) != raw:
msg = '{{BOLD_PURPLE}}Converted{{NO_COLOR}} input {0!r} to {1!r}.'
print_color(msg.format(raw, x))
else:

View file

@ -112,11 +112,11 @@ def _list(ns):
def _create_xontrib_parser():
# parse command line args
parser = argparse.ArgumentParser(prog='xontrib',
description='Manages xonsh extensions')
description='Manages xonsh extensions')
subp = parser.add_subparsers(title='action', dest='action')
load = subp.add_parser('load', help='loads xontribs')
load.add_argument('-v', '--verbose', action='store_true', default=False,
dest='verbose')
dest='verbose')
load.add_argument('names', nargs='+', default=(),
help='names of xontribs')
lyst = subp.add_parser('list', help=('list xontribs, whether they are '
@ -133,6 +133,7 @@ _MAIN_XONTRIB_ACTIONS = {
'list': _list,
}
def xontribs_main(args=None, stdin=None):
"""Alias that loads xontribs"""
if not args or (args[0] not in _MAIN_XONTRIB_ACTIONS and
@ -143,4 +144,3 @@ def xontribs_main(args=None, stdin=None):
if ns.action is None: # apply default action
ns = parser.parse_args(['load'] + args)
return _MAIN_XONTRIB_ACTIONS[ns.action](ns)

View file

@ -2,6 +2,7 @@
from xonsh.proc import foreground as _foreground
@_foreground
def _mpl(args, stdin=None):
"""Hooks to matplotlib"""

View file

@ -7,6 +7,7 @@ import matplotlib.pyplot as plt
from xonsh.tools import print_color, ON_WINDOWS
def figure_to_rgb_array(fig, width, height):
"""Converts figure to a numpy array of rgb values
@ -43,7 +44,7 @@ def buf_to_color_str(buf):
for h in range(buf.shape[0]):
last = None
for w in range(buf.shape[1]):
rgb = buf[h,w]
rgb = buf[h, w]
if last is not None and (last == rgb).all():
pixels.append(space)
else: