response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Determines the command for Bash on windows.
def windows_bash_command(): """Determines the command for Bash on windows.""" # Check that bash is on path otherwise try the default directory # used by Git for windows from xonsh.built_ins import XSH wbc = "bash" cmd_cache = XSH.commands_cache bash_on_path = cmd_cache.lazy_locate_binary("b...
This dispatches to the correct, case-sensitive version of os.environ. This is mainly a problem for Windows. See #2024 for more details. This can probably go away once support for Python v3.5 or v3.6 is dropped.
def os_environ(): """This dispatches to the correct, case-sensitive version of os.environ. This is mainly a problem for Windows. See #2024 for more details. This can probably go away once support for Python v3.5 or v3.6 is dropped. """ if ON_WINDOWS: return OSEnvironCasePreserving() ...
Determines the command for Bash on the current platform.
def bash_command(): """Determines the command for Bash on the current platform.""" if (bc := os.getenv("XONSH_BASH_PATH_OVERRIDE", None)) is not None: bc = str(bc) # for pathlib Paths elif ON_WINDOWS: bc = windows_bash_command() else: bc = "bash" return bc
A possibly empty tuple with default paths to Bash completions known for the current platform.
def BASH_COMPLETIONS_DEFAULT(): """A possibly empty tuple with default paths to Bash completions known for the current platform. """ if ON_LINUX or ON_CYGWIN or ON_MSYS: bcd = ("/usr/share/bash-completion/bash_completion",) elif ON_DARWIN: bcd = ( "/usr/local/share/bash-...
The platform dependent libc implementation.
def LIBC(): """The platform dependent libc implementation.""" global ctypes if ON_DARWIN: import ctypes.util libc = ctypes.CDLL(ctypes.util.find_library("c")) elif ON_CYGWIN: libc = ctypes.CDLL("cygwin1.dll") elif ON_MSYS: libc = ctypes.CDLL("msys-2.0.dll") ...
Safe version of getattr. Same as getattr, but will return ``default`` on any Exception, rather than raising.
def _safe_getattr(obj, attr, default=None): """Safe version of getattr. Same as getattr, but will return ``default`` on any Exception, rather than raising. """ try: return getattr(obj, attr, default) except Exception: return default
Pretty print the object's representation.
def pretty( obj, verbose=False, max_width=79, newline="\n", max_seq_length=MAX_SEQ_LENGTH ): """ Pretty print the object's representation. """ if _safe_getattr(obj, "xonsh_display"): return obj.xonsh_display() stream = io.StringIO() printer = RepresentationPrinter( stream, v...
Like pretty() but print to stdout.
def pretty_print( obj, verbose=False, max_width=79, newline="\n", max_seq_length=MAX_SEQ_LENGTH ): """ Like pretty() but print to stdout. """ printer = RepresentationPrinter( sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length ) printer.pretty(obj) printer.flus...
Get a reasonable method resolution order of a class and its superclasses for both old-style and new-style classes.
def _get_mro(obj_class): """Get a reasonable method resolution order of a class and its superclasses for both old-style and new-style classes. """ if not hasattr(obj_class, "__mro__"): # Old-style class. Mix in object to make a fake new-style class. try: obj_class = type(obj...
The default print function. Used if an object does not provide one and it's none of the builtin objects.
def _default_pprint(obj, p, cycle): """ The default print function. Used if an object does not provide one and it's none of the builtin objects. """ klass = _safe_getattr(obj, "__class__", None) or type(obj) if _safe_getattr(klass, "__repr__", None) not in _baseclass_reprs: # A user-pro...
Factory that returns a pprint function useful for sequences. Used by the default pprint for tuples, dicts, and lists.
def _seq_pprinter_factory(start, end, basetype): """ Factory that returns a pprint function useful for sequences. Used by the default pprint for tuples, dicts, and lists. """ def inner(obj, p, cycle): typ = type(obj) if ( basetype is not None and typ is not ...
Factory that returns a pprint function useful for sets and frozensets.
def _set_pprinter_factory(start, end, basetype): """ Factory that returns a pprint function useful for sets and frozensets. """ def inner(obj, p, cycle): typ = type(obj) if ( basetype is not None and typ is not basetype and typ.__repr__ != basetype.__...
Factory that returns a pprint function used by the default pprint of dicts and dict proxies.
def _dict_pprinter_factory(start, end, basetype=None): """ Factory that returns a pprint function used by the default pprint of dicts and dict proxies. """ def inner(obj, p, cycle): typ = type(obj) if ( basetype is not None and typ is not basetype ...
The pprint for the super type.
def _super_pprint(obj, p, cycle): """The pprint for the super type.""" p.begin_group(8, "<super: ") p.pretty(obj.__thisclass__) p.text(",") p.breakable() p.pretty(obj.__self__) p.end_group(8, ">")
The pprint function for regular expression patterns.
def _re_pattern_pprint(obj, p, cycle): """The pprint function for regular expression patterns.""" p.text("re.compile(") pattern = repr(obj.pattern) if pattern[:1] in "uU": pattern = pattern[1:] prefix = "ur" else: prefix = "r" pattern = prefix + pattern.replace("\\\\", "...
The pprint for classes and types.
def _type_pprint(obj, p, cycle): """The pprint for classes and types.""" # Heap allocated types might not have the module attribute, # and others may set it to None. # Checks for a __repr__ override in the metaclass if type(obj).__repr__ is not type.__repr__: _repr_pprint(obj, p, cycle) ...
A pprint that just redirects to the normal repr function.
def _repr_pprint(obj, p, cycle): """A pprint that just redirects to the normal repr function.""" # Find newlines and replace them with p.break_() output = repr(obj) for idx, output_line in enumerate(output.splitlines()): if idx: p.break_() p.text(output_line)
Base pprint for all functions and builtin functions.
def _function_pprint(obj, p, cycle): """Base pprint for all functions and builtin functions.""" name = _safe_getattr(obj, "__qualname__", obj.__name__) mod = obj.__module__ if mod and mod not in ("__builtin__", "builtins", "exceptions"): name = mod + "." + name p.text(f"<function {name}>")
Base pprint for all exceptions.
def _exception_pprint(obj, p, cycle): """Base pprint for all exceptions.""" name = getattr(obj.__class__, "__qualname__", obj.__class__.__name__) if obj.__class__.__module__ not in ("exceptions", "builtins"): name = f"{obj.__class__.__module__}.{name}" step = len(name) + 1 p.begin_group(step...
Add a pretty printer for a given type.
def for_type(typ, func): """ Add a pretty printer for a given type. """ oldfunc = _type_pprinters.get(typ, None) if func is not None: # To support easy restoration of old pprinters, we need to ignore Nones. _type_pprinters[typ] = func return oldfunc
Add a pretty printer for a type specified by the module and name of a type rather than the type object itself.
def for_type_by_name(type_module, type_name, func, dtp=None): """ Add a pretty printer for a type specified by the module and name of a type rather than the type object itself. """ if dtp is None: dtp = _deferred_type_pprinters key = (type_module, type_name) oldfunc = dtp.get(key, No...
Converts a color name to a color token, foreground name, and background name. Will take into consideration current foreground and background colors, if provided. Parameters ---------- name : str Color name. fg : str, optional Foreground color name. bg : str, optional Background color name. Returns ------...
def color_by_name(name, fg=None, bg=None): """Converts a color name to a color token, foreground name, and background name. Will take into consideration current foreground and background colors, if provided. Parameters ---------- name : str Color name. fg : str, optional Fo...
Converts a xonsh color name to a pygments color code.
def color_name_to_pygments_code(name, styles): """Converts a xonsh color name to a pygments color code.""" token = getattr(Color, norm_name(name)) if token in styles: return styles[token] m = RE_XONSH_COLOR.match(name) if m is None: raise ValueError(f"{name!r} is not a color!") p...
Converts a token name into a pygments-style color code. Parameters ---------- name : str Color token name. styles : Mapping Mapping for looking up non-hex colors Returns ------- code : str Pygments style color code.
def code_by_name(name, styles): """Converts a token name into a pygments-style color code. Parameters ---------- name : str Color token name. styles : Mapping Mapping for looking up non-hex colors Returns ------- code : str Pygments style color code. """ ...
Returns (color) token corresponding to Xonsh color tuple, side effect: defines token is defined in styles
def color_token_by_name(xc: tuple, styles=None) -> _TokenType: """Returns (color) token corresponding to Xonsh color tuple, side effect: defines token is defined in styles""" if not styles: try: styles = XSH.shell.shell.styler.styles # type:ignore except AttributeError: ...
Tokenizes a template string containing colors. Will return a list of tuples mapping the token to the string which has that color. These sub-strings maybe templates themselves.
def partial_color_tokenize(template): """Tokenizes a template string containing colors. Will return a list of tuples mapping the token to the string which has that color. These sub-strings maybe templates themselves. """ if XSH.shell is not None: styles = XSH.shell.shell.styler.styles e...
Factory for a proxy class to a xonsh style.
def xonsh_style_proxy(styler): """Factory for a proxy class to a xonsh style.""" # Monky patch pygments' list of known ansi colors # with the new ansi color names used by PTK2 # Can be removed once pygment names get fixed. if pygments_version_info() and pygments_version_info() < (2, 4, 0): p...
Checks if the given value is PTK style specific
def _ptk_specific_style_value(style_value): """Checks if the given value is PTK style specific""" for ptk_spec in PTK_SPECIFIC_VALUES: if ptk_spec in style_value: return True return False
Format PTK style name to be able to include it in a pygments style
def _format_ptk_style_name(name): """Format PTK style name to be able to include it in a pygments style""" parts = name.split("-") return "".join(part.capitalize() for part in parts)
Get pygments token object by its string representation.
def _get_token_by_name(name): """Get pygments token object by its string representation.""" if not isinstance(name, str): return name token = Token parts = name.split(".") # PTK - all lowercase if parts[0] == parts[0].lower(): parts = ["PTK"] + [_format_ptk_style_name(part) for...
Converts possible string keys in style dicts to Tokens
def _tokenize_style_dict(styles): """Converts possible string keys in style dicts to Tokens""" return { _get_token_by_name(token): value for token, value in styles.items() if not _ptk_specific_style_value(value) }
Register custom style. Parameters ---------- name : str Style name. styles : dict Token -> style mapping. highlight_color : str Hightlight color. background_color : str Background color. base : str, optional Base style to use as default. Returns ------- style : The ``pygments.Style`` subclass crea...
def register_custom_pygments_style( name, styles, highlight_color=None, background_color=None, base="default" ): """Register custom style. Parameters ---------- name : str Style name. styles : dict Token -> style mapping. highlight_color : str Hightlight color. b...
Makes a pygments style based on a color palette.
def make_pygments_style(palette): """Makes a pygments style based on a color palette.""" global Color style = {Color.DEFAULT: "noinherit"} for name, t in BASE_XONSH_COLORS.items(): color = find_closest_color(t, palette) style[getattr(Color, name)] = "#" + color return style
Gets or makes a pygments color style by its name.
def pygments_style_by_name(name): """Gets or makes a pygments color style by its name.""" if name in STYLES: return STYLES[name] pstyle = get_style_by_name(name) palette = make_palette(pstyle.styles.values()) astyle = make_pygments_style(palette) STYLES[name] = astyle return astyle
Monky patch pygments' dict of console codes, with new color names
def _monkey_patch_pygments_codes(): """Monky patch pygments' dict of console codes, with new color names """ if pygments_version_info() and pygments_version_info() >= (2, 4, 0): return import pygments.console if "brightblack" in pygments.console.codes: # Assume that colors are ...
if LS_COLORS updated, update file_color_tokens and corresponding color token in style
def on_lscolors_change(key, oldvalue, newvalue, **kwargs): """if LS_COLORS updated, update file_color_tokens and corresponding color token in style""" if newvalue is None: del file_color_tokens[key] else: file_color_tokens[key] = color_token_by_name(newvalue)
Determine color to use for file *approximately* as ls --color would, given lstat() results and its path. Parameters ---------- file_path relative path of file (as user typed it). path_stat lstat() results for file_path. Returns ------- color token, color_key Notes ----- * implementation follows one author...
def color_file(file_path: str, path_stat: os.stat_result) -> tuple[_TokenType, str]: """Determine color to use for file *approximately* as ls --color would, given lstat() results and its path. Parameters ---------- file_path relative path of file (as user typed it). path_stat ...
Yield Builtin token if match contains valid command, otherwise fallback to fallback lexer.
def subproc_cmd_callback(_, match): """Yield Builtin token if match contains valid command, otherwise fallback to fallback lexer. """ cmd = match.group() yield match.start(), Name.Builtin if _command_is_valid(cmd) else Error, cmd
Check if match contains valid path
def subproc_arg_callback(_, match): """Check if match contains valid path""" text = match.group() yieldVal = Text try: path = os.path.expanduser(text) path_stat = os.lstat(path) # lstat() will raise FNF if not a real file yieldVal, _ = color_file(path, path_stat) except OSEr...
Does the hard work of building a cache from nothing.
def build_cache(): """Does the hard work of building a cache from nothing.""" cache = {} cache["lexers"] = _discover_lexers() cache["formatters"] = _discover_formatters() cache["styles"] = _discover_styles() cache["filters"] = _discover_filters() return cache
Gets the name of the cache file to use.
def cache_filename(): """Gets the name of the cache file to use.""" # Configuration variables read from the environment if "PYGMENTS_CACHE_FILE" in os.environ: return os.environ["PYGMENTS_CACHE_FILE"] else: return os.path.join( os.environ.get( "XDG_DATA_HOME",...
Register custom style to be able to retrieve it by ``get_style_by_name``. Parameters ---------- name Style name. style Custom style to add.
def add_custom_style(name: str, style: "Style"): """Register custom style to be able to retrieve it by ``get_style_by_name``. Parameters ---------- name Style name. style Custom style to add. """ CUSTOM_STYLES[name] = style
Loads the cache from a filename.
def load(filename): """Loads the cache from a filename.""" global CACHE with open(filename) as f: s = f.read() ctx = globals() CACHE = eval(s, ctx, ctx) return CACHE
Writes the current cache to the file
def write_cache(filename): """Writes the current cache to the file""" from pprint import pformat d = os.path.dirname(filename) os.makedirs(d, exist_ok=True) s = pformat(CACHE) with open(filename, "w") as f: f.write(s)
Loads the cache from disk. If the cache does not exist, this will build and write it out.
def load_or_build(): """Loads the cache from disk. If the cache does not exist, this will build and write it out. """ global CACHE fname = cache_filename() if os.path.exists(fname): load(fname) else: import sys if DEBUG: print("pygments cache not found...
Gets a lexer from a filename (usually via the filename extension). This mimics the behavior of ``pygments.lexers.get_lexer_for_filename()`` and ``pygments.lexers.guess_lexer_for_filename()``.
def get_lexer_for_filename(filename, text="", **options): """Gets a lexer from a filename (usually via the filename extension). This mimics the behavior of ``pygments.lexers.get_lexer_for_filename()`` and ``pygments.lexers.guess_lexer_for_filename()``. """ if CACHE is None: load_or_build() ...
Gets a formatter instance from a filename (usually via the filename extension). This mimics the behavior of ``pygments.formatters.get_formatter_for_filename()``.
def get_formatter_for_filename(fn, **options): """Gets a formatter instance from a filename (usually via the filename extension). This mimics the behavior of ``pygments.formatters.get_formatter_for_filename()``. """ if CACHE is None: load_or_build() exts = CACHE["formatters"]["exts"] ...
Gets a formatter instance from its name or alias. This mimics the behavior of ``pygments.formatters.get_formatter_by_name()``.
def get_formatter_by_name(alias, **options): """Gets a formatter instance from its name or alias. This mimics the behavior of ``pygments.formatters.get_formatter_by_name()``. """ if CACHE is None: load_or_build() names = CACHE["formatters"]["names"] if alias in names: modname, c...
Gets a style class from its name or alias. This mimics the behavior of ``pygments.styles.get_style_by_name()``.
def get_style_by_name(name): """Gets a style class from its name or alias. This mimics the behavior of ``pygments.styles.get_style_by_name()``. """ if CACHE is None: load_or_build() names = CACHE["styles"]["names"] if name in names: modname, clsname = names[name] mod = i...
Iterable through all known style names. This mimics the behavior of ``pygments.styles.get_all_styles``.
def get_all_styles(): """Iterable through all known style names. This mimics the behavior of ``pygments.styles.get_all_styles``. """ if CACHE is None: load_or_build() yield from CACHE["styles"]["names"] yield from CUSTOM_STYLES
Gets a filter instance from its name. This mimics the behavior of ``pygments.filters.get_filtere_by_name()``.
def get_filter_by_name(filtername, **options): """Gets a filter instance from its name. This mimics the behavior of ``pygments.filters.get_filtere_by_name()``. """ if CACHE is None: load_or_build() names = CACHE["filters"]["names"] if filtername in names: modname, clsname = name...
Sets up the readline module and completion suppression, if available.
def setup_readline(): """Sets up the readline module and completion suppression, if available.""" global \ RL_COMPLETION_SUPPRESS_APPEND, \ RL_LIB, \ RL_CAN_RESIZE, \ RL_STATE, \ readline, \ RL_COMPLETION_QUERY_ITEMS if RL_COMPLETION_SUPPRESS_APPEND is not Non...
Tears down up the readline module, if available.
def teardown_readline(): """Tears down up the readline module, if available.""" try: import readline except (ImportError, TypeError): return
Fix to allow Ctrl-C to exit reverse-i-search. Based on code from: http://bugs.python.org/file39467/raw_input__workaround_demo.py
def fix_readline_state_after_ctrl_c(): """ Fix to allow Ctrl-C to exit reverse-i-search. Based on code from: http://bugs.python.org/file39467/raw_input__workaround_demo.py """ if ON_WINDOWS: # hack to make pyreadline mimic the desired behavior try: _q = readline....
Sets the rl_completion_suppress_append variable, if possible. A value of 1 (default) means to suppress, a value of 0 means to enable.
def rl_completion_suppress_append(val=1): """Sets the rl_completion_suppress_append variable, if possible. A value of 1 (default) means to suppress, a value of 0 means to enable. """ if RL_COMPLETION_SUPPRESS_APPEND is None: return RL_COMPLETION_SUPPRESS_APPEND.value = val
Sets the rl_completion_query_items variable, if possible. A None value will set this to $COMPLETION_QUERY_LIMIT, otherwise any integer is accepted.
def rl_completion_query_items(val=None): """Sets the rl_completion_query_items variable, if possible. A None value will set this to $COMPLETION_QUERY_LIMIT, otherwise any integer is accepted. """ if RL_COMPLETION_QUERY_ITEMS is None: return if val is None: val = XSH.env.get("COMP...
Dumps the currently set readline variables. If readable is True, then this output may be used in an inputrc file.
def rl_variable_dumper(readable=True): """Dumps the currently set readline variables. If readable is True, then this output may be used in an inputrc file. """ RL_LIB.rl_variable_dumper(int(readable))
Returns the currently set value for a readline configuration variable.
def rl_variable_value(variable): """Returns the currently set value for a readline configuration variable.""" global RL_VARIABLE_VALUE if RL_VARIABLE_VALUE is None: import ctypes RL_VARIABLE_VALUE = RL_LIB.rl_variable_value RL_VARIABLE_VALUE.restype = ctypes.c_char_p env = XSH.e...
Grabs one of a few possible redisplay functions in readline.
def rl_on_new_line(): """Grabs one of a few possible redisplay functions in readline.""" names = ["rl_on_new_line", "rl_forced_update_display", "rl_redisplay"] for name in names: func = getattr(RL_LIB, name, None) if func is not None: break else: def print_for_new...
Creates a function to insert text via readline.
def _insert_text_func(s, readline): """Creates a function to insert text via readline.""" def inserter(): readline.insert_text(s) readline.redisplay() return inserter
Render the completions according to the required prefix_len. Readline will replace the current prefix with the chosen rendered completion.
def _render_completions(completions, prefix, prefix_len): """Render the completions according to the required prefix_len. Readline will replace the current prefix with the chosen rendered completion. """ chopped = prefix[:-prefix_len] if prefix_len else prefix rendered_completions = [] for com...
Returns the results of firing the precommand handles.
def transform_command(src, show_diff=True): """Returns the results of firing the precommand handles.""" i = 0 limit = sys.getrecursionlimit() lst = "" raw = src while src != lst: lst = src srcs = events.on_transform_command.fire(cmd=src) for s in srcs: if s...
Tokenizes a template string containing colors. Will return a list of tuples mapping the token to the string which has that color. These sub-strings maybe templates themselves.
def partial_color_tokenize(template): """Tokenizes a template string containing colors. Will return a list of tuples mapping the token to the string which has that color. These sub-strings maybe templates themselves. """ from xonsh.built_ins import XSH if HAS_PYGMENTS and XSH.shell is not None:...
Converts a color name to a color token, foreground name, and background name. Will take into consideration current foreground and background colors, if provided. Parameters ---------- name : str Color name. fg : str, optional Foreground color name. bg : str, optional Background color name. Returns ------...
def color_by_name(name, fg=None, bg=None): """Converts a color name to a color token, foreground name, and background name. Will take into consideration current foreground and background colors, if provided. Parameters ---------- name : str Color name. fg : str, optional Fo...
Normalizes a color name.
def norm_name(name): """Normalizes a color name.""" return name.upper().replace("#", "HEX")
Remove the colors from the template string and style as faded.
def style_as_faded(template: str) -> str: """Remove the colors from the template string and style as faded.""" tokens = partial_color_tokenize(template) without_color = "".join([str(sect) for _, sect in tokens]) return "{RESET}{#d3d3d3}" + without_color + "{RESET}"
Formats the timespan in a human readable form
def format_time(timespan, precision=3): """Formats the timespan in a human readable form""" if timespan >= 60.0: # we have more than a minute, format that in a human readable form parts = [("d", 60 * 60 * 24), ("h", 60 * 60), ("min", 60), ("s", 1)] time = [] leftover = timespan ...
Runs timing study on arguments.
def timeit_alias(args, stdin=None): """Runs timing study on arguments.""" if not args: print("Usage: timeit! <expression>") return -1 # some real args number = 0 quiet = False repeat = 3 precision = 3 # setup ctx = XSH.ctx timer = Timer(timer=clock) stmt = " "...
Transform tokens back into Python source code. It returns a bytes object, encoded using the ENCODING token, which is the first token sequence output by tokenize. Each element returned by the iterable must be a token sequence with at least two elements, a token number and token value. If only two tokens are passed, th...
def untokenize(iterable): """Transform tokens back into Python source code. It returns a bytes object, encoded using the ENCODING token, which is the first token sequence output by tokenize. Each element returned by the iterable must be a token sequence with at least two elements, a token number an...
Imitates get_normal_name in tokenizer.c.
def _get_normal_name(orig_enc): """Imitates get_normal_name in tokenizer.c.""" # Only care about the first 12 characters. enc = orig_enc[:12].lower().replace("_", "-") if enc == "utf-8" or enc.startswith("utf-8-"): return "utf-8" if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or enc.star...
The detect_encoding() function is used to detect the encoding that should be used to decode a Python source file. It requires one argument, readline, in the same way as the tokenize() generator. It will call readline a maximum of twice, and return the encoding used (as a string) and a list of any lines (left as bytes...
def detect_encoding(readline): """ The detect_encoding() function is used to detect the encoding that should be used to decode a Python source file. It requires one argument, readline, in the same way as the tokenize() generator. It will call readline a maximum of twice, and return the encoding us...
Open a file in read only mode using the encoding detected by detect_encoding().
def tokopen(filename): """Open a file in read only mode using the encoding detected by detect_encoding(). """ buffer = builtins.open(filename, "rb") try: encoding, lines = detect_encoding(buffer.readline) buffer.seek(0) text = io.TextIOWrapper(buffer, encoding, line_buffering...
The tokenize() generator requires one argument, readline, which must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as bytes. Alternately, readline can be a callable function terminating with StopItera...
def tokenize(readline, tolerant=False, tokenize_ioredirects=True): """ The tokenize() generator requires one argument, readline, which must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of i...
Takes a string path and expands ~ to home if expand_user is set and environment vars if EXPAND_ENV_VARS is set.
def expand_path(s, expand_user=True): """Takes a string path and expands ~ to home if expand_user is set and environment vars if EXPAND_ENV_VARS is set.""" env = xsh.env or os_environ if env.get("EXPAND_ENV_VARS", False): s = expandvars(s) if expand_user: # expand ~ according to Bas...
Performs environment variable / user expansion on a given path if EXPAND_ENV_VARS is set.
def _expandpath(path): """Performs environment variable / user expansion on a given path if EXPAND_ENV_VARS is set. """ env = xsh.env or os_environ expand_user = env.get("EXPAND_ENV_VARS", False) return expand_path(path, expand_user=expand_user)
Returns random element from the list with length less than 1 million elements.
def simple_random_choice(lst): """Returns random element from the list with length less than 1 million elements.""" size = len(lst) if size > 1000000: # microsecond maximum raise ValueError("The list is too long.") return lst[datetime.datetime.now().microsecond % size]
Tries to decode the bytes using XONSH_ENCODING if available, otherwise using sys.getdefaultencoding().
def decode_bytes(b): """Tries to decode the bytes using XONSH_ENCODING if available, otherwise using sys.getdefaultencoding(). """ env = xsh.env or os_environ enc = env.get("XONSH_ENCODING") or DEFAULT_ENCODING err = env.get("XONSH_ENCODING_ERRORS") or "strict" return b.decode(encoding=enc, ...
Finds whichever of the given substrings occurs first in the given string and returns that substring, or returns None if no such strings occur.
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. """ i = len(s) result = None for substr in substrs: pos = s.find(substr) if -1 < pos < i: i = ...
Tests if an RPAREN token is matched with something other than a plain old LPAREN type.
def _is_not_lparen_and_rparen(lparens, rtok): """Tests if an RPAREN token is matched with something other than a plain old LPAREN type. """ # note that any([]) is False, so this covers len(lparens) == 0 return rtok.type == "RPAREN" and any(x != "LPAREN" for x in lparens)
Determines if parentheses are balanced in an expression.
def balanced_parens(line, mincol=0, maxcol=None, lexer=None): """Determines if parentheses are balanced in an expression.""" line = line[mincol:maxcol] if lexer is None: lexer = xsh.execer.parser.lexer if "(" not in line and ")" not in line: return True cnt = 0 lexer.input(line)...
Determines whether a line ends with a colon token, ignoring comments.
def ends_with_colon_token(line, lexer=None): """Determines whether a line ends with a colon token, ignoring comments.""" if lexer is None: lexer = xsh.execer.parser.lexer lexer.input(line) toks = list(lexer) return len(toks) > 0 and toks[-1].type == "COLON"
Returns the column number of the next logical break in subproc mode. This function may be useful in finding the maxcol argument of subproc_toks().
def find_next_break(line, mincol=0, lexer=None): """Returns the column number of the next logical break in subproc mode. This function may be useful in finding the maxcol argument of subproc_toks(). """ if mincol >= 1: line = line[mincol:] if lexer is None: lexer = xsh.execer.pa...
Encapsulates tokens in a source code line in a uncaptured subprocess ![] starting at a minimum column. If there are no tokens (ie in a comment line) this returns None. If greedy is True, it will encapsulate normal parentheses. Greedy is False by default.
def subproc_toks( line, mincol=-1, maxcol=None, lexer=None, returnline=False, greedy=False ): """Encapsulates tokens in a source code line in a uncaptured subprocess ![] starting at a minimum column. If there are no tokens (ie in a comment line) this returns None. If greedy is True, it will encapsulate ...
Checks if a token is a bad string.
def check_bad_str_token(tok): """Checks if a token is a bad string.""" if tok.type == "ERRORTOKEN" and tok.value == "EOF in multi-line string": return True elif isinstance(tok.value, str) and not check_quotes(tok.value): return True else: return False
Checks a string to make sure that if it starts with quotes, it also ends with quotes.
def check_quotes(s): """Checks a string to make sure that if it starts with quotes, it also ends with quotes. """ starts_as_str = RE_BEGIN_STRING.match(s) is not None ends_as_str = s.endswith('"') or s.endswith("'") if not starts_as_str and not ends_as_str: ok = True elif starts_as_...
The line continuation characters used in subproc mode. In interactive mode on Windows the backslash must be preceded by a space. This is because paths on Windows may end in a backslash.
def get_line_continuation(): """The line continuation characters used in subproc mode. In interactive mode on Windows the backslash must be preceded by a space. This is because paths on Windows may end in a backslash. """ if ON_WINDOWS: env = getattr(xsh, "env", None) or {} if env.g...
Returns a single logical line (i.e. one without line continuations) from a list of lines. This line should begin at index idx. This also returns the number of physical lines the logical line spans. The lines should not contain newlines
def get_logical_line(lines, idx): """Returns a single logical line (i.e. one without line continuations) from a list of lines. This line should begin at index idx. This also returns the number of physical lines the logical line spans. The lines should not contain newlines """ n = 1 nlines =...
Replaces lines at idx that may end in line continuation with a logical line that spans n lines.
def replace_logical_line(lines, logical, idx, n): """Replaces lines at idx that may end in line continuation with a logical line that spans n lines. """ linecont = get_line_continuation() if n == 1: lines[idx] = logical return space = " " for i in range(idx, idx + n - 1): ...
Determines whether an expression has unbalanced opening and closing tokens.
def is_balanced(expr, ltok, rtok): """Determines whether an expression has unbalanced opening and closing tokens.""" lcnt = expr.count(ltok) if lcnt == 0: return True rcnt = expr.count(rtok) if lcnt == rcnt: return True else: return False
Attempts to pull out a valid subexpression for unbalanced grouping, based on opening tokens, eg. '(', and closing tokens, eg. ')'. This does not do full tokenization, but should be good enough for tab completion.
def subexpr_from_unbalanced(expr, ltok, rtok): """Attempts to pull out a valid subexpression for unbalanced grouping, based on opening tokens, eg. '(', and closing tokens, eg. ')'. This does not do full tokenization, but should be good enough for tab completion. """ if is_balanced(expr, ltok, r...
Obtains the expression prior to last unbalanced left token.
def subexpr_before_unbalanced(expr, ltok, rtok): """Obtains the expression prior to last unbalanced left token.""" subexpr, _, post = expr.rpartition(ltok) nrtoks_in_post = post.count(rtok) while nrtoks_in_post != 0: for _ in range(nrtoks_in_post): subexpr, _, post = subexpr.rpartit...
Returns the whitespace at the start of a string
def starting_whitespace(s): """Returns the whitespace at the start of a string""" return STARTING_WHITESPACE_RE.match(s).group(1)
In recent versions of Python, hasattr() only catches AttributeError. This catches all errors.
def safe_hasattr(obj, attr): """In recent versions of Python, hasattr() only catches AttributeError. This catches all errors. """ try: getattr(obj, attr) return True except Exception: return False
Indent a string a given number of spaces or tabstops. indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. Parameters ---------- instr : basestring The string to be indented. nspaces : int (default: 4) The number of spaces to be indented. ntabs : int (default: 0) The number of tabs to be indented...
def indent(instr, nspaces=4, ntabs=0, flatten=False): """Indent a string a given number of spaces or tabstops. indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. Parameters ---------- instr : basestring The string to be indented. nspaces : int (default: 4) The number...
Returns the appropriate filepath separator char depending on OS and xonsh options set
def get_sep(): """Returns the appropriate filepath separator char depending on OS and xonsh options set """ if ON_WINDOWS and xsh.env.get("FORCE_POSIX_PATHS"): return os.altsep else: return os.sep
Decorator for returning the object if cond is true and a backup if cond is false.
def fallback(cond, backup): """Decorator for returning the object if cond is true and a backup if cond is false. """ def dec(obj): return obj if cond else backup return dec
yield file names of executable files in path.
def _yield_accessible_unix_file_names(path): """yield file names of executable files in path.""" if not os.path.exists(path): return for file_ in os.scandir(path): try: if file_.is_file() and os.access(file_.path, os.X_OK): yield file_.name except OSError...
Returns a generator of files in path that the user could execute.
def executables_in(path) -> tp.Iterable[str]: """Returns a generator of files in path that the user could execute.""" if ON_WINDOWS: func = _executables_in_windows else: func = _executables_in_posix try: yield from func(path) except PermissionError: return
Uses the debian/ubuntu command-not-found utility to suggest packages for a command that cannot currently be found.
def debian_command_not_found(cmd): """Uses the debian/ubuntu command-not-found utility to suggest packages for a command that cannot currently be found. """ if not ON_LINUX: return "" cnf = xsh.commands_cache.lazyget( "command-not-found", ("/usr/lib/command-not-found",) )[0] ...
Uses conda-suggest to suggest packages for a command that cannot currently be found.
def conda_suggest_command_not_found(cmd, env): """Uses conda-suggest to suggest packages for a command that cannot currently be found. """ try: from conda_suggest import find except ImportError: return "" return find.message_string( cmd, conda_suggest_path=env.get("CONDA_...