response stringlengths 1 33.1k | instruction stringlengths 22 582k |
|---|---|
Complete attributes of an object. | def attr_complete(prefix, ctx, filter_func):
"""Complete attributes of an object."""
attrs = set()
m = RE_ATTR.match(prefix)
if m is None:
return attrs
expr, attr = m.group(1, 3)
expr = xt.subexpr_from_unbalanced(expr, "(", ")")
expr = xt.subexpr_from_unbalanced(expr, "[", "]")
e... |
Completes a python function (or other callable) call by completing
argument and keyword argument names. | def python_signature_complete(prefix, line, end, ctx, filter_func):
"""Completes a python function (or other callable) call by completing
argument and keyword argument names.
"""
front = line[:end]
if xt.is_balanced(front, "(", ")"):
return set()
funcname = xt.subexpr_before_unbalanced(f... |
Return an appropriate filtering function for completions, given the valid
of $CASE_SENSITIVE_COMPLETIONS | def get_filter_function():
"""
Return an appropriate filtering function for completions, given the valid
of $CASE_SENSITIVE_COMPLETIONS
"""
csc = XSH.env.get("CASE_SENSITIVE_COMPLETIONS")
if csc:
return _filter_normal
else:
return _filter_ignorecase |
Re-wrap the string s so that each line is no more than max_length
characters long, padding all lines but the first on the left with the
string left_pad. | def justify(s, max_length, left_pad=0):
"""
Re-wrap the string s so that each line is no more than max_length
characters long, padding all lines but the first on the left with the
string left_pad.
"""
txt = textwrap.wrap(s, width=max_length, subsequent_indent=" " * left_pad)
return "\n".join... |
The ``__init__`` parameters' default values (excluding ``self`` and ``value``). | def RICH_COMPLETION_DEFAULTS():
"""The ``__init__`` parameters' default values (excluding ``self`` and ``value``)."""
return [
(name, param.default)
for name, param in inspect.signature(RichCompletion.__init__).parameters.items()
if name not in ("self", "value")
] |
Decorator for a contextual completer
This is used to mark completers that want to use the parsed completion context.
See ``xonsh/parsers/completion_context.py``.
``func`` receives a single CompletionContext object. | def contextual_completer(func: ContextualCompleter):
"""Decorator for a contextual completer
This is used to mark completers that want to use the parsed completion context.
See ``xonsh/parsers/completion_context.py``.
``func`` receives a single CompletionContext object.
"""
func.contextual = T... |
like ``contextual_completer``,
but will only run when completing a command and will directly receive the ``CommandContext`` object | def contextual_command_completer(func: tp.Callable[[CommandContext], CompleterResult]):
"""like ``contextual_completer``,
but will only run when completing a command and will directly receive the ``CommandContext`` object
"""
@contextual_completer
@wraps(func)
def _completer(context: Completion... |
like ``contextual_command_completer``,
but will only run when completing the ``cmd`` command | def contextual_command_completer_for(cmd: str):
"""like ``contextual_command_completer``,
but will only run when completing the ``cmd`` command"""
def decor(func: tp.Callable[[CommandContext], CompleterResult]):
@contextual_completer
@wraps(func)
def _completer(context: CompletionCo... |
Decorator for a non-exclusive completer
This is used to mark completers that will be collected with other completer's results. | def non_exclusive_completer(func):
"""Decorator for a non-exclusive completer
This is used to mark completers that will be collected with other completer's results.
"""
func.non_exclusive = True # type: ignore
return func |
Helper function to complete commands such as ``pip``,``django-admin``,... that use bash's ``complete`` | def comp_based_completer(ctx: CommandContext, start_index=0, **env: str):
"""Helper function to complete commands such as ``pip``,``django-admin``,... that use bash's ``complete``"""
prefix = ctx.prefix
args = [arg.value for arg in ctx.args]
if prefix:
args.append(prefix)
yield from comple... |
for backward compatibility | def _remove_completer(args):
"""for backward compatibility"""
return remove_completer(args[0]) |
Return all callable names in the current context | def complete_func_name_choices(xsh, **_):
"""Return all callable names in the current context"""
for i, j in xsh.ctx.items():
if callable(j):
yield i |
Compute possible positions for the new completer | def complete_completer_pos_choices(xsh, **_):
"""Compute possible positions for the new completer"""
yield from {"start", "end"}
for k in xsh.completers.keys():
yield ">" + k
yield "<" + k |
Add a new completer to xonsh
Parameters
----------
name
unique name to use in the listing (run "completer list" to see the
current completers in order)
func
the name of a completer function to use. This should be a function
that takes a Completion Context object and marked with the
``xonsh.comp... | def _register_completer(
name: str,
func: xcli.Annotated[str, xcli.Arg(completer=complete_func_name_choices)],
pos: xcli.Annotated[
str, xcli.Arg(completer=complete_completer_pos_choices, nargs="?")
] = "start",
_stack=None,
):
"""Add a new completer to xonsh
Parameters
--------... |
Complete any alias that has ``xonsh_complete`` attribute.
The said attribute should be a function. The current command context is passed to it. | def complete_aliases(command: CommandContext):
"""Complete any alias that has ``xonsh_complete`` attribute.
The said attribute should be a function. The current command context is passed to it.
"""
if not command.args:
return
cmd = command.args[0].value
if cmd not in XSH.aliases:
... |
Return number of units and list of history files to remove to get under the limit,
Parameters:
-----------
hsize (int): units of history, # of commands in this case.
files ((mod_ts, num_commands, path)[], fsize): history files, sorted oldest first.
Returns:
--------
hsize_removed (int): units of history to be remov... | def _xhj_gc_commands_to_rmfiles(hsize, files):
"""Return number of units and list of history files to remove to get under the limit,
Parameters:
-----------
hsize (int): units of history, # of commands in this case.
files ((mod_ts, num_commands, path)[], fsize): history files, sorted oldest first.... |
Return the number and list of history files to remove to get under the file limit. | def _xhj_gc_files_to_rmfiles(hsize, files):
"""Return the number and list of history files to remove to get under the file limit."""
rmfiles = files[:-hsize] if len(files) > hsize else []
return len(rmfiles), rmfiles |
Return excess duration and list of history files to remove to get under the age limit. | def _xhj_gc_seconds_to_rmfiles(hsize, files):
"""Return excess duration and list of history files to remove to get under the age limit."""
now = time.time()
n = 0
for ts, _, _, _ in files:
if (now - ts) < hsize:
break
n += 1
rmfiles = files[:n]
size_over = now - hs... |
Return the history files to remove to get under the byte limit. | def _xhj_gc_bytes_to_rmfiles(hsize, files):
"""Return the history files to remove to get under the byte limit."""
n = 0
nbytes = 0
for _, _, _, fsize in reversed(files):
if nbytes + fsize > hsize:
break
nbytes += fsize
n += 1
bytes_removed = 0
files_removed =... |
Find and return the history files. Optionally sort files by
modify time. | def _xhj_get_history_files(sort=True, newest_first=False):
"""Find and return the history files. Optionally sort files by
modify time.
"""
data_dirs = [
_xhj_get_data_dir(),
XSH.env.get("XONSH_DATA_DIR"), # backwards compatibility, remove in the future
]
files = []
for data... |
Construct the history backend object. | def construct_history(backend=None, **kwargs) -> "History":
"""Construct the history backend object."""
env = XSH.env
backend = backend or env.get("XONSH_HISTORY_BACKEND", "json")
if isinstance(backend, str) and backend in HISTORY_BACKENDS:
kls_history = HISTORY_BACKENDS[backend]
elif xt.is... |
Returns history items of current session. | def _xh_session_parser(hist=None, newest_first=False, **kwargs):
"""Returns history items of current session."""
if hist is None:
hist = XSH.history
return hist.items() |
Returns all history items. | def _xh_all_parser(hist=None, newest_first=False, **kwargs):
"""Returns all history items."""
if hist is None:
hist = XSH.history
return hist.all_items(newest_first=newest_first) |
Return the path of the history file
from the value of the envvar HISTFILE. | def _xh_find_histfile_var(file_list, default=None):
"""Return the path of the history file
from the value of the envvar HISTFILE.
"""
for f in file_list:
f = xt.expanduser_abs_path(f)
if not os.path.isfile(f):
continue
with open(f) as rc_file:
for line ... |
Yield commands from bash history file | def _xh_bash_hist_parser(location=None, **kwargs):
"""Yield commands from bash history file"""
if location is None:
location = _xh_find_histfile_var(
[os.path.join("~", ".bashrc"), os.path.join("~", ".bash_profile")],
os.path.join("~", ".bash_history"),
)
if location... |
Yield commands from zsh history file | def _xh_zsh_hist_parser(location=None, **kwargs):
"""Yield commands from zsh history file"""
if location is None:
location = _xh_find_histfile_var(
[os.path.join("~", ".zshrc"), os.path.join("~", ".zprofile")],
os.path.join("~", ".zsh_history"),
)
if location:
... |
Yield only the commands between start and end time. | def _xh_filter_ts(commands, start_time, end_time):
"""Yield only the commands between start and end time."""
for cmd in commands:
if start_time <= cmd["ts"] < end_time:
yield cmd |
Get the requested portion of shell history.
Parameters
----------
session: {'session', 'all', 'xonsh', 'bash', 'zsh'}
The history session to get.
slices : list of slice-like objects, optional
Get only portions of history.
start_time, end_time: float, optional
Filter commands by timestamp.
location: string,... | def _xh_get_history(
session="session",
*,
slices=None,
datetime_format=None,
start_time=None,
end_time=None,
location=None,
):
"""Get the requested portion of shell history.
Parameters
----------
session: {'session', 'all', 'xonsh', 'bash', 'zsh'}
The history sessio... |
Create Table for history items.
Columns:
info - JSON formatted, reserved for future extension.
frequency - in case of HISTCONTROL=erasedups,
it tracks the frequency of the inputs. helps in sorting autocompletion | def _xh_sqlite_create_history_table(cursor):
"""Create Table for history items.
Columns:
info - JSON formatted, reserved for future extension.
frequency - in case of HISTCONTROL=erasedups,
it tracks the frequency of the inputs. helps in sorting autocompletion
"""
if not getattr(... |
handy function to run insert query | def _sql_insert(cursor, values):
# type: (sqlite3.Cursor, dict) -> None
"""handy function to run insert query"""
sql = "INSERT INTO {} ({}) VALUES ({});"
fields = ", ".join(values)
marks = ", ".join(["?"] * len(values))
cursor.execute(
sql.format(XH_SQLITE_TABLE_NAME, fields, marks), tup... |
Wipe the current session's entries from the database. | def xh_sqlite_wipe_session(sessionid=None, filename=None):
"""Wipe the current session's entries from the database."""
sql = "DELETE FROM xonsh_history WHERE sessionid = ?"
with _xh_sqlite_get_conn(filename=filename) as conn:
c = conn.cursor()
_xh_sqlite_create_history_table(c)
c.exe... |
Deletes entries from the database where the input matches a pattern. | def xh_sqlite_delete_input_matching(pattern, filename=None):
"""Deletes entries from the database where the input matches a pattern."""
with _xh_sqlite_get_conn(filename=filename) as conn:
c = conn.cursor()
_xh_sqlite_create_history_table(c)
for inp, *_ in _xh_sqlite_get_records(c):
... |
Utility for converting an object to an iterable.
Parameters
----------
iterable_or_scalar : anything
Returns
-------
l : iterable
If `obj` was None, return the empty tuple.
If `obj` was not iterable returns a 1-tuple containing `obj`.
Otherwise return `obj`
Notes
-----
Although string types are iterable i... | def as_iterable(iterable_or_scalar):
"""Utility for converting an object to an iterable.
Parameters
----------
iterable_or_scalar : anything
Returns
-------
l : iterable
If `obj` was None, return the empty tuple.
If `obj` was not iterable returns a 1-tuple containing `obj`.
... |
Remove a directory, even if it has read-only files (Windows).
Git creates read-only files that must be removed on teardown. See
https://stackoverflow.com/questions/2656322 for more info.
Parameters
----------
dirname : str
Directory to be removed
force : bool
If True force removal, defaults to False | def rmtree(dirname, force=False):
"""Remove a directory, even if it has read-only files (Windows).
Git creates read-only files that must be removed on teardown. See
https://stackoverflow.com/questions/2656322 for more info.
Parameters
----------
dirname : str
Directory to be removed
... |
Drop in replacement for ``subprocess.run`` like functionality | def run(cmd, cwd=None, check=False):
"""Drop in replacement for ``subprocess.run`` like functionality"""
env = XSH.env
if cwd is None:
with env.swap(RAISE_SUBPROC_ERROR=check):
p = subproc_captured_hiddenobject(cmd)
else:
with indir(cwd), env.swap(RAISE_SUBPROC_ERROR=check):... |
Drop in replacement for ``subprocess.check_call`` like functionality | def check_call(cmd, cwd=None):
"""Drop in replacement for ``subprocess.check_call`` like functionality"""
p = run(cmd, cwd=cwd, check=True)
return p.returncode |
Drop in replacement for ``subprocess.check_output`` like functionality | def check_output(cmd, cwd=None):
"""Drop in replacement for ``subprocess.check_output`` like functionality"""
env = XSH.env
if cwd is None:
with env.swap(RAISE_SUBPROC_ERROR=True):
output = subproc_captured_stdout(cmd)
else:
with indir(cwd), env.swap(RAISE_SUBPROC_ERROR=Tru... |
Ensures that x is an AST node with elements. | def ensure_has_elts(x, lineno=None, col_offset=None):
"""Ensures that x is an AST node with elements."""
if not has_elts(x):
if not isinstance(x, Iterable):
x = [x]
lineno = x[0].lineno if lineno is None else lineno
col_offset = x[0].col_offset if col_offset is None else col... |
Creates the AST node for an empty list. | def empty_list(lineno=None, col=None):
"""Creates the AST node for an empty list."""
return ast.List(elts=[], ctx=ast.Load(), lineno=lineno, col_offset=col) |
Creates the AST node for a binary operation. | def binop(x, op, y, lineno=None, col=None):
"""Creates the AST node for a binary operation."""
lineno = x.lineno if lineno is None else lineno
col = x.col_offset if col is None else col
return ast.BinOp(left=x, op=op, right=y, lineno=lineno, col_offset=col) |
Creates the AST node for calling the 'splitlines' attribute of an
object, nominally a string. | def call_split_lines(x, lineno=None, col=None):
"""Creates the AST node for calling the 'splitlines' attribute of an
object, nominally a string.
"""
return ast.Call(
func=ast.Attribute(
value=x, attr="splitlines", ctx=ast.Load(), lineno=lineno, col_offset=col
),
args=... |
Creates the AST node for the following expression::
[x] if isinstance(x, str) else x
Somewhat useful. | def ensure_list_from_str_or_list(x, lineno=None, col=None):
"""Creates the AST node for the following expression::
[x] if isinstance(x, str) else x
Somewhat useful.
"""
return ast.IfExp(
test=ast.Call(
func=ast.Name(
id="isinstance", ctx=ast.Load(), lineno=l... |
Creates the AST node for calling the __xonsh__.help() function. | def xonsh_help(x, lineno=None, col=None):
"""Creates the AST node for calling the __xonsh__.help() function."""
return xonsh_call("__xonsh__.help", [x], lineno=lineno, col=col) |
Creates the AST node for calling the __xonsh__.superhelp() function. | def xonsh_superhelp(x, lineno=None, col=None):
"""Creates the AST node for calling the __xonsh__.superhelp() function."""
return xonsh_call("__xonsh__.superhelp", [x], lineno=lineno, col=col) |
Recursively sets ctx to ast.Load() | def load_ctx(x):
"""Recursively sets ctx to ast.Load()"""
if not hasattr(x, "ctx"):
return
x.ctx = ast.Load()
if isinstance(x, (ast.Tuple, ast.List)):
for e in x.elts:
load_ctx(e)
elif isinstance(x, ast.Starred):
load_ctx(x.value) |
Recursively sets ctx to ast.Store() | def store_ctx(x):
"""Recursively sets ctx to ast.Store()"""
if not hasattr(x, "ctx"):
return
x.ctx = ast.Store()
if isinstance(x, (ast.Tuple, ast.List)):
for e in x.elts:
store_ctx(e)
elif isinstance(x, ast.Starred):
store_ctx(x.value) |
Recursively sets ctx to ast.Del() | def del_ctx(x):
"""Recursively sets ctx to ast.Del()"""
if not hasattr(x, "ctx"):
return
x.ctx = ast.Del()
if isinstance(x, (ast.Tuple, ast.List)):
for e in x.elts:
del_ctx(e)
elif isinstance(x, ast.Starred):
del_ctx(x.value) |
Extracts the line and column number for a node that may have an opening
parenthesis, brace, or bracket. | def lopen_loc(x):
"""Extracts the line and column number for a node that may have an opening
parenthesis, brace, or bracket.
"""
lineno = x._lopen_lineno if hasattr(x, "_lopen_lineno") else x.lineno
col = x._lopen_col if hasattr(x, "_lopen_col") else x.col_offset
return lineno, col |
Returns True if a node has literal '*' for globbing. | def hasglobstar(x):
"""Returns True if a node has literal '*' for globbing."""
if ast.is_const_str(x):
return "*" in x.value
elif isinstance(x, list):
for e in x:
if hasglobstar(e):
return True
else:
return False
else:
return Fal... |
Returns (line_continuation, replacement, diff).
Diff is the diff in length for each replacement. | def LINE_CONT_REPLACEMENT_DIFF():
"""Returns (line_continuation, replacement, diff).
Diff is the diff in length for each replacement.
"""
line_cont = get_line_continuation()
if " \\" == line_cont:
# interactive windows
replacement = " "
else:
replacement = ""
line_co... |
If ``x`` represents a value that can be assigned to, return ``None``.
Otherwise, return a string describing the object. For use in generating
meaningful syntax errors. | def _not_assignable(x, augassign=False):
"""
If ``x`` represents a value that can be assigned to, return ``None``.
Otherwise, return a string describing the object. For use in generating
meaningful syntax errors.
"""
if augassign and isinstance(x, (ast.Tuple, ast.List)):
return "literal... |
\s+ | def t_CPP_WS(t):
r'\s+'
t.lexer.lineno += t.value.count("\n")
return t |
(((((0x)|(0X))[0-9a-fA-F]+)|(\d+))([uU][lL]|[lL][uU]|[uU]|[lL])?) | def CPP_INTEGER(t):
r'(((((0x)|(0X))[0-9a-fA-F]+)|(\d+))([uU][lL]|[lL][uU]|[uU]|[lL])?)'
return t |
\"([^\\\n]|(\\(.|\n)))*?\" | def t_CPP_STRING(t):
r'\"([^\\\n]|(\\(.|\n)))*?\"'
t.lexer.lineno += t.value.count("\n")
return t |
(L)?\'([^\\\n]|(\\(.|\n)))*?\' | def t_CPP_CHAR(t):
r'(L)?\'([^\\\n]|(\\(.|\n)))*?\''
t.lexer.lineno += t.value.count("\n")
return t |
(/\*(.|\n)*?\*/) | def t_CPP_COMMENT1(t):
r'(/\*(.|\n)*?\*/)'
ncr = t.value.count("\n")
t.lexer.lineno += ncr
# replace with one space or a number of '\n'
t.type = 'CPP_WS'; t.value = '\n' * ncr if ncr else ' '
return t |
(//.*?(\n|$)) | def t_CPP_COMMENT2(t):
r'(//.*?(\n|$))'
# replace with '/n'
t.type = 'CPP_WS'; t.value = '\n'
return t |
/\*(.|\n)*?\*/ | def t_COMMENT(t):
r'/\*(.|\n)*?\*/'
t.lexer.lineno += t.value.count('\n')
return t |
//.*\n | def t_CPPCOMMENT(t):
r'//.*\n'
t.lexer.lineno += 1
return t |
Attempts to read lines without throwing an error. | def safe_readlines(handle, hint=-1):
"""Attempts to read lines without throwing an error."""
try:
lines = handle.readlines(hint)
except OSError:
lines = []
return lines |
Attempts to find if the handle is readable without throwing an error. | def safe_readable(handle):
"""Attempts to find if the handle is readable without throwing an error."""
try:
status = handle.readable()
except (OSError, ValueError):
status = False
return status |
Sends SIGCONT to a process if possible. | def resume_process(p):
"""Sends SIGCONT to a process if possible."""
can_send_signal = (
hasattr(p, "send_signal")
and xp.ON_POSIX
and not xp.ON_MSYS
and not xp.ON_CYGWIN
)
if can_send_signal:
try:
p.send_signal(signal.SIGCONT)
except Permissio... |
Determines whether a file descriptor is still writable by trying to
write an empty string and seeing if it fails. | def still_writable(fd):
"""Determines whether a file descriptor is still writable by trying to
write an empty string and seeing if it fails.
"""
try:
os.write(fd, b"")
status = True
except OSError:
status = False
return status |
Attempts to safely flush a file handle, returns success bool. | def safe_flush(handle):
"""Attempts to safely flush a file handle, returns success bool."""
status = True
try:
handle.flush()
except OSError:
status = False
return status |
Proxies may return a variety of outputs. This handles them generally.
Parameters
----------
r : tuple, str, int, or None
Return from proxy function
stdout : file-like
Current stdout stream
stdout : file-like
Current stderr stream
Returns
-------
cmd_result : int
The return code of the proxy | def parse_proxy_return(r, stdout, stderr):
"""Proxies may return a variety of outputs. This handles them generally.
Parameters
----------
r : tuple, str, int, or None
Return from proxy function
stdout : file-like
Current stdout stream
stdout : file-like
Current stderr st... |
Calls a proxy function which takes no parameters. | def proxy_zero(f, args, stdin, stdout, stderr, spec, stack):
"""Calls a proxy function which takes no parameters."""
return f() |
Calls a proxy function which takes one parameter: args | def proxy_one(f, args, stdin, stdout, stderr, spec, stack):
"""Calls a proxy function which takes one parameter: args"""
return f(args) |
Calls a proxy function which takes two parameter: args and stdin. | def proxy_two(f, args, stdin, stdout, stderr, spec, stack):
"""Calls a proxy function which takes two parameter: args and stdin."""
return f(args, stdin) |
Calls a proxy function which takes three parameter: args, stdin, stdout. | def proxy_three(f, args, stdin, stdout, stderr, spec, stack):
"""Calls a proxy function which takes three parameter: args, stdin, stdout."""
return f(args, stdin, stdout) |
Calls a proxy function which takes four parameter: args, stdin, stdout,
and stderr. | def proxy_four(f, args, stdin, stdout, stderr, spec, stack):
"""Calls a proxy function which takes four parameter: args, stdin, stdout,
and stderr.
"""
return f(args, stdin, stdout, stderr) |
Calls a proxy function which takes four parameter: args, stdin, stdout,
stderr, and spec. | def proxy_five(f, args, stdin, stdout, stderr, spec, stack):
"""Calls a proxy function which takes four parameter: args, stdin, stdout,
stderr, and spec.
"""
return f(args, stdin, stdout, stderr, spec) |
Dispatches the appropriate proxy function based on the number of args. | def partial_proxy(f):
"""Dispatches the appropriate proxy function based on the number of args."""
numargs = 0
for name, param in inspect.signature(f).parameters.items():
# handle *args/**kwargs signature
if param.kind in {param.VAR_KEYWORD, param.VAR_POSITIONAL}:
numargs = 6
... |
Reads 1 kb of data from a file descriptor into a queue.
If this ends or fails, it flags the calling reader object as closed. | def populate_fd_queue(reader, fd, queue):
"""Reads 1 kb of data from a file descriptor into a queue.
If this ends or fails, it flags the calling reader object as closed.
"""
while True:
try:
c = os.read(fd, 1024)
except OSError:
reader.closed = True
br... |
Reads bytes from the file descriptor and copies them into a buffer.
The reads happen in parallel using the pread() syscall; which is only
available on POSIX systems. If the read fails for any reason, the reader is
flagged as closed. | def populate_buffer(reader, fd, buffer, chunksize):
"""Reads bytes from the file descriptor and copies them into a buffer.
The reads happen in parallel using the pread() syscall; which is only
available on POSIX systems. If the read fails for any reason, the reader is
flagged as closed.
"""
off... |
Reads bytes from the file descriptor and puts lines into the queue.
The reads happened in parallel,
using xonsh.winutils.read_console_output_character(),
and is thus only available on windows. If the read fails for any reason,
the reader is flagged as closed. | def populate_console(reader, fd, buffer, chunksize, queue, expandsize=None):
"""Reads bytes from the file descriptor and puts lines into the queue.
The reads happened in parallel,
using xonsh.winutils.read_console_output_character(),
and is thus only available on windows. If the read fails for any reaso... |
Closes a file handle in the safest way possible, and potentially
storing the result. | def safe_fdclose(handle, cache=None):
"""Closes a file handle in the safest way possible, and potentially
storing the result.
"""
if cache is not None and cache.get(handle, False):
return
status = True
if handle is None:
pass
elif isinstance(handle, int):
if handle... |
App execution aliases behave strangly on Windows and Python.
Here we try to detect if a file is an app execution alias. | def is_app_execution_alias(fname):
"""App execution aliases behave strangly on Windows and Python.
Here we try to detect if a file is an app execution alias.
"""
fname = pathlib.Path(fname)
try:
return fname.stat().st_reparse_tag == stat.IO_REPARSE_TAG_APPEXECLINK
# os.stat().st_reparse... |
Given the name of a script outside the path, returns a list representing
an appropriate subprocess command to execute the script or None if
the argument is not readable or not a script. Raises PermissionError
if the script is not executable. | def get_script_subproc_command(fname, args):
"""Given the name of a script outside the path, returns a list representing
an appropriate subprocess command to execute the script or None if
the argument is not readable or not a script. Raises PermissionError
if the script is not executable.
"""
# ... |
Safely attempts to open a file in for xonsh subprocs. | def safe_open(fname, mode, buffering=-1):
"""Safely attempts to open a file in for xonsh subprocs."""
# file descriptors
try:
return open(fname, mode, buffering=buffering)
except PermissionError as ex:
raise xt.XonshError(f"xonsh: {fname}: permission denied") from ex
except FileNotFo... |
Safely attempts to close an object. | def safe_close(x):
"""Safely attempts to close an object."""
if not isinstance(x, io.IOBase):
return
if x.closed:
return
try:
x.close()
except Exception:
pass |
returns origin, mode, destination tuple | def _parse_redirects(r, loc=None):
"""returns origin, mode, destination tuple"""
orig, mode, dest = _REDIR_REGEX.match(r).groups()
# redirect to fd
if dest.startswith("&"):
try:
dest = int(dest[1:])
if loc is None:
loc, dest = dest, "" # NOQA
... |
Returns stdin, stdout, stderr tuple of redirections. | def _redirect_streams(r, loc=None):
"""Returns stdin, stdout, stderr tuple of redirections."""
stdin = stdout = stderr = None
no_ampersand = r.replace("&", "")
# special case of redirecting stderr to stdout
if no_ampersand in _E2O_MAP:
stderr = subprocess.STDOUT
return stdin, stdout,... |
Transforms a command like ['ls', ('>', '/dev/null')] into ['ls', '>', '/dev/null']. | def _flatten_cmd_redirects(cmd):
"""Transforms a command like ['ls', ('>', '/dev/null')] into ['ls', '>', '/dev/null']."""
new_cmd = []
for c in cmd:
if isinstance(c, tuple):
new_cmd.extend(c)
else:
new_cmd.append(c)
return new_cmd |
Pauses a signal, as needed. | def default_signal_pauser(n, f):
"""Pauses a signal, as needed."""
signal.pause() |
Default subprocess preexec function for when there is no existing
pipeline group. | def no_pg_xonsh_preexec_fn():
"""Default subprocess preexec function for when there is no existing
pipeline group.
"""
os.setpgrp()
signal.signal(signal.SIGTSTP, default_signal_pauser) |
Makes sure that a pipe file descriptor properties are reasonable. | def _safe_pipe_properties(fd, use_tty=False):
"""Makes sure that a pipe file descriptor properties are reasonable."""
if not use_tty:
return
# due to some weird, long standing issue in Python, PTYs come out
# replacing newline \n with \r\n. This causes issues for raw unix
# protocols, like g... |
Converts a list of cmds to a list of SubprocSpec objects that are
ready to be executed. | def cmds_to_specs(cmds, captured=False, envs=None):
"""Converts a list of cmds to a list of SubprocSpec objects that are
ready to be executed.
"""
# first build the subprocs independently and separate from the redirects
i = 0
specs = []
redirects = []
for i, cmd in enumerate(cmds):
... |
Runs a subprocess, in its many forms. This takes a list of 'commands,'
which may be a list of command line arguments or a string, representing
a special connecting character. For example::
$ ls | grep wakka
is represented by the following cmds::
[['ls'], '|', ['grep', 'wakka']]
Lastly, the captured argumen... | def run_subproc(cmds, captured=False, envs=None):
"""Runs a subprocess, in its many forms. This takes a list of 'commands,'
which may be a list of command line arguments or a string, representing
a special connecting character. For example::
$ ls | grep wakka
is represented by the following c... |
Join the tokens
Parameters
----------
container: ParsedTokens
parsed tokens holder
Returns
-------
str
process the tokens and finally return the prompt string | def prompt_tokens_formatter_default(container: ParsedTokens) -> str:
"""
Join the tokens
Parameters
----------
container: ParsedTokens
parsed tokens holder
Returns
-------
str
process the tokens and finally return the prompt string
"""
return "".join([tok.va... |
Creates a new instance of the default prompt. | def default_prompt():
"""Creates a new instance of the default prompt."""
if xp.ON_CYGWIN or xp.ON_MSYS:
dp = (
"{env_name}"
"{BOLD_GREEN}{user}@{hostname}"
"{BOLD_BLUE} {cwd} {prompt_end}{RESET} "
)
elif xp.ON_WINDOWS and not xp.win_ansi_support():
... |
Returns the filler text for the prompt in multiline scenarios. | def multiline_prompt(curr=""):
"""Returns the filler text for the prompt in multiline scenarios."""
line = curr.rsplit("\n", 1)[1] if "\n" in curr else curr
line = RE_HIDDEN.sub("", line) # gets rid of colors
# most prompts end in whitespace, head is the part before that.
head = line.rstrip()
h... |
Returns whether or not the string is a valid template. | def is_template_string(template, PROMPT_FIELDS=None):
"""Returns whether or not the string is a valid template."""
template = template() if callable(template) else template
try:
included_names = {i[1] for i in xt.FORMATTER.parse(template)}
except ValueError:
return False
included_nam... |
Formats a value from a template string {val!conv:spec}. The spec is
applied as a format string itself, but if the value is None, the result
will be empty. The purpose of this is to allow optional parts in a
prompt string. For example, if the prompt contains '{current_job:{} | }',
and 'current_job' returns 'sleep', the ... | def _format_value(val, spec, conv) -> str:
"""Formats a value from a template string {val!conv:spec}. The spec is
applied as a format string itself, but if the value is None, the result
will be empty. The purpose of this is to allow optional parts in a
prompt string. For example, if the prompt contains ... |
Return the compact current working directory. It respects the
environment variable DYNAMIC_CWD_WIDTH. | def _dynamically_collapsed_pwd():
"""Return the compact current working directory. It respects the
environment variable DYNAMIC_CWD_WIDTH.
"""
original_path = _replace_home_cwd()
target_width, units = XSH.env["DYNAMIC_CWD_WIDTH"]
elision_char = XSH.env["DYNAMIC_CWD_ELISION_CHAR"]
if target_... |
Find current environment name from available sources.
If ``$VIRTUAL_ENV`` is set, it is determined from the prompt setting in
``<venv>/pyvenv.cfg`` or from the folder name of the environment.
Otherwise - if it is set - from ``$CONDA_DEFAULT_ENV``. | def find_env_name() -> Optional[str]:
"""Find current environment name from available sources.
If ``$VIRTUAL_ENV`` is set, it is determined from the prompt setting in
``<venv>/pyvenv.cfg`` or from the folder name of the environment.
Otherwise - if it is set - from ``$CONDA_DEFAULT_ENV``.
"""
v... |
Build env_name based on different sources. Respect order of precedence.
Name from VIRTUAL_ENV_PROMPT will be used as-is.
Names from other sources are surrounded with ``{env_prefix}`` and
``{env_postfix}`` fields. | def env_name() -> str:
"""Build env_name based on different sources. Respect order of precedence.
Name from VIRTUAL_ENV_PROMPT will be used as-is.
Names from other sources are surrounded with ``{env_prefix}`` and
``{env_postfix}`` fields.
"""
if XSH.env.get("VIRTUAL_ENV_DISABLE_PROMPT"):
... |
Use prompt setting from pyvenv.cfg or basename of virtual_env.
Tries to be resilient to subtle changes in whitespace and quoting in the
configuration file format as it adheres to no clear standard. | def _determine_env_name(virtual_env: str) -> str:
"""Use prompt setting from pyvenv.cfg or basename of virtual_env.
Tries to be resilient to subtle changes in whitespace and quoting in the
configuration file format as it adheres to no clear standard.
"""
venv_path = Path(virtual_env)
pyvenv_cfg... |
This prints an escape sequence that tells VTE terminals the hostname
and pwd. This should not be needed in most cases, but sometimes is for
certain Linux terminals that do not read the PWD from the environment
on startup. Note that this does not return a string, it simply prints
and flushes the escape sequence to stdou... | def vte_new_tab_cwd() -> None:
"""This prints an escape sequence that tells VTE terminals the hostname
and pwd. This should not be needed in most cases, but sometimes is for
certain Linux terminals that do not read the PWD from the environment
on startup. Note that this does not return a string, it simp... |
Get git-stash count | def get_stash_count(gitdir: str):
"""Get git-stash count"""
with contextlib.suppress(OSError):
with open(os.path.join(gitdir, "logs/refs/stash")) as f:
return sum(1 for _ in f)
return 0 |
get the current git operation e.g. MERGE/REBASE... | def get_operations(gitdir: str):
"""get the current git operation e.g. MERGE/REBASE..."""
for file, name in (
("rebase-merge", "REBASE"),
("rebase-apply", "AM/REBASE"),
("MERGE_HEAD", "MERGING"),
("CHERRY_PICK_HEAD", "CHERRY-PICKING"),
("REVERT_HEAD", "REVERTING"),
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.