response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Uses various mechanism to suggest packages for a command that cannot currently be found.
def command_not_found(cmd, env): """Uses various mechanism to suggest packages for a command that cannot currently be found. """ if ON_LINUX: rtn = debian_command_not_found(cmd) else: rtn = "" conda = conda_suggest_command_not_found(cmd, env) if conda: rtn = rtn + "\n\n" + conda if rtn else conda return rtn
Suggests alternative commands given an environment and aliases.
def suggest_commands(cmd, env): """Suggests alternative commands given an environment and aliases.""" if not env.get("SUGGEST_COMMANDS"): return "" thresh = env.get("SUGGEST_THRESHOLD") max_sugg = env.get("SUGGEST_MAX_NUM") if max_sugg < 0: max_sugg = float("inf") cmd = cmd.lower() suggested = {} for alias in xsh.aliases: if alias not in suggested: if levenshtein(alias.lower(), cmd, thresh) < thresh: suggested[alias] = "Alias" for _cmd in xsh.commands_cache.all_commands: if _cmd not in suggested: if levenshtein(_cmd.lower(), cmd, thresh) < thresh: suggested[_cmd] = f"Command ({_cmd})" suggested = collections.OrderedDict( sorted( suggested.items(), key=lambda x: suggestion_sort_helper(x[0].lower(), cmd) ) ) num = min(len(suggested), max_sugg) if num == 0: rtn = command_not_found(cmd, env) else: oneof = "" if num == 1 else "one of " tips = f"Did you mean {oneof}the following?" items = list(suggested.popitem(False) for _ in range(num)) length = max(len(key) for key, _ in items) + 2 alternatives = "\n".join( " {: <{}} {}".format(key + ":", length, val) for key, val in items ) rtn = f"{tips}\n{alternatives}" c = command_not_found(cmd, env) rtn += ("\n\n" + c) if len(c) > 0 else "" return rtn
Returns if the given variable is manually set as well as it's value.
def _get_manual_env_var(name, default=None): """Returns if the given variable is manually set as well as it's value.""" env = getattr(xsh, "env", None) if env is None: env = os_environ manually_set = name in env else: manually_set = env.is_manually_set(name) value = env.get(name, default) return (manually_set, value)
Print warnings with/without traceback.
def print_warning(msg): """Print warnings with/without traceback.""" manually_set_trace, show_trace = _get_manual_env_var("XONSH_SHOW_TRACEBACK", False) manually_set_logfile, log_file = _get_manual_env_var("XONSH_TRACEBACK_LOGFILE") if (not manually_set_trace) and (not manually_set_logfile): # Notify about the traceback output possibility if neither of # the two options have been manually set sys.stderr.write( "xonsh: For full traceback set: " "$XONSH_SHOW_TRACEBACK = True\n" ) # convert show_trace to bool if necessary if not is_bool(show_trace): show_trace = to_bool(show_trace) # if the trace option has been set, print all traceback info to stderr if show_trace: # notify user about XONSH_TRACEBACK_LOGFILE if it has # not been set manually if not manually_set_logfile: sys.stderr.write( "xonsh: To log full traceback to a file set: " "$XONSH_TRACEBACK_LOGFILE = <filename>\n" ) traceback.print_stack() # additionally, check if a file for traceback logging has been # specified and convert to a proper option if needed log_file = to_logfile_opt(log_file) if log_file: # if log_file <> '' or log_file <> None, append # traceback log there as well with open(os.path.abspath(log_file), "a") as f: traceback.print_stack(file=f) msg = msg if msg.endswith("\n") else msg + "\n" sys.stderr.write(msg)
Print given exception (or current if None) with/without traceback and set sys.last_type, sys.last_value, sys.last_traceback accordingly.
def print_exception(msg=None, exc_info=None, source_msg=None): """Print given exception (or current if None) with/without traceback and set sys.last_type, sys.last_value, sys.last_traceback accordingly.""" # is no exec_info() triple is given, use the exception beeing handled at the moment if exc_info is None: exc_info = sys.exc_info() # these values (initialized with their default for traceback.print_exception) control how an exception is printed limit = None chain = True _, debug_level = _get_manual_env_var("XONSH_DEBUG", 0) # the interal state of the parsers stack is # not helpful in normal operation (XONSH_DEBUG == 0). # this is also done to be consistent with python is_syntax_error = issubclass(exc_info[0], SyntaxError) # XonshErrors don't show where in the users code they occured # (most are reported deeper in the callstack, e.g. see procs/pipelines.py), # but only show non-helpful xonsh internals. # These are only relevent when developing/debugging xonsh itself. # Therefore, dont print these traces until this gets overhauled. is_xonsh_error = exc_info[0] in (XonshError, XonshCalledProcessError) # hide unhelpful traces if not debugging hide_stacktrace = debug_level == 0 and (is_syntax_error or is_xonsh_error) if hide_stacktrace: limit = 0 chain = False sys.last_type, sys.last_value, sys.last_traceback = exc_info manually_set_trace, show_trace = _get_manual_env_var("XONSH_SHOW_TRACEBACK", False) manually_set_logfile, log_file = _get_manual_env_var("XONSH_TRACEBACK_LOGFILE") if (not manually_set_trace) and (not manually_set_logfile): # Notify about the traceback output possibility if neither of # the two options have been manually set sys.stderr.write( "xonsh: For full traceback set: " "$XONSH_SHOW_TRACEBACK = True\n" ) # convert show_trace to bool if necessary if not is_bool(show_trace): show_trace = to_bool(show_trace) if source_msg: sys.stderr.write(source_msg + "\n") # if the trace option has been set, print all traceback info to stderr if show_trace: # notify user about XONSH_TRACEBACK_LOGFILE if it has # not been set manually if not manually_set_logfile: sys.stderr.write( "xonsh: To log full traceback to a file set: " "$XONSH_TRACEBACK_LOGFILE = <filename>\n" ) display_colored_error_message(exc_info) # additionally, check if a file for traceback logging has been # specified and convert to a proper option if needed log_file = to_logfile_opt(log_file) if log_file: # if log_file <> '' or log_file <> None, append # traceback log there as well with open(os.path.abspath(log_file), "a") as f: traceback.print_exception(*exc_info, limit=limit, chain=chain, file=f) if not show_trace: # if traceback output is disabled, print the exception's # error message on stderr. if not xsh.env.get("XONSH_SHOW_TRACEBACK") and xsh.env.get( "RAISE_SUBPROC_ERROR" ): display_colored_error_message(exc_info, limit=1) return display_error_message(exc_info) if msg: msg = msg if msg.endswith("\n") else msg + "\n" sys.stderr.write(msg)
Prints the error message of the given sys.exc_info() triple on stderr.
def display_error_message(exc_info, strip_xonsh_error_types=True): """ Prints the error message of the given sys.exc_info() triple on stderr. """ exc_type, exc_value, exc_traceback = exc_info exception_only = traceback.format_exception_only(exc_type, exc_value) if exc_type is XonshError and strip_xonsh_error_types: exception_only[0] = exception_only[0].partition(": ")[-1] sys.stderr.write("".join(exception_only))
Checks if a filepath is valid for writing.
def is_writable_file(filepath): """ Checks if a filepath is valid for writing. """ filepath = expand_path(filepath) # convert to absolute path if needed if not os.path.isabs(filepath): filepath = os.path.abspath(filepath) # cannot write to directories if os.path.isdir(filepath): return False # if the file exists and is writable, we're fine if os.path.exists(filepath): return True if os.access(filepath, os.W_OK) else False # if the path doesn't exist, isolate its directory component # and ensure that directory is writable instead return os.access(os.path.dirname(filepath), os.W_OK)
Calculates the Levenshtein distance between a and b.
def levenshtein(a, b, max_dist=float("inf")): """Calculates the Levenshtein distance between a and b.""" n, m = len(a), len(b) if abs(n - m) > max_dist: return float("inf") if n > m: # Make sure n <= m, to use O(min(n,m)) space a, b = b, a n, m = m, n current = range(n + 1) for i in range(1, m + 1): previous, current = current, [i] + [0] * n for j in range(1, n + 1): add, delete = previous[j] + 1, current[j - 1] + 1 change = previous[j - 1] if a[j - 1] != b[i - 1]: change = change + 1 current[j] = min(add, delete, change) return current[n]
Returns a score (lower is better) for x based on how similar it is to y. Used to rank suggestions.
def suggestion_sort_helper(x, y): """Returns a score (lower is better) for x based on how similar it is to y. Used to rank suggestions.""" x = x.lower() y = y.lower() lendiff = len(x) + len(y) inx = len([i for i in x if i not in y]) iny = len([i for i in y if i not in x]) return lendiff + inx + iny
Returns a string that is usable by the Windows cmd.exe. The escaping is based on details here and empirical testing: http://www.robvanderwoude.com/escapechars.php
def escape_windows_cmd_string(s): """Returns a string that is usable by the Windows cmd.exe. The escaping is based on details here and empirical testing: http://www.robvanderwoude.com/escapechars.php """ for c in '^()%!<>&|"': s = s.replace(c, "^" + c) return s
Returns an argument quoted in such a way that that CommandLineToArgvW on Windows will return the argument string unchanged. This is the same thing Popen does when supplied with an list of arguments. Arguments in a command line should be separated by spaces; this function does not add these spaces. This implementation follows the suggestions outlined here: https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/
def argvquote(arg, force=False): """Returns an argument quoted in such a way that that CommandLineToArgvW on Windows will return the argument string unchanged. This is the same thing Popen does when supplied with an list of arguments. Arguments in a command line should be separated by spaces; this function does not add these spaces. This implementation follows the suggestions outlined here: https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/ """ if not force and len(arg) != 0 and not any([c in arg for c in ' \t\n\v"']): return arg else: n_backslashes = 0 cmdline = '"' for c in arg: if c == "\\": # first count the number of current backslashes n_backslashes += 1 continue if c == '"': # Escape all backslashes and the following double quotation mark cmdline += (n_backslashes * 2 + 1) * "\\" else: # backslashes are not special here cmdline += n_backslashes * "\\" n_backslashes = 0 cmdline += c # Escape all backslashes, but let the terminating # double quotation mark we add below be interpreted # as a metacharacter cmdline += +n_backslashes * 2 * "\\" + '"' return cmdline
Checks if we are on the main thread or not.
def on_main_thread(): """Checks if we are on the main thread or not.""" return threading.current_thread() is threading.main_thread()
Swaps a current variable name in a namespace for another value, and then replaces it when the context is exited.
def swap(namespace, name, value, default=_DEFAULT_SENTINEL): """Swaps a current variable name in a namespace for another value, and then replaces it when the context is exited. """ old = getattr(namespace, name, default) setattr(namespace, name, value) yield value if old is default: delattr(namespace, name) else: setattr(namespace, name, old)
Updates a dictionary (or other mapping) with values from another mapping, and then restores the original mapping when the context is exited.
def swap_values(d, updates, default=_DEFAULT_SENTINEL): """Updates a dictionary (or other mapping) with values from another mapping, and then restores the original mapping when the context is exited. """ old = {k: d.get(k, default) for k in updates} d.update(updates) yield for k, v in old.items(): if v is default and k in d: del d[k] else: d[k] = v
This assumes that the object has a detype method, and calls that.
def detype(x): """This assumes that the object has a detype method, and calls that.""" return x.detype()
Tests if something is an integer
def is_int(x): """Tests if something is an integer""" return isinstance(x, int)
Tests if something is a float
def is_float(x): """Tests if something is a float""" return isinstance(x, float)
Tests if something is a string
def is_string(x): """Tests if something is a string""" return isinstance(x, str)
Tests if something is a slice
def is_slice(x): """Tests if something is a slice""" return isinstance(x, slice)
Tests if something is callable
def is_callable(x): """Tests if something is callable""" return callable(x)
Tests if something is a string or callable
def is_string_or_callable(x): """Tests if something is a string or callable""" return is_string(x) or is_callable(x)
Tests if something is a class
def is_class(x): """Tests if something is a class""" return isinstance(x, type)
Returns True
def always_true(x): """Returns True""" return True
Returns False
def always_false(x): """Returns False""" return False
Returns None
def always_none(x): """Returns None""" return None
Returns a string if x is not a string, and x if it already is. If x is None, the empty string is returned.
def ensure_string(x): """Returns a string if x is not a string, and x if it already is. If x is None, the empty string is returned.""" return str(x) if x is not None else ""
This tests if something is a path.
def is_path(x): """This tests if something is a path.""" return isinstance(x, pathlib.Path)
This tests if something is an environment path, ie a list of strings.
def is_env_path(x): """This tests if something is an environment path, ie a list of strings.""" return isinstance(x, EnvPath)
Converts a string to a path.
def str_to_path(x): """Converts a string to a path.""" if x is None or x == "": return None elif isinstance(x, str): return pathlib.Path(x) elif isinstance(x, pathlib.Path): return x elif isinstance(x, EnvPath) and len(x) == 1: return pathlib.Path(x[0]) if x[0] else None else: raise TypeError( f"Variable should be a pathlib.Path, str or single EnvPath type. {type(x)} given." )
Converts a string to an environment path, ie a list of strings, splitting on the OS separator.
def str_to_env_path(x): """Converts a string to an environment path, ie a list of strings, splitting on the OS separator. """ # splitting will be done implicitly in EnvPath's __init__ return EnvPath(x)
Converts a path to a string.
def path_to_str(x): """Converts a path to a string.""" return str(x) if x is not None else ""
Converts an environment path to a string by joining on the OS separator.
def env_path_to_str(x): """Converts an environment path to a string by joining on the OS separator. """ return os.pathsep.join(x)
Tests if something is a boolean.
def is_bool(x): """Tests if something is a boolean.""" return isinstance(x, bool)
Tests if something is a boolean or None.
def is_bool_or_none(x): """Tests if something is a boolean or None.""" return (x is None) or isinstance(x, bool)
Checks if x is a valid $XONSH_TRACEBACK_LOGFILE option. Returns False if x is not a writable/creatable file or an empty string or None.
def is_logfile_opt(x): """ Checks if x is a valid $XONSH_TRACEBACK_LOGFILE option. Returns False if x is not a writable/creatable file or an empty string or None. """ if x is None: return True if not isinstance(x, str): return False else: return is_writable_file(x) or x == ""
Converts a $XONSH_TRACEBACK_LOGFILE option to either a str containing the filepath if it is a writable file or None if the filepath is not valid, informing the user on stderr about the invalid choice.
def to_logfile_opt(x): """Converts a $XONSH_TRACEBACK_LOGFILE option to either a str containing the filepath if it is a writable file or None if the filepath is not valid, informing the user on stderr about the invalid choice. """ if isinstance(x, os.PathLike): # type: ignore x = str(x) if is_logfile_opt(x): return expand_path(x) if x else x else: # if option is not valid, return a proper # option and inform the user on stderr sys.stderr.write( "xonsh: $XONSH_TRACEBACK_LOGFILE must be a " "filepath pointing to a file that either exists " "and is writable or that can be created.\n" ) return None
Detypes a $XONSH_TRACEBACK_LOGFILE option.
def logfile_opt_to_str(x): """ Detypes a $XONSH_TRACEBACK_LOGFILE option. """ if x is None: # None should not be detyped to 'None', as 'None' constitutes # a perfectly valid filename and retyping it would introduce # ambiguity. Detype to the empty string instead. return "" return str(x)
Converts to a boolean in a semantically meaningful way.
def to_bool(x): """Converts to a boolean in a semantically meaningful way.""" if isinstance(x, bool): return x elif isinstance(x, str): return False if x.lower() in _FALSES else True else: return bool(x)
Converts to a boolean or none in a semantically meaningful way.
def to_bool_or_none(x): """Converts to a boolean or none in a semantically meaningful way.""" if x is None or isinstance(x, bool): return x elif isinstance(x, str): low_x = x.lower() if low_x == "none": return None else: return False if x.lower() in _FALSES else True else: return bool(x)
No conversion, returns itself.
def to_itself(x): """No conversion, returns itself.""" return x
Convert the given value to integer if possible. Otherwise return None
def to_int_or_none(x) -> tp.Optional[int]: """Convert the given value to integer if possible. Otherwise return None""" if isinstance(x, str) and x.lower() == "none": return None else: return int(x)
Converts a bool to an empty string if False and the string '1' if True.
def bool_to_str(x): """Converts a bool to an empty string if False and the string '1' if True. """ return "1" if x else ""
Converts a bool or None value to a string.
def bool_or_none_to_str(x): """Converts a bool or None value to a string.""" if x is None: return "None" else: return "1" if x else ""
Returns whether a value is a boolean or integer.
def is_bool_or_int(x): """Returns whether a value is a boolean or integer.""" return is_bool(x) or is_int(x)
Converts a value to a boolean or an integer.
def to_bool_or_int(x): """Converts a value to a boolean or an integer.""" if isinstance(x, str): return int(x) if x.isdigit() else to_bool(x) elif is_int(x): # bools are ints too! return x else: return bool(x)
Converts a boolean or integer to a string.
def bool_or_int_to_str(x): """Converts a boolean or integer to a string.""" return bool_to_str(x) if is_bool(x) else str(x)
Converts a value to an $SHLVL integer according to bash's behaviour (variables.c::adjust_shell_level).
def to_shlvl(x): """Converts a value to an $SHLVL integer according to bash's behaviour (variables.c::adjust_shell_level).""" if x is None: return 0 else: x = str(x) try: return adjust_shlvl(max(0, int(x)), 0) except ValueError: return 0
Checks whether a variable is a proper $SHLVL integer.
def is_valid_shlvl(x): """Checks whether a variable is a proper $SHLVL integer.""" return isinstance(x, int) and to_shlvl(x) == x
Adjusts an $SHLVL integer according to bash's behaviour (variables.c::adjust_shell_level).
def adjust_shlvl(old_lvl: int, change: int): """Adjusts an $SHLVL integer according to bash's behaviour (variables.c::adjust_shell_level).""" new_level = old_lvl + change if new_level < 0: new_level = 0 elif new_level >= 1000: new_level = 1 return new_level
Try to convert an object into a slice, complain on failure
def ensure_slice(x): """Try to convert an object into a slice, complain on failure""" if not x and x != 0: return slice(None) elif is_slice(x): return x try: x = int(x) if x != -1: s = slice(x, x + 1) else: s = slice(-1, None, None) except ValueError as ex: x = x.strip("[]()") m = SLICE_REG.fullmatch(x) if m: groups = (int(i) if i else None for i in m.groups()) s = slice(*groups) else: raise ValueError(f"cannot convert {x!r} to slice") from ex except TypeError: try: s = slice(*(int(i) for i in x)) except (TypeError, ValueError) as ex: raise ValueError(f"cannot convert {x!r} to slice") from ex return s
Yield from portions of an iterable. Parameters ---------- it : iterable slices : a slice or a list of slice objects
def get_portions(it, slices): """Yield from portions of an iterable. Parameters ---------- it : iterable slices : a slice or a list of slice objects """ if is_slice(slices): slices = [slices] if len(slices) == 1: s = slices[0] try: yield from itertools.islice(it, s.start, s.stop, s.step) return except ValueError: # islice failed pass it = list(it) for s in slices: yield from it[s]
Test if string x is a slice. If not a string return False.
def is_slice_as_str(x): """ Test if string x is a slice. If not a string return False. """ try: x = x.strip("[]()") m = SLICE_REG.fullmatch(x) if m: return True except AttributeError: pass return False
Test if string x is an integer. If not a string return False.
def is_int_as_str(x): """ Test if string x is an integer. If not a string return False. """ try: return x.isdecimal() except AttributeError: return False
Tests if something is a set of strings
def is_string_set(x): """Tests if something is a set of strings""" return isinstance(x, cabc.Set) and all(isinstance(a, str) for a in x)
Convert a comma-separated list of strings to a set of strings.
def csv_to_set(x): """Convert a comma-separated list of strings to a set of strings.""" if not x: return set() else: return set(x.split(","))
Convert a set of strings to a comma-separated list of strings.
def set_to_csv(x): """Convert a set of strings to a comma-separated list of strings.""" return ",".join(x)
Converts a os.pathsep separated string to a set of strings.
def pathsep_to_set(x): """Converts a os.pathsep separated string to a set of strings.""" if not x: return set() else: return set(x.split(os.pathsep))
Converts a set to an os.pathsep separated string. The sort kwarg specifies whether to sort the set prior to str conversion.
def set_to_pathsep(x, sort=False): """Converts a set to an os.pathsep separated string. The sort kwarg specifies whether to sort the set prior to str conversion. """ if sort: x = sorted(x) return os.pathsep.join(x)
Tests if something is a sequence of strings
def is_string_seq(x): """Tests if something is a sequence of strings""" return isinstance(x, cabc.Sequence) and all(isinstance(a, str) for a in x)
Tests if something is a sequence of strings, where the top-level sequence is not a string itself.
def is_nonstring_seq_of_strings(x): """Tests if something is a sequence of strings, where the top-level sequence is not a string itself. """ return ( isinstance(x, cabc.Sequence) and not isinstance(x, str) and all(isinstance(a, str) for a in x) )
Converts a os.pathsep separated string to a sequence of strings.
def pathsep_to_seq(x): """Converts a os.pathsep separated string to a sequence of strings.""" if not x: return [] else: return x.split(os.pathsep)
Converts a sequence to an os.pathsep separated string.
def seq_to_pathsep(x): """Converts a sequence to an os.pathsep separated string.""" return os.pathsep.join(x)
Converts a os.pathsep separated string to a sequence of uppercase strings.
def pathsep_to_upper_seq(x): """Converts a os.pathsep separated string to a sequence of uppercase strings. """ if not x: return [] else: return x.upper().split(os.pathsep)
Converts a sequence to an uppercase os.pathsep separated string.
def seq_to_upper_pathsep(x): """Converts a sequence to an uppercase os.pathsep separated string.""" return os.pathsep.join(x).upper()
Tests if an object is a sequence of bools.
def is_bool_seq(x): """Tests if an object is a sequence of bools.""" return isinstance(x, cabc.Sequence) and all(isinstance(y, bool) for y in x)
Takes a comma-separated string and converts it into a list of bools.
def csv_to_bool_seq(x): """Takes a comma-separated string and converts it into a list of bools.""" return [to_bool(y) for y in csv_to_set(x)]
Converts a sequence of bools to a comma-separated string.
def bool_seq_to_csv(x): """Converts a sequence of bools to a comma-separated string.""" return ",".join(map(str, x))
Setter function for $PROMPT_TOOLKIT_COLOR_DEPTH. Also updates os.environ so prompt toolkit can pickup the value.
def ptk2_color_depth_setter(x): """Setter function for $PROMPT_TOOLKIT_COLOR_DEPTH. Also updates os.environ so prompt toolkit can pickup the value. """ x = str(x) if x in { "DEPTH_1_BIT", "MONOCHROME", "DEPTH_4_BIT", "ANSI_COLORS_ONLY", "DEPTH_8_BIT", "DEFAULT", "DEPTH_24_BIT", "TRUE_COLOR", }: pass elif x in {"", None}: x = "" else: msg = f'"{x}" is not a valid value for $PROMPT_TOOLKIT_COLOR_DEPTH. ' warnings.warn(msg, RuntimeWarning, stacklevel=2) x = "" if x == "" and "PROMPT_TOOLKIT_COLOR_DEPTH" in os_environ: del os_environ["PROMPT_TOOLKIT_COLOR_DEPTH"] else: os_environ["PROMPT_TOOLKIT_COLOR_DEPTH"] = x return x
Enumerated values of ``$COMPLETIONS_DISPLAY``
def is_completions_display_value(x): """Enumerated values of ``$COMPLETIONS_DISPLAY``""" return x in {"none", "single", "multi"}
Convert user input to value of ``$COMPLETIONS_DISPLAY``
def to_completions_display_value(x): """Convert user input to value of ``$COMPLETIONS_DISPLAY``""" x = str(x).lower() if x in {"none", "false"}: x = "none" elif x in {"multi", "true"}: x = "multi" elif x in {"single", "readline"}: pass else: msg = f'"{x}" is not a valid value for $COMPLETIONS_DISPLAY. ' msg += 'Using "multi".' warnings.warn(msg, RuntimeWarning, stacklevel=2) x = "multi" return x
Enumerated values of $COMPLETION_MODE
def is_completion_mode(x): """Enumerated values of $COMPLETION_MODE""" return x in CANONIC_COMPLETION_MODES
Convert user input to value of $COMPLETION_MODE
def to_completion_mode(x): """Convert user input to value of $COMPLETION_MODE""" y = str(x).casefold().replace("_", "-") y = ( "default" if y in ("", "d", "xonsh", "none", "def") else "menu-complete" if y in ("m", "menu", "menu-completion") else y ) if y not in CANONIC_COMPLETION_MODES: warnings.warn( f"'{x}' is not valid for $COMPLETION_MODE, must be one of {CANONIC_COMPLETION_MODES}. Using 'default'.", RuntimeWarning, stacklevel=2, ) y = "default" return y
Converts a string to a dictionary
def to_dict(x): """Converts a string to a dictionary""" if isinstance(x, dict): return x try: x = ast.literal_eval(x) except (ValueError, SyntaxError): msg = f'"{x}" can not be converted to Python dictionary.' warnings.warn(msg, RuntimeWarning, stacklevel=2) x = dict() return x
Converts a string to Token:str dictionary
def to_tok_color_dict(x): """Converts a string to Token:str dictionary""" if is_tok_color_dict(x): return x x = to_dict(x) if not is_tok_color_dict(x): msg = f'"{x}" can not be converted to Token:str dictionary.' warnings.warn(msg, RuntimeWarning, stacklevel=2) x = dict() return x
Converts a dictionary to a string
def dict_to_str(x): """Converts a dictionary to a string""" if not x or len(x) == 0: return "" return str(x)
Tests if something is a proper history value, units tuple.
def is_history_tuple(x): """Tests if something is a proper history value, units tuple.""" if ( isinstance(x, cabc.Sequence) and len(x) == 2 and isinstance(x[0], (int, float)) and x[1].lower() in CANON_HISTORY_UNITS ): return True return False
Tests if something is a valid regular expression.
def is_regex(x): """Tests if something is a valid regular expression.""" try: re.compile(x) return True except re.error: pass return False
Tests if something is a valid history backend.
def is_history_backend(x): """Tests if something is a valid history backend.""" return is_string(x) or is_class(x) or isinstance(x, object)
Determine if the input is a valid input for the DYNAMIC_CWD_WIDTH environment variable.
def is_dynamic_cwd_width(x): """Determine if the input is a valid input for the DYNAMIC_CWD_WIDTH environment variable. """ return ( isinstance(x, tuple) and len(x) == 2 and isinstance(x[0], float) and x[1] in set("c%") )
Convert to a canonical cwd_width tuple.
def to_dynamic_cwd_tuple(x): """Convert to a canonical cwd_width tuple.""" unit = "c" if isinstance(x, str): if x[-1] == "%": x = x[:-1] unit = "%" else: unit = "c" return (float(x), unit) else: return (float(x[0]), x[1])
Convert a canonical cwd_width tuple to a string.
def dynamic_cwd_tuple_to_str(x): """Convert a canonical cwd_width tuple to a string.""" if x[1] == "%": return str(x[0]) + "%" else: return str(x[0])
Converts to a canonical history tuple.
def to_history_tuple(x): """Converts to a canonical history tuple.""" if not isinstance(x, (cabc.Sequence, float, int)): raise ValueError("history size must be given as a sequence or number") if isinstance(x, str): m = RE_HISTORY_TUPLE.match(x.strip().lower()) return to_history_tuple((m.group(1), m.group(3))) elif isinstance(x, (float, int)): return to_history_tuple((x, "commands")) units, converter = HISTORY_UNITS[x[1]] value = converter(x[0]) return (value, units)
Converts a valid history tuple to a canonical string.
def history_tuple_to_str(x): """Converts a valid history tuple to a canonical string.""" return "{} {}".format(*x)
Yeilds all permutations, not just those of a specified length
def all_permutations(iterable): """Yeilds all permutations, not just those of a specified length""" for r in range(1, len(iterable) + 1): yield from itertools.permutations(iterable, r=r)
Formats strings that may contain colors. This simply dispatches to the shell instances method of the same name. The results of this function should be directly usable by print_color().
def format_color(string, **kwargs): """Formats strings that may contain colors. This simply dispatches to the shell instances method of the same name. The results of this function should be directly usable by print_color(). """ if hasattr(xsh.shell, "shell"): return xsh.shell.shell.format_color(string, **kwargs) else: # fallback for ANSI if shell is not yet initialized from xonsh.ansi_colors import ansi_partial_color_format style = xsh.env.get("XONSH_COLOR_STYLE") return ansi_partial_color_format(string, style=style)
Prints a string that may contain colors. This dispatched to the shell method of the same name. Colors will be formatted if they have not already been.
def print_color(string, **kwargs): """Prints a string that may contain colors. This dispatched to the shell method of the same name. Colors will be formatted if they have not already been. """ if hasattr(xsh.shell, "shell"): xsh.shell.shell.print_color(string, **kwargs) else: # fallback for ANSI if shell is not yet initialized print(format_color(string, **kwargs))
Returns an iterable of all available style names.
def color_style_names(): """Returns an iterable of all available style names.""" return xsh.shell.shell.color_style_names()
Returns the current color map.
def color_style(): """Returns the current color map.""" return xsh.shell.shell.color_style()
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 style object created, None if not succeeded
def register_custom_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. background_color : str Background color. base : str, optional Base style to use as default. Returns ------- style : The style object created, None if not succeeded """ style = None if pygments_version_info(): from xonsh.pyghooks import register_custom_pygments_style style = register_custom_pygments_style( name, styles, highlight_color, background_color, base ) # register ANSI colors from xonsh.ansi_colors import register_custom_ansi_style register_custom_ansi_style(name, styles, base) return style
yields tokens attr, and index from a stylemap
def _token_attr_from_stylemap(stylemap): """yields tokens attr, and index from a stylemap""" import prompt_toolkit as ptk if xsh.shell.shell_type == "prompt_toolkit1": style = ptk.styles.style_from_dict(stylemap) for token in stylemap: yield token, style.token_to_attrs[token] else: style = ptk.styles.style_from_pygments_dict(stylemap) for token in stylemap: style_str = ( f"class:{ptk.styles.pygments.pygments_token_to_classname(token)}" ) yield (token, style.get_attrs_for_style_str(style_str))
Returns the prompt_toolkit win32 ColorLookupTable
def _get_color_lookup_table(): """Returns the prompt_toolkit win32 ColorLookupTable""" if xsh.shell.shell_type == "prompt_toolkit1": from prompt_toolkit.terminal.win32_output import ColorLookupTable else: from prompt_toolkit.output.win32 import ColorLookupTable return ColorLookupTable()
Generates the color and windows color index for a style
def _get_color_indexes(style_map): """Generates the color and windows color index for a style""" table = _get_color_lookup_table() for token, attr in _token_attr_from_stylemap(style_map): if attr.color: index = table.lookup_fg_color(attr.color) try: rgb = ( int(attr.color[0:2], 16), int(attr.color[2:4], 16), int(attr.color[4:6], 16), ) except Exception: rgb = None yield token, index, rgb
Map dark ansi colors to lighter version.
def _win_bold_color_map(): """Map dark ansi colors to lighter version.""" return { "ansiblack": "ansibrightblack", "ansiblue": "ansibrightblue", "ansigreen": "ansibrightgreen", "ansicyan": "ansibrightcyan", "ansired": "ansibrightred", "ansimagenta": "ansibrightmagenta", "ansiyellow": "ansibrightyellow", "ansigray": "ansiwhite", }
Replace all ansi colors with hardcoded colors to avoid unreadable defaults in conhost.exe
def hardcode_colors_for_win10(style_map): """Replace all ansi colors with hardcoded colors to avoid unreadable defaults in conhost.exe """ modified_style = {} if not xsh.env["PROMPT_TOOLKIT_COLOR_DEPTH"]: xsh.env["PROMPT_TOOLKIT_COLOR_DEPTH"] = "DEPTH_24_BIT" # Replace all ansi colors with hardcoded colors to avoid unreadable defaults # in conhost.exe for token, style_str in style_map.items(): for ansicolor in WIN10_COLOR_MAP: if ansicolor in style_str: if "bold" in style_str and "nobold" not in style_str: # Win10 doesn't yet handle bold colors. Instead dark # colors are mapped to their lighter version. We simulate # the same here. style_str.replace("bold", "") hexcolor = WIN10_COLOR_MAP[ WIN_BOLD_COLOR_MAP.get(ansicolor, ansicolor) ] else: hexcolor = WIN10_COLOR_MAP[ansicolor] style_str = style_str.replace(ansicolor, hexcolor) modified_style[token] = style_str return modified_style
Converts ansicolor names in a stylemap to old PTK1 color names
def ansicolors_to_ptk1_names(stylemap): """Converts ansicolor names in a stylemap to old PTK1 color names""" if pygments_version_info() and pygments_version_info() >= (2, 4, 0): return stylemap modified_stylemap = {} for token, style_str in stylemap.items(): for color, ptk1_color in ANSICOLOR_NAMES_MAP.items(): if "#" + color not in style_str: style_str = style_str.replace(color, ptk1_color) modified_stylemap[token] = style_str return modified_stylemap
Returns a modified style to where colors that maps to dark colors are replaced with brighter versions.
def intensify_colors_for_cmd_exe(style_map): """Returns a modified style to where colors that maps to dark colors are replaced with brighter versions. """ modified_style = {} replace_colors = { 1: "ansibrightcyan", # subst blue with bright cyan 2: "ansibrightgreen", # subst green with bright green 4: "ansibrightred", # subst red with bright red 5: "ansibrightmagenta", # subst magenta with bright magenta 6: "ansibrightyellow", # subst yellow with bright yellow 9: "ansicyan", # subst intense blue with dark cyan (more readable) } if xsh.shell.shell_type == "prompt_toolkit1": replace_colors = ansicolors_to_ptk1_names(replace_colors) for token, idx, _ in _get_color_indexes(style_map): if idx in replace_colors: modified_style[token] = replace_colors[idx] return modified_style
Resets the style when setting the INTENSIFY_COLORS_ON_WIN environment variable.
def intensify_colors_on_win_setter(enable): """Resets the style when setting the INTENSIFY_COLORS_ON_WIN environment variable. """ enable = to_bool(enable) if xsh.shell is not None and hasattr(xsh.shell.shell.styler, "style_name"): delattr(xsh.shell.shell.styler, "style_name") return enable
Formats a template prefix/postfix string for a standard buffer. Returns a string suitable for prepending or appending.
def format_std_prepost(template, env=None): """Formats a template prefix/postfix string for a standard buffer. Returns a string suitable for prepending or appending. """ if not template: return "" env = xsh.env if env is None else env invis = "\001\002" if xsh.shell is None: # shell hasn't fully started up (probably still in xonshrc) from xonsh.ansi_colors import ansi_partial_color_format from xonsh.prompt.base import PromptFormatter pf = PromptFormatter() s = pf(template) style = env.get("XONSH_COLOR_STYLE") s = ansi_partial_color_format(invis + s + invis, hide=False, style=style) else: # shell has fully started. do the normal thing shell = xsh.shell.shell try: s = shell.prompt_formatter(template) except Exception: print_exception() # \001\002 is there to fool pygments into not returning an empty string # for potentially empty input. This happens when the template is just a # color code with no visible text. s = shell.format_color(invis + s + invis, force_string=True) s = s.replace(invis, "") return s
Gets rid of single quotes, double quotes, single triple quotes, and single double quotes from a string, if present front and back of a string. Otherwiswe, does nothing.
def strip_simple_quotes(s): """Gets rid of single quotes, double quotes, single triple quotes, and single double quotes from a string, if present front and back of a string. Otherwiswe, does nothing. """ starts_single = s.startswith("'") starts_double = s.startswith('"') if not starts_single and not starts_double: return s elif starts_single: ends_single = s.endswith("'") if not ends_single: return s elif s.startswith("'''") and s.endswith("'''") and len(s) >= 6: return s[3:-3] elif len(s) >= 2: return s[1:-1] else: return s else: # starts double ends_double = s.endswith('"') if not ends_double: return s elif s.startswith('"""') and s.endswith('"""') and len(s) >= 6: return s[3:-3] elif len(s) >= 2: return s[1:-1] else: return s
Returns the starting index (inclusive), ending index (exclusive), and starting quote string of the most recent Python string found in the input. check_for_partial_string(x) -> (startix, endix, quote) Parameters ---------- x : str The string to be checked (representing a line of terminal input) Returns ------- startix : int (or None) The index where the most recent Python string found started (inclusive), or None if no strings exist in the input endix : int (or None) The index where the most recent Python string found ended (exclusive), or None if no strings exist in the input OR if the input ended in the middle of a Python string quote : str (or None) A string containing the quote used to start the string (e.g., b", ", '''), or None if no string was found.
def check_for_partial_string(x): """Returns the starting index (inclusive), ending index (exclusive), and starting quote string of the most recent Python string found in the input. check_for_partial_string(x) -> (startix, endix, quote) Parameters ---------- x : str The string to be checked (representing a line of terminal input) Returns ------- startix : int (or None) The index where the most recent Python string found started (inclusive), or None if no strings exist in the input endix : int (or None) The index where the most recent Python string found ended (exclusive), or None if no strings exist in the input OR if the input ended in the middle of a Python string quote : str (or None) A string containing the quote used to start the string (e.g., b", ", '''), or None if no string was found. """ string_indices = [] starting_quote = [] current_index = 0 match = re.search(RE_BEGIN_STRING, x) while match is not None: # add the start in start = match.start() quote = match.group(0) lenquote = len(quote) current_index += start # store the starting index of the string, as well as the # characters in the starting quotes (e.g., ", ', """, r", etc) string_indices.append(current_index) starting_quote.append(quote) # determine the string that should terminate this string ender = re.sub(RE_STRING_START, "", quote) x = x[start + lenquote :] current_index += lenquote # figure out what is inside the string continuer = RE_STRING_CONT[ender] contents = re.match(continuer, x) inside = contents.group(0) leninside = len(inside) current_index += contents.start() + leninside + len(ender) # if we are not at the end of the input string, add the ending index of # the string to string_indices if contents.end() < len(x): string_indices.append(current_index) x = x[leninside + len(ender) :] # find the next match match = re.search(RE_BEGIN_STRING, x) numquotes = len(string_indices) if numquotes == 0: return (None, None, None) elif numquotes % 2: return (string_indices[-1], None, starting_quote[-1]) else: return (string_indices[-2], string_indices[-1], starting_quote[-1])