response stringlengths 1 33.1k | instruction stringlengths 22 582k |
|---|---|
Returns the current color map. | def ansi_color_style(style="default"):
"""Returns the current color map."""
if style in ANSI_STYLES:
cmap = ANSI_STYLES[style]
else:
msg = f"Could not find color style {style!r}, using default."
warnings.warn(msg, RuntimeWarning, stacklevel=2)
cmap = ANSI_STYLES["default"]
... |
Reverses an ANSI color style mapping so that escape codes map to
colors. Style may either be string or mapping. May also return
the style it looked up. | def ansi_reverse_style(style="default", return_style=False):
"""Reverses an ANSI color style mapping so that escape codes map to
colors. Style may either be string or mapping. May also return
the style it looked up.
"""
style = ansi_style_by_name(style) if isinstance(style, str) else style
rever... |
Converts an ANSI color code escape sequence to a tuple of color names
in the provided style ('default' should almost be the style). For example,
'0' becomes ('RESET',) and '32;41' becomes ('GREEN', 'BACKGROUND_RED').
The style keyword may either be a string, in which the style is looked up,
or an actual style dict. Yo... | def ansi_color_escape_code_to_name(escape_code, style, reversed_style=None):
"""Converts an ANSI color code escape sequence to a tuple of color names
in the provided style ('default' should almost be the style). For example,
'0' becomes ('RESET',) and '32;41' becomes ('GREEN', 'BACKGROUND_RED').
The sty... |
Makes an ANSI color style from a color palette | def make_ansi_style(palette):
"""Makes an ANSI color style from a color palette"""
style = {"RESET": "0"}
for name, t in BASE_XONSH_COLORS.items():
closest = find_closest_color(t, palette)
if len(closest) == 3:
closest = "".join([a * 2 for a in closest])
short = rgb2shor... |
Tries to convert the given pygments style to ANSI style.
Parameters
----------
style : pygments style value
Returns
-------
ANSI style | def _pygments_to_ansi_style(style):
"""Tries to convert the given pygments style to ANSI style.
Parameters
----------
style : pygments style value
Returns
-------
ANSI style
"""
ansi_style_list = []
parts = style.split(" ")
for part in parts:
if part in _PART_STYLE... |
Converts pygments like style dict to ANSI rules | def _style_dict_to_ansi(styles):
"""Converts pygments like style dict to ANSI rules"""
ansi_style = {}
for token, style in styles.items():
token = str(token) # convert pygments token to str
parts = token.split(".")
if len(parts) == 1 or parts[-2] == "Color":
ansi_style[... |
Register custom ANSI style.
Parameters
----------
name : str
Style name.
styles : dict
Token (or str) -> style mapping.
base : str, optional
Base style to use as default. | def register_custom_ansi_style(name, styles, base="default"):
"""Register custom ANSI style.
Parameters
----------
name : str
Style name.
styles : dict
Token (or str) -> style mapping.
base : str, optional
Base style to use as default.
"""
base_style = ANSI_STYLE... |
Gets or makes an ANSI color style by name. If the styles does not
exist, it will look for a style using the pygments name. | def ansi_style_by_name(name):
"""Gets or makes an ANSI color style by name. If the styles does not
exist, it will look for a style using the pygments name.
"""
if name in ANSI_STYLES:
return ANSI_STYLES[name]
elif not HAS_PYGMENTS:
print(f"could not find style {name!r}, using 'defaul... |
Attempts to find the first name in the tree. | def leftmostname(node):
"""Attempts to find the first name in the tree."""
if isinstance(node, Name):
rtn = node.id
elif isinstance(node, (BinOp, Compare)):
rtn = leftmostname(node.left)
elif isinstance(node, (Attribute, Subscript, Starred, Expr)):
rtn = leftmostname(node.valu... |
Gets the lineno of a node or returns the default. | def get_lineno(node, default=0):
"""Gets the lineno of a node or returns the default."""
return getattr(node, "lineno", default) |
Computes the minimum lineno. | def min_line(node):
"""Computes the minimum lineno."""
node_line = get_lineno(node)
return min(map(get_lineno, walk(node), itertools.repeat(node_line))) |
Computes the maximum lineno. | def max_line(node):
"""Computes the maximum lineno."""
return max(map(get_lineno, walk(node))) |
Gets the col_offset of a node, or returns the default | def get_col(node, default=-1):
"""Gets the col_offset of a node, or returns the default"""
return getattr(node, "col_offset", default) |
Computes the minimum col_offset. | def min_col(node):
"""Computes the minimum col_offset."""
return min(map(get_col, walk(node), itertools.repeat(node.col_offset))) |
Returns the maximum col_offset of the node and all sub-nodes. | def max_col(node):
"""Returns the maximum col_offset of the node and all sub-nodes."""
col = getattr(node, "max_col", None)
if col is not None:
return col
highest = max(walk(node), key=get_col)
col = highest.col_offset + node_len(highest)
return col |
The length of a node as a string | def node_len(node):
"""The length of a node as a string"""
val = 0
for n in walk(node):
if isinstance(n, Name):
val += len(n.id)
elif isinstance(n, Attribute):
val += 1 + (len(n.attr) if isinstance(n.attr, str) else 0)
# this may need to be added to for mor... |
Gets the id attribute of a node, or returns a default. | def get_id(node, default=None):
"""Gets the id attribute of a node, or returns a default."""
return getattr(node, "id", default) |
Returns the set of all names present in the node's tree. | def gather_names(node):
"""Returns the set of all names present in the node's tree."""
rtn = set(map(get_id, walk(node)))
rtn.discard(None)
return rtn |
Gets the id and attribute of a node, or returns a default. | def get_id_ctx(node):
"""Gets the id and attribute of a node, or returns a default."""
nid = getattr(node, "id", None)
if nid is None:
return (None, None)
return (nid, node.ctx) |
Returns the names present in the node's tree in a set of load nodes and
a set of store nodes. | def gather_load_store_names(node):
"""Returns the names present in the node's tree in a set of load nodes and
a set of store nodes.
"""
load = set()
store = set()
for nid, ctx in map(get_id_ctx, walk(node)):
if nid is None:
continue
elif isinstance(ctx, Load):
... |
Tests if x is an AST node with elements. | def has_elts(x):
"""Tests if x is an AST node with elements."""
return isinstance(x, AST) and hasattr(x, "elts") |
Creates an AST that loads variable name that may (or may not)
have attribute chains. For example, "a.b.c" | def load_attribute_chain(name, lineno=None, col=None):
"""Creates an AST that loads variable name that may (or may not)
have attribute chains. For example, "a.b.c"
"""
names = name.split(".")
node = Name(id=names.pop(0), ctx=Load(), lineno=lineno, col_offset=col)
for attr in names:
node ... |
Creates the AST node for calling a function of a given name.
Functions names may contain attribute access, e.g. __xonsh__.env. | def xonsh_call(name, args, lineno=None, col=None):
"""Creates the AST node for calling a function of a given name.
Functions names may contain attribute access, e.g. __xonsh__.env.
"""
return Call(
func=load_attribute_chain(name, lineno=lineno, col=col),
args=args,
keywords=[],
... |
Determines whether or not a node is worth visiting. Currently only
UnaryOp and BoolOp nodes are visited. | def isdescendable(node):
"""Determines whether or not a node is worth visiting. Currently only
UnaryOp and BoolOp nodes are visited.
"""
return isinstance(node, (UnaryOp, BoolOp)) |
Determines whether a node (or code string) is an expression, and
does not contain any statements. The execution context (ctx) and
other args and kwargs are passed down to the parser, as needed. | def isexpression(node, ctx=None, *args, **kwargs):
"""Determines whether a node (or code string) is an expression, and
does not contain any statements. The execution context (ctx) and
other args and kwargs are passed down to the parser, as needed.
"""
# parse string to AST
if isinstance(node, st... |
performs a pretty dump of an AST node. | def pdump(s, **kwargs):
"""performs a pretty dump of an AST node."""
if isinstance(s, AST):
s = dump(s, **kwargs).replace(",", ",\n")
openers = "([{"
closers = ")]}"
lens = len(s) + 1
if lens == 1:
return s
i = min(s.find(o) % lens for o in openers)
if i == lens - 1:
... |
Performs a pretty print of the AST nodes. | def pprint_ast(s, *, sep=None, end=None, file=None, flush=False, **kwargs):
"""Performs a pretty print of the AST nodes."""
print(pdump(s, **kwargs), sep=sep, end=end, file=file, flush=flush) |
calls getattr(name, '__xonsh_block__', False). | def _getblockattr(name, lineno, col):
"""calls getattr(name, '__xonsh_block__', False)."""
return xonsh_call(
"getattr",
args=[
Name(id=name, ctx=Load(), lineno=lineno, col_offset=col),
const_str(s="__xonsh_block__", lineno=lineno, col_offset=col),
const_name(... |
Sets a new signal handle that will automatically restore the old value
once the new handle is finished. | def resetting_signal_handle(sig, f):
"""Sets a new signal handle that will automatically restore the old value
once the new handle is finished.
"""
oldh = signal.getsignal(sig)
def newh(s=None, frame=None):
f(s, frame)
signal.signal(sig, oldh)
if sig != 0:
sys.ex... |
Prints help about, and then returns that variable. | def helper(x, name=""):
"""Prints help about, and then returns that variable."""
name = name or getattr(x, "__name__", "")
INSPECTOR.pinfo(x, oname=name, detail_level=0)
return x |
Prints help about, and then returns that variable. | def superhelper(x, name=""):
"""Prints help about, and then returns that variable."""
name = name or getattr(x, "__name__", "")
INSPECTOR.pinfo(x, oname=name, detail_level=1)
return x |
Regular expression-based globbing. | def reglob(path, parts=None, i=None):
"""Regular expression-based globbing."""
if parts is None:
path = os.path.normpath(path)
drive, tail = os.path.splitdrive(path)
parts = tail.split(os.sep)
d = os.sep if os.path.isabs(path) else "."
d = os.path.join(drive, d)
r... |
Takes a string and returns a list of file paths that match (regex, glob,
or arbitrary search function). If pathobj=True, the return is a list of
pathlib.Path objects instead of strings. | def pathsearch(func, s, pymode=False, pathobj=False):
"""
Takes a string and returns a list of file paths that match (regex, glob,
or arbitrary search function). If pathobj=True, the return is a list of
pathlib.Path objects instead of strings.
"""
if not callable(func) or len(inspect.signature(f... |
Runs a subprocess, capturing the output. Returns the stdout
that was produced as a str. | def subproc_captured_stdout(*cmds, envs=None):
"""Runs a subprocess, capturing the output. Returns the stdout
that was produced as a str.
"""
import xonsh.procs.specs
return xonsh.procs.specs.run_subproc(cmds, captured="stdout", envs=envs) |
Runs a subprocess, capturing the output. Returns a list of
whitespace-separated strings of the stdout that was produced.
The string is split using xonsh's lexer, rather than Python's str.split()
or shlex.split(). | def subproc_captured_inject(*cmds, envs=None):
"""Runs a subprocess, capturing the output. Returns a list of
whitespace-separated strings of the stdout that was produced.
The string is split using xonsh's lexer, rather than Python's str.split()
or shlex.split().
"""
import xonsh.procs.specs
... |
Runs a subprocess, capturing the output. Returns an instance of
CommandPipeline representing the completed command. | def subproc_captured_object(*cmds, envs=None):
"""
Runs a subprocess, capturing the output. Returns an instance of
CommandPipeline representing the completed command.
"""
import xonsh.procs.specs
return xonsh.procs.specs.run_subproc(cmds, captured="object", envs=envs) |
Runs a subprocess, capturing the output. Returns an instance of
HiddenCommandPipeline representing the completed command. | def subproc_captured_hiddenobject(*cmds, envs=None):
"""Runs a subprocess, capturing the output. Returns an instance of
HiddenCommandPipeline representing the completed command.
"""
import xonsh.procs.specs
return xonsh.procs.specs.run_subproc(cmds, captured="hiddenobject", envs=envs) |
Runs a subprocess, without capturing the output. Returns the stdout
that was produced as a str. | def subproc_uncaptured(*cmds, envs=None):
"""Runs a subprocess, without capturing the output. Returns the stdout
that was produced as a str.
"""
import xonsh.procs.specs
return xonsh.procs.specs.run_subproc(cmds, captured=False, envs=envs) |
Ensures that x is a list of strings. | def ensure_list_of_strs(x):
"""Ensures that x is a list of strings."""
if isinstance(x, str):
rtn = [x]
elif isinstance(x, cabc.Sequence):
rtn = [i if isinstance(i, str) else str(i) for i in x]
else:
rtn = [str(x)]
return rtn |
Ensures that x is single string or function. | def ensure_str_or_callable(x):
"""Ensures that x is single string or function."""
if isinstance(x, str) or callable(x):
return x
if isinstance(x, bytes):
# ``os.fsdecode`` decodes using "surrogateescape" on linux and "strict" on windows.
# This is used to decode bytes for interfacing... |
Ensures that x is a list of strings or functions.
This is called when using the ``@()`` operator to expand it's content. | def list_of_strs_or_callables(x):
"""
Ensures that x is a list of strings or functions.
This is called when using the ``@()`` operator to expand it's content.
"""
if isinstance(x, (str, bytes)) or callable(x):
rtn = [ensure_str_or_callable(x)]
elif isinstance(x, cabc.Iterable):
... |
Takes an outer product of a list of strings | def list_of_list_of_strs_outer_product(x):
"""Takes an outer product of a list of strings"""
lolos = map(ensure_list_of_strs, x)
rtn = []
for los in itertools.product(*lolos):
s = "".join(los)
if "*" in s:
rtn.extend(XSH.glob(s))
else:
rtn.append(XSH.ex... |
Evaluates the argument in Xonsh context. | def eval_fstring_field(field):
"""Evaluates the argument in Xonsh context."""
res = XSH.execer.eval(
field[0].strip(), glbs=globals(), locs=XSH.ctx, filename=field[1]
)
return res |
Puts a kind flag (string) a canonical form. | def _convert_kind_flag(x):
"""Puts a kind flag (string) a canonical form."""
x = x.lower()
kind = MACRO_FLAG_KINDS.get(x, None)
if kind is None:
raise TypeError(f"{x!r} not a recognized macro type.")
return kind |
Converts a string macro argument based on the requested kind.
Parameters
----------
raw_arg : str
The str representation of the macro argument.
kind : object
A flag or type representing how to convert the argument.
glbs : Mapping
The globals from the call site.
locs : Mapping or None
The locals from th... | def convert_macro_arg(raw_arg, kind, glbs, locs, *, name="<arg>", macroname="<macro>"):
"""Converts a string macro argument based on the requested kind.
Parameters
----------
raw_arg : str
The str representation of the macro argument.
kind : object
A flag or type representing how to... |
Attaches macro globals and locals temporarily to function as a
context manager.
Parameters
----------
f : callable object
The function that is called as ``f(*args)``.
glbs : Mapping
The globals from the call site.
locs : Mapping or None
The locals from the call site. | def in_macro_call(f, glbs, locs):
"""Attaches macro globals and locals temporarily to function as a
context manager.
Parameters
----------
f : callable object
The function that is called as ``f(*args)``.
glbs : Mapping
The globals from the call site.
locs : Mapping or None
... |
Calls a function as a macro, returning its result.
Parameters
----------
f : callable object
The function that is called as ``f(*args)``.
raw_args : tuple of str
The str representation of arguments of that were passed into the
macro. These strings will be parsed, compiled, evaled, or left as
a string d... | def call_macro(f, raw_args, glbs, locs):
"""Calls a function as a macro, returning its result.
Parameters
----------
f : callable object
The function that is called as ``f(*args)``.
raw_args : tuple of str
The str representation of arguments of that were passed into the
macr... |
Tests if a string starts as a non-kwarg string would. | def _starts_as_arg(s):
"""Tests if a string starts as a non-kwarg string would."""
return KWARG_RE.match(s) is None |
Prepares to enter a context manager macro by attaching the contents
of the macro block, globals, and locals to the object. These modifications
are made in-place and the original object is returned.
Parameters
----------
obj : context manager
The object that is about to be entered via a with-statement.
raw_block : ... | def enter_macro(obj, raw_block, glbs, locs):
"""Prepares to enter a context manager macro by attaching the contents
of the macro block, globals, and locals to the object. These modifications
are made in-place and the original object is returned.
Parameters
----------
obj : context manager
... |
A context manager for using the xonsh builtins only in a limited
scope. Likely useful in testing. | def xonsh_builtins(execer=None):
"""A context manager for using the xonsh builtins only in a limited
scope. Likely useful in testing.
"""
XSH.load(execer=execer)
yield
XSH.unload() |
Using the function's annotation add arguments to the parser
basically converts ``def fn(param : Arg(*args, **kw), ...): ...``
-> into equivalent ``parser.add_argument(*args, *kw)`` call. | def add_args(
parser: ap.ArgumentParser,
func: tp.Callable,
allowed_params=None,
doc=None,
) -> None:
"""Using the function's annotation add arguments to the parser
basically converts ``def fn(param : Arg(*args, **kw), ...): ...``
-> into equivalent ``parser.add_argument(*args, *kw)`` c... |
A bare-bones argparse builder from functions | def make_parser(
func: tp.Union[tp.Callable, str],
empty_help=False,
**kwargs,
) -> "ArgParser":
"""A bare-bones argparse builder from functions"""
doc = NumpyDoc(func)
if "description" not in kwargs:
kwargs["description"] = doc.description
if "epilog" not in kwargs:
if do... |
Final dispatch to the function based on signature. | def _dispatch_func(func: tp.Callable, ns: dict[str, tp.Any]):
"""Final dispatch to the function based on signature."""
sign = inspect.signature(func)
kwargs = {}
for name, param in sign.parameters.items():
default = None
# sometimes the args are skipped in the parser.
# like ones... |
Call the underlying function with arguments parsed from sys.argv
Parameters
----------
parser
root parser
args
sys.argv as parsed by Alias
lenient
if True, then use parser_know_args and pass the extra arguments as `_unparsed`
ns
a dict that will be passed to underlying function | def dispatch(parser: ap.ArgumentParser, args=None, lenient=False, **ns):
"""Call the underlying function with arguments parsed from sys.argv
Parameters
----------
parser
root parser
args
sys.argv as parsed by Alias
lenient
if True, then use parser_know_args and pass the ... |
Return ``True`` if caching has been enabled for this mode (through command
line flags or environment variables) | def should_use_cache(execer, mode):
"""
Return ``True`` if caching has been enabled for this mode (through command
line flags or environment variables)
"""
if mode == "exec":
return (execer.scriptcache or execer.cacheall) and (
XSH.env["XONSH_CACHE_SCRIPTS"] or XSH.env["XONSH_CAC... |
Helper to run code in a given mode and context.
Returns a sys.exc_info() triplet in case the code raises an exception, or (None, None, None) otherwise. | def run_compiled_code(code, glb, loc, mode):
"""
Helper to run code in a given mode and context.
Returns a sys.exc_info() triplet in case the code raises an exception, or (None, None, None) otherwise.
"""
if code is None:
return
if mode in {"exec", "single"}:
func = exec
els... |
Return the filename of the cache for the given filename.
Cache filenames are similar to those used by the Mercurial DVCS for its
internal store.
The ``code`` switch should be true if we should use the code store rather
than the script store. | def get_cache_filename(fname, code=True):
"""
Return the filename of the cache for the given filename.
Cache filenames are similar to those used by the Mercurial DVCS for its
internal store.
The ``code`` switch should be true if we should use the code store rather
than the script store.
""... |
Update the cache at ``cache_file_name`` to contain the compiled code
represented by ``ccode``. | def update_cache(ccode, cache_file_name):
"""
Update the cache at ``cache_file_name`` to contain the compiled code
represented by ``ccode``.
"""
if cache_file_name is not None:
os.makedirs(os.path.dirname(cache_file_name), exist_ok=True)
with open(cache_file_name, "wb") as cfile:
... |
Wrapper for ``execer.compile`` to compile the given code | def compile_code(filename, code, execer, glb, loc, mode):
"""
Wrapper for ``execer.compile`` to compile the given code
"""
if filename.endswith(".py") and mode == "exec":
return compile(code, filename, mode)
if not code.endswith("\n"):
code += "\n"
old_filename = execer.filenam... |
Check whether the script cache for a particular file is valid.
Returns a tuple containing: a boolean representing whether the cached code
should be used, and the cached code (or ``None`` if the cache should not be
used). | def script_cache_check(filename, cachefname):
"""
Check whether the script cache for a particular file is valid.
Returns a tuple containing: a boolean representing whether the cached code
should be used, and the cached code (or ``None`` if the cache should not be
used).
"""
ccode = None
... |
Run a script, using a cached version if it exists (and the source has not
changed), and updating the cache as necessary.
See run_compiled_code for the return value. | def run_script_with_cache(filename, execer, glb=None, loc=None, mode="exec"):
"""
Run a script, using a cached version if it exists (and the source has not
changed), and updating the cache as necessary.
See run_compiled_code for the return value.
"""
run_cached = False
use_cache = should_use... |
Return an appropriate spoofed filename for the given code. | def code_cache_name(code):
"""
Return an appropriate spoofed filename for the given code.
"""
if isinstance(code, str):
code = code.encode()
return hashlib.md5(code).hexdigest() |
Check whether the code cache for a particular piece of code is valid.
Returns a tuple containing: a boolean representing whether the cached code
should be used, and the cached code (or ``None`` if the cache should not be
used). | def code_cache_check(cachefname):
"""
Check whether the code cache for a particular piece of code is valid.
Returns a tuple containing: a boolean representing whether the cached code
should be used, and the cached code (or ``None`` if the cache should not be
used).
"""
ccode = None
run_... |
Run a piece of code, using a cached version if it exists, and updating the
cache as necessary.
See run_compiled_code for the return value. | def run_code_with_cache(
code, display_filename, execer, glb=None, loc=None, mode="exec"
):
"""
Run a piece of code, using a cached version if it exists, and updating the
cache as necessary.
See run_compiled_code for the return value.
"""
use_cache = should_use_cache(execer, mode)
filena... |
These are the minimum number of colors that need to be implemented by
any style. | def KNOWN_XONSH_COLORS():
"""These are the minimum number of colors that need to be implemented by
any style.
"""
return frozenset(
[
"DEFAULT",
"BLACK",
"RED",
"GREEN",
"YELLOW",
"BLUE",
"PURPLE",
"C... |
Tests if a string is a valid color | def iscolor(s):
"""Tests if a string is a valid color"""
return RE_XONSH_COLOR.match(s) is not None |
color look-up table | def CLUT():
"""color look-up table"""
return [
# 8-bit, RGB hex
# Primary 3-bit (8 colors). Unique representation!
("0", "000000"),
("1", "800000"),
("2", "008000"),
("3", "808000"),
("4", "000080"),
("5", "800080"),
("6", "008080"),
... |
Find the closest ANSI 256 approximation to the given RGB value.
>>> rgb2short('123456')
('23', '005f5f')
>>> rgb2short('ffffff')
('231', 'ffffff')
>>> rgb2short('0DADD6') # vimeo logo
('38', '00afd7')
Parameters
----------
rgb : Hex code representing an RGB value, eg, 'abcdef'
Returns
-------... | def rgb_to_256(rgb):
"""Find the closest ANSI 256 approximation to the given RGB value.
>>> rgb2short('123456')
('23', '005f5f')
>>> rgb2short('ffffff')
('231', 'ffffff')
>>> rgb2short('0DADD6') # vimeo logo
('38', '00afd7')
Parameters
----------
rgb : H... |
Coverts a short (256) color to a 3-tuple of ints. | def short_to_ints(short):
"""Coverts a short (256) color to a 3-tuple of ints."""
return rgb_to_ints(short2rgb(short)) |
Makes a color palette from a collection of strings. | def make_palette(strings):
"""Makes a color palette from a collection of strings."""
palette = {}
for s in strings:
while "#" in s:
_, t = s.split("#", 1)
t, _, s = t.partition(" ")
palette[t] = rgb_to_ints(t)
return palette |
Show a warning once if NO_COLOR was used instead of RESET. | def warn_deprecated_no_color():
"""Show a warning once if NO_COLOR was used instead of RESET."""
global _NO_COLOR_WARNING_SHOWN
if not _NO_COLOR_WARNING_SHOWN:
print_warning("NO_COLOR is deprecated and should be replaced with RESET.")
_NO_COLOR_WARNING_SHOWN = True |
Always say the process is threadable. | def predict_true(_, __):
"""Always say the process is threadable."""
return True |
Never say the process is threadable. | def predict_false(_, __):
"""Never say the process is threadable."""
return False |
Predict the backgroundability of the normal shell interface, which
comes down to whether it is being run in subproc mode. | def predict_shell(args, _):
"""Predict the backgroundability of the normal shell interface, which
comes down to whether it is being run in subproc mode.
"""
ns, _ = SHELL_PREDICTOR_PARSER.parse_known_args(args)
if ns.c is None and ns.filename is None:
pred = False
else:
pred = T... |
Predict the backgroundability of commands that have help & version
switches: -h, --help, -v, -V, --version. If either of these options is
present, the command is assumed to print to stdout normally and is therefore
threadable. Otherwise, the command is assumed to not be threadable.
This is useful for commands, like top... | def predict_help_ver(args, _):
"""Predict the backgroundability of commands that have help & version
switches: -h, --help, -v, -V, --version. If either of these options is
present, the command is assumed to print to stdout normally and is therefore
threadable. Otherwise, the command is assumed to not be... |
Predict if mercurial is about to be run in interactive mode.
If it is interactive, predict False. If it isn't, predict True.
Also predict False for certain commands, such as split. | def predict_hg(args, _):
"""Predict if mercurial is about to be run in interactive mode.
If it is interactive, predict False. If it isn't, predict True.
Also predict False for certain commands, such as split.
"""
ns, _ = HG_PREDICTOR_PARSER.parse_known_args(args)
if ns.command == "split":
... |
Predict if env is launching a threadable command or not.
The launched command is extracted from env args, and the predictor of
lauched command is used. | def predict_env(args, cmd_cache: CommandsCache):
"""Predict if env is launching a threadable command or not.
The launched command is extracted from env args, and the predictor of
lauched command is used."""
for i in range(len(args)):
if args[i] and args[i][0] != "-" and "=" not in args[i]:
... |
Generates a new defaultdict for known threadable predictors.
The default is to predict true. | def default_threadable_predictors():
"""Generates a new defaultdict for known threadable predictors.
The default is to predict true.
"""
# alphabetical, for what it is worth.
predictors = {
"asciinema": predict_help_ver,
"aurman": predict_false,
"awk": predict_true,
"... |
Returns a highlighted string, with bold characters where different. | def highlighted_ndiff(a, b):
"""Returns a highlighted string, with bold characters where different."""
s = ""
sm = difflib.SequenceMatcher()
sm.set_seqs(a, b)
linesm = difflib.SequenceMatcher()
for tag, i1, i2, j1, j2 in sm.get_opcodes():
if tag == REPLACE_S:
for aline, bl... |
Check whether CMD.EXE is enforcing no-UNC-as-working-directory check.
Check can be disabled by setting {HKCU, HKLM}/SOFTWARE\Microsoft\Command Processor\DisableUNCCheck:REG_DWORD=1
Returns:
True if `CMD.EXE` is enforcing the check (default Windows situation)
False if check is explicitly disabled. | def _unc_check_enabled() -> bool:
r"""Check whether CMD.EXE is enforcing no-UNC-as-working-directory check.
Check can be disabled by setting {HKCU, HKLM}/SOFTWARE\Microsoft\Command Processor\DisableUNCCheck:REG_DWORD=1
Returns:
True if `CMD.EXE` is enforcing the check (default Windows situation)
... |
True if path starts with 2 backward (or forward, due to python path hacking) slashes. | def _is_unc_path(some_path) -> bool:
"""True if path starts with 2 backward (or forward, due to python path hacking) slashes."""
return (
len(some_path) > 1
and some_path[0] == some_path[1]
and some_path[0] in (os.sep, os.altsep)
) |
Map a new temporary drive letter for each distinct share,
unless `CMD.EXE` is not insisting on non-UNC working directory.
Emulating behavior of `CMD.EXE` `pushd`, create a new mapped drive (starting from Z: towards A:, skipping existing
drive letters) for each new UNC path user selects.
Args:
unc_path: the path ... | def _unc_map_temp_drive(unc_path) -> str:
r"""Map a new temporary drive letter for each distinct share,
unless `CMD.EXE` is not insisting on non-UNC working directory.
Emulating behavior of `CMD.EXE` `pushd`, create a new mapped drive (starting from Z: towards A:, skipping existing
drive letters) for ... |
Unmap a temporary drive letter if it is no longer needed.
Called after popping `DIRSTACK` and changing to new working directory, so we need stack *and*
new current working directory to be sure drive letter no longer needed.
Args:
left_drive: driveletter (and colon) of working directory we just left
cwd: full p... | def _unc_unmap_temp_drive(left_drive, cwd):
"""Unmap a temporary drive letter if it is no longer needed.
Called after popping `DIRSTACK` and changing to new working directory, so we need stack *and*
new current working directory to be sure drive letter no longer needed.
Args:
left_drive: drivel... |
Changes the directory.
If no directory is specified (i.e. if `args` is None) then this
changes to the current user's home directory. | def cd(args, stdin=None):
"""Changes the directory.
If no directory is specified (i.e. if `args` is None) then this
changes to the current user's home directory.
"""
env = XSH.env
oldpwd = env.get("OLDPWD", None)
cwd = env["PWD"]
follow_symlinks = False
if len(args) > 0 and args[0]... |
Adds a directory to the top of the directory stack, or rotates the stack,
making the new top of the stack the current working directory.
On Windows, if the path is a UNC path (begins with `\\<server>\<share>`) and if the `DisableUNCCheck` registry
value is not enabled, creates a temporary mapped drive letter and sets ... | def pushd_fn(
dir_or_n: Annotated[tp.Optional[str], Arg(metavar="+N|-N|dir", nargs="?")] = None,
cd=True,
quiet=False,
):
r"""Adds a directory to the top of the directory stack, or rotates the stack,
making the new top of the stack the current working directory.
On Windows, if the path is a UNC... |
When no arguments are given, popd removes the top directory from the stack
and performs a cd to the new top directory.
The elements are numbered from 0 starting at the first directory listed with ``dirs``;
that is, popd is equivalent to popd +0.
Parameters
----------
cd : -n, --cd
Suppresses the normal change of d... | def popd_fn(
nth: Annotated[tp.Optional[str], Arg(metavar="+N|-N", nargs="?")] = None,
cd=True,
quiet=False,
):
"""When no arguments are given, popd removes the top directory from the stack
and performs a cd to the new top directory.
The elements are numbered from 0 starting at the first directo... |
Manage the list of currently remembered directories.
Parameters
----------
nth
Displays the Nth directory (counting from the left/right according to +/x prefix respectively),
starting with zero
clear : -c
Clears the directory stack by deleting all of the entries.
print_long : -p
Print the directory sta... | def dirs_fn(
nth: Annotated[tp.Optional[str], Arg(metavar="N", nargs="?")] = None,
clear=False,
print_long=False,
verbose=False,
long=False,
):
"""Manage the list of currently remembered directories.
Parameters
----------
nth
Displays the Nth directory (counting from the lef... |
Use pushd as a context manager | def with_pushd(d):
"""Use pushd as a context manager"""
pushd_fn(d)
try:
yield
finally:
popd_fn() |
Creates a converter for a locale key. | def locale_convert(key):
"""Creates a converter for a locale key."""
def lc_converter(val):
try:
locale.setlocale(LOCALE_CATS[key], val)
val = locale.setlocale(LOCALE_CATS[key])
except (locale.Error, KeyError):
msg = f"Failed to set locale {key!r} to {val!r}"... |
Converts value using to_bool_or_int() and sets this value on as the
execer's debug level. | def to_debug(x):
"""Converts value using to_bool_or_int() and sets this value on as the
execer's debug level.
"""
val = to_bool_or_int(x)
if XSH.execer is not None:
XSH.execer.debug_level = val
return val |
Checks if an object is an instance of LsColors | def is_lscolors(x):
"""Checks if an object is an instance of LsColors"""
return isinstance(x, LsColors) |
This ensures that the $LS_COLORS environment variable is in the
environment. This fires exactly once upon the first time the
ls command is called. | def ensure_ls_colors_in_env(spec=None, **kwargs):
"""This ensures that the $LS_COLORS environment variable is in the
environment. This fires exactly once upon the first time the
ls command is called.
"""
env = XSH.env
if "LS_COLORS" not in env._d:
# this adds it to the env too
de... |
Decorator for making callable default values. | def default_value(f):
"""Decorator for making callable default values."""
f._xonsh_callable_default = True
return f |
Checks if a value is a callable default. | def is_callable_default(x):
"""Checks if a value is a callable default."""
return callable(x) and getattr(x, "_xonsh_callable_default", False) |
Ensures and returns the $XONSH_DATA_DIR | def xonsh_data_dir(env):
"""Ensures and returns the $XONSH_DATA_DIR"""
xdd = os.path.expanduser(os.path.join(env.get("XDG_DATA_HOME"), "xonsh"))
os.makedirs(xdd, exist_ok=True)
return xdd |
Ensures and returns the $XONSH_CACHE_DIR | def xonsh_cache_dir(env):
"""Ensures and returns the $XONSH_CACHE_DIR"""
xdd = os.path.expanduser(os.path.join(env.get("XDG_CACHE_HOME"), "xonsh"))
os.makedirs(xdd, exist_ok=True)
return xdd |
``$XDG_CONFIG_HOME/xonsh`` | def xonsh_config_dir(env):
"""``$XDG_CONFIG_HOME/xonsh``"""
xcd = os.path.expanduser(os.path.join(env.get("XDG_CONFIG_HOME"), "xonsh"))
os.makedirs(xcd, exist_ok=True)
return xcd |
On Windows: ``[%ProgramData%]`` (normally C:\ProgramData)
- More Info: https://docs.microsoft.com/en-us/windows-hardware/customize/desktop/unattend/microsoft-windows-shell-setup-folderlocations-programdata
On Linux and Unix based systemd it is the same as in open-desktop standard: ``['/usr/share', '/usr/local/shar... | def xdg_data_dirs(env):
r"""
On Windows: ``[%ProgramData%]`` (normally C:\ProgramData)
- More Info: https://docs.microsoft.com/en-us/windows-hardware/customize/desktop/unattend/microsoft-windows-shell-setup-folderlocations-programdata
On Linux and Unix based systemd it is the same as in open-deskto... |
On Linux & Mac OSX: ``'/etc/xonsh'``
On Windows: ``'%ALLUSERSPROFILE%\\xonsh'`` | def xonsh_sys_config_dir(env):
"""
On Linux & Mac OSX: ``'/etc/xonsh'``
On Windows: ``'%ALLUSERSPROFILE%\\\\xonsh'``
"""
if ON_WINDOWS:
etc_path = os_environ["ALLUSERSPROFILE"]
else:
etc_path = "/etc"
return os.path.join(etc_path, "xonsh") |
Ensures and returns the $XONSHCONFIG | def xonshconfig(env):
"""Ensures and returns the $XONSHCONFIG"""
xcd = env.get("XONSH_CONFIG_DIR")
xc = os.path.join(xcd, "config.json")
return xc |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.