response
stringlengths 1
33.1k
| instruction
stringlengths 22
582k
|
---|---|
Expand shell variables of the forms $var, ${var} and %var%.
Unknown variables are left unchanged. | def expandvars(path):
"""Expand shell variables of the forms $var, ${var} and %var%.
Unknown variables are left unchanged."""
env = xsh.env
if isinstance(path, bytes):
path = path.decode(
encoding=env.get("XONSH_ENCODING"), errors=env.get("XONSH_ENCODING_ERRORS")
)
elif isinstance(path, pathlib.Path):
# get the path's string representation
path = str(path)
if "$" in path:
shift = 0
for match in POSIX_ENVVAR_REGEX.finditer(path):
name = match.group("envvar")
if name in env:
detyper = env.get_detyper(name)
val = env[name]
value = str(val) if detyper is None else detyper(val)
value = str(val) if value is None else value
start_pos, end_pos = match.span()
path_len_before_replace = len(path)
path = path[: start_pos + shift] + value + path[end_pos + shift :]
shift = shift + len(path) - path_len_before_replace
return path |
Moves an existing file to a new name that has the current time right
before the extension. | def backup_file(fname):
"""Moves an existing file to a new name that has the current time right
before the extension.
"""
# lazy imports
import shutil
from datetime import datetime
base, ext = os.path.splitext(fname)
timestamp = datetime.now().strftime("%Y-%m-%d-%H-%M-%S-%f")
newfname = f"{base}.{timestamp}{ext}"
shutil.move(fname, newfname) |
Returns as normalized absolute path, namely, normcase(abspath(p)) | def normabspath(p):
"""Returns as normalized absolute path, namely, normcase(abspath(p))"""
return os.path.normcase(os.path.abspath(p)) |
Provides user expanded absolute path | def expanduser_abs_path(inp):
"""Provides user expanded absolute path"""
return os.path.abspath(expanduser(inp)) |
Expands a string to a case insensitive globable string. | def expand_case_matching(s):
"""Expands a string to a case insensitive globable string."""
t = []
openers = {"[", "{"}
closers = {"]", "}"}
nesting = 0
drive_part = WINDOWS_DRIVE_MATCHER.match(s) if ON_WINDOWS else None
if drive_part:
drive_part = drive_part.group(0)
t.append(drive_part)
s = s[len(drive_part) :]
for c in s:
if c in openers:
nesting += 1
elif c in closers:
nesting -= 1
elif nesting > 0:
pass
elif c.isalpha():
folded = c.casefold()
if len(folded) == 1:
c = f"[{c.upper()}{c.lower()}]"
else:
newc = [f"[{f.upper()}{f.lower()}]?" for f in folded[:-1]]
newc = "".join(newc)
newc += f"[{folded[-1].upper()}{folded[-1].lower()}{c}]"
c = newc
t.append(c)
return "".join(t) |
Simple wrapper around glob that also expands home and env vars. | def globpath(
s, ignore_case=False, return_empty=False, sort_result=None, include_dotfiles=None
):
"""Simple wrapper around glob that also expands home and env vars."""
o, s = _iglobpath(
s,
ignore_case=ignore_case,
sort_result=sort_result,
include_dotfiles=include_dotfiles,
)
o = list(o)
no_match = [] if return_empty else [s]
return o if len(o) != 0 else no_match |
Simple wrapper around iglob that also expands home and env vars. | def iglobpath(s, ignore_case=False, sort_result=None, include_dotfiles=None):
"""Simple wrapper around iglob that also expands home and env vars."""
try:
return _iglobpath(
s,
ignore_case=ignore_case,
sort_result=sort_result,
include_dotfiles=include_dotfiles,
)[0]
except IndexError:
# something went wrong in the actual iglob() call
return iter(()) |
Format datetime object to string base on $XONSH_DATETIME_FORMAT Env. | def format_datetime(dt):
"""Format datetime object to string base on $XONSH_DATETIME_FORMAT Env."""
format_ = xsh.env["XONSH_DATETIME_FORMAT"]
return dt.strftime(format_) |
Takes an iterable of strings and returns a list of lines with the
elements placed in columns. Each line will be at most *width* columns.
The newline character will be appended to the end of each line. | def columnize(elems, width=80, newline="\n"):
"""Takes an iterable of strings and returns a list of lines with the
elements placed in columns. Each line will be at most *width* columns.
The newline character will be appended to the end of each line.
"""
sizes = [len(e) + 1 for e in elems]
total = sum(sizes)
nelem = len(elems)
if total - 1 <= width:
ncols = len(sizes)
nrows = 1
columns = [sizes]
last_longest_row = total
enter_loop = False
else:
ncols = 1
nrows = len(sizes)
columns = [sizes]
last_longest_row = max(sizes)
enter_loop = True
while enter_loop:
longest_row = sum(map(max, columns))
if longest_row - 1 <= width:
# we might be able to fit another column.
ncols += 1
nrows = nelem // ncols
columns = [sizes[i * nrows : (i + 1) * nrows] for i in range(ncols)]
last_longest_row = longest_row
else:
# we can't fit another column
ncols -= 1
nrows = nelem // ncols
break
pad = (width - last_longest_row + ncols) // ncols
pad = pad if pad > 1 else 1
data = [elems[i * nrows : (i + 1) * nrows] for i in range(ncols)]
colwidths = [max(map(len, d)) + pad for d in data]
colwidths[-1] -= pad
row_t = "".join([f"{{row[{i}]: <{{w[{i}]}}}}" for i in range(ncols)])
row_t += newline
lines = [
row_t.format(row=row, w=colwidths)
for row in itertools.zip_longest(*data, fillvalue="")
]
return lines |
Decorator that specifies that a callable alias should be run only
on the main thread process. This is often needed for debuggers and
profilers. | def unthreadable(f):
"""Decorator that specifies that a callable alias should be run only
on the main thread process. This is often needed for debuggers and
profilers.
"""
f.__xonsh_threadable__ = False
return f |
Decorator that specifies that a callable alias should not be run with
any capturing. This is often needed if the alias call interactive
subprocess, like pagers and text editors. | def uncapturable(f):
"""Decorator that specifies that a callable alias should not be run with
any capturing. This is often needed if the alias call interactive
subprocess, like pagers and text editors.
"""
f.__xonsh_capturable__ = False
return f |
Writes a carriage return to stdout, and nothing else. | def carriage_return():
"""Writes a carriage return to stdout, and nothing else."""
print("\r", flush=True, end="") |
Parametrized decorator that deprecates a function in a graceful manner.
Updates the decorated function's docstring to mention the version
that deprecation occurred in and the version it will be removed
in if both of these values are passed.
When removed_in is not a release equal to or less than the current
release, call ``warnings.warn`` with details, while raising
``DeprecationWarning``.
When removed_in is a release equal to or less than the current release,
raise an ``AssertionError``.
Parameters
----------
deprecated_in : str
The version number that deprecated this function.
removed_in : str
The version number that this function will be removed in. | def deprecated(deprecated_in=None, removed_in=None):
"""Parametrized decorator that deprecates a function in a graceful manner.
Updates the decorated function's docstring to mention the version
that deprecation occurred in and the version it will be removed
in if both of these values are passed.
When removed_in is not a release equal to or less than the current
release, call ``warnings.warn`` with details, while raising
``DeprecationWarning``.
When removed_in is a release equal to or less than the current release,
raise an ``AssertionError``.
Parameters
----------
deprecated_in : str
The version number that deprecated this function.
removed_in : str
The version number that this function will be removed in.
"""
message_suffix = _deprecated_message_suffix(deprecated_in, removed_in)
if not message_suffix:
message_suffix = ""
def decorated(func):
warning_message = f"{func.__name__} has been deprecated"
warning_message += message_suffix
@functools.wraps(func)
def wrapped(*args, **kwargs):
_deprecated_error_on_expiration(func.__name__, removed_in)
func(*args, **kwargs)
warnings.warn(warning_message, DeprecationWarning, stacklevel=2)
wrapped.__doc__ = (
f"{wrapped.__doc__}\n\n{warning_message}"
if wrapped.__doc__
else warning_message
)
return wrapped
return decorated |
Formats a trace line suitable for printing. | def tracer_format_line(fname, lineno, line, color=True, lexer=None, formatter=None):
"""Formats a trace line suitable for printing."""
fname = min(fname, prompt._replace_home(fname), os.path.relpath(fname), key=len)
if not color:
return COLORLESS_LINE.format(fname=fname, lineno=lineno, line=line)
cline = COLOR_LINE.format(fname=fname, lineno=lineno)
if not HAS_PYGMENTS:
return cline + line
# OK, so we have pygments
tokens = pyghooks.partial_color_tokenize(cline)
lexer = lexer or pyghooks.XonshLexer()
tokens += pygments.lex(line, lexer=lexer)
if tokens[-1][1] == "\n":
del tokens[-1]
elif tokens[-1][1].endswith("\n"):
tokens[-1] = (tokens[-1][0], tokens[-1][1].rstrip())
return tokens |
Somewhat hacky method of finding the __file__ based on the line executed. | def _find_caller(args):
"""Somewhat hacky method of finding the __file__ based on the line executed."""
re_line = re.compile(r"[^;\s|&<>]+\s+" + r"\s+".join(args))
curr = inspect.currentframe()
for _, fname, lineno, _, lines, _ in inspect.getouterframes(curr, context=1)[3:]:
if lines is not None and re_line.search(lines[0]) is not None:
return fname
elif (
lineno == 1 and re_line.search(linecache.getline(fname, lineno)) is not None
):
# There is a bug in CPython such that getouterframes(curr, context=1)
# will actually return the 2nd line in the code_context field, even though
# line number is itself correct. We manually fix that in this branch.
return fname
else:
msg = (
"xonsh: warning: __file__ name could not be found. You may be "
"trying to trace interactively. Please pass in the file names "
"you want to trace explicitly."
)
print(msg, file=sys.stderr) |
Waits till spawned process finishes and closes the handle for it
Parameters
----------
process_handle : HANDLE
The Windows handle for the process | def wait_and_close_handle(process_handle):
"""
Waits till spawned process finishes and closes the handle for it
Parameters
----------
process_handle : HANDLE
The Windows handle for the process
"""
WaitForSingleObject(process_handle, INFINITE)
CloseHandle(process_handle) |
This will re-run current Python script requesting to elevate administrative rights.
Parameters
----------
executable : str
The path/name of the executable
args : list of str
The arguments to be passed to the executable | def sudo(executable, args=None):
"""
This will re-run current Python script requesting to elevate administrative rights.
Parameters
----------
executable : str
The path/name of the executable
args : list of str
The arguments to be passed to the executable
"""
if not args:
args = []
execute_info = ShellExecuteInfo(
fMask=SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NO_CONSOLE,
hwnd=GetActiveWindow(),
lpVerb=b"runas",
lpFile=executable.encode("utf-8"),
lpParameters=subprocess.list2cmdline(args).encode("utf-8"),
lpDirectory=None,
nShow=SW_SHOW,
)
if not ShellExecuteEx(byref(execute_info)):
raise ctypes.WinError()
wait_and_close_handle(execute_info.hProcess) |
Tuple of the Windows handles for (stdin, stdout, stderr). | def STDHANDLES():
"""Tuple of the Windows handles for (stdin, stdout, stderr)."""
hs = [
lazyimps._winapi.STD_INPUT_HANDLE,
lazyimps._winapi.STD_OUTPUT_HANDLE,
lazyimps._winapi.STD_ERROR_HANDLE,
]
hcons = []
for h in hs:
hcon = GetStdHandle(int(h))
hcons.append(hcon)
return tuple(hcons) |
Get the mode of the active console input, output, or error
buffer. Note that if the process isn't attached to a
console, this function raises an EBADF IOError.
Parameters
----------
fd : int
Standard buffer file descriptor, 0 for stdin, 1 for stdout (default),
and 2 for stderr | def get_console_mode(fd=1):
"""Get the mode of the active console input, output, or error
buffer. Note that if the process isn't attached to a
console, this function raises an EBADF IOError.
Parameters
----------
fd : int
Standard buffer file descriptor, 0 for stdin, 1 for stdout (default),
and 2 for stderr
"""
mode = DWORD()
hcon = STDHANDLES[fd]
GetConsoleMode(hcon, byref(mode))
return mode.value |
Set the mode of the active console input, output, or
error buffer. Note that if the process isn't attached to a
console, this function raises an EBADF IOError.
Parameters
----------
mode : int
Mode flags to set on the handle.
fd : int, optional
Standard buffer file descriptor, 0 for stdin, 1 for stdout (default),
and 2 for stderr | def set_console_mode(mode, fd=1):
"""Set the mode of the active console input, output, or
error buffer. Note that if the process isn't attached to a
console, this function raises an EBADF IOError.
Parameters
----------
mode : int
Mode flags to set on the handle.
fd : int, optional
Standard buffer file descriptor, 0 for stdin, 1 for stdout (default),
and 2 for stderr
"""
hcon = STDHANDLES[fd]
SetConsoleMode(hcon, mode) |
Enables virtual terminal processing on Windows.
This includes ANSI escape sequence interpretation.
See http://stackoverflow.com/a/36760881/2312428 | def enable_virtual_terminal_processing():
"""Enables virtual terminal processing on Windows.
This includes ANSI escape sequence interpretation.
See http://stackoverflow.com/a/36760881/2312428
"""
SetConsoleMode(GetStdHandle(-11), 7) |
Reads characters from the console buffer.
Parameters
----------
x : int, optional
Starting column.
y : int, optional
Starting row.
fd : int, optional
Standard buffer file descriptor, 0 for stdin, 1 for stdout (default),
and 2 for stderr.
buf : ctypes.c_wchar_p if raw else ctypes.c_wchar_p, optional
An existing buffer to (re-)use.
bufsize : int, optional
The maximum read size.
raw : bool, optional
Whether to read in and return as bytes (True) or as a
unicode string (False, default).
Returns
-------
value : str
Result of what was read, may be shorter than bufsize. | def read_console_output_character(x=0, y=0, fd=1, buf=None, bufsize=1024, raw=False):
"""Reads characters from the console buffer.
Parameters
----------
x : int, optional
Starting column.
y : int, optional
Starting row.
fd : int, optional
Standard buffer file descriptor, 0 for stdin, 1 for stdout (default),
and 2 for stderr.
buf : ctypes.c_wchar_p if raw else ctypes.c_wchar_p, optional
An existing buffer to (re-)use.
bufsize : int, optional
The maximum read size.
raw : bool, optional
Whether to read in and return as bytes (True) or as a
unicode string (False, default).
Returns
-------
value : str
Result of what was read, may be shorter than bufsize.
"""
hcon = STDHANDLES[fd]
if buf is None:
if raw:
buf = ctypes.c_char_p(b" " * bufsize)
else:
buf = ctypes.c_wchar_p(" " * bufsize)
coord = COORD(x, y)
n = DWORD()
if raw:
ReadConsoleOutputCharacterA(hcon, buf, bufsize, coord, byref(n))
else:
ReadConsoleOutputCharacterW(hcon, buf, bufsize, coord, byref(n))
return buf.value[: n.value] |
This is a console-based implementation of os.pread() for windows.
that uses read_console_output_character(). | def pread_console(fd, buffersize, offset, buf=None):
"""This is a console-based implementation of os.pread() for windows.
that uses read_console_output_character().
"""
cols, rows = os.get_terminal_size(fd=fd)
x = offset % cols
y = offset // cols
return read_console_output_character(
x=x, y=y, fd=fd, buf=buf, bufsize=buffersize, raw=True
) |
Returns the windows version of the get screen buffer. | def GetConsoleScreenBufferInfo():
"""Returns the windows version of the get screen buffer."""
gcsbi = ctypes.windll.kernel32.GetConsoleScreenBufferInfo
gcsbi.errcheck = check_zero
gcsbi.argtypes = (HANDLE, POINTER(CONSOLE_SCREEN_BUFFER_INFO))
gcsbi.restype = BOOL
return gcsbi |
Returns an screen buffer info object for the relevant stdbuf.
Parameters
----------
fd : int, optional
Standard buffer file descriptor, 0 for stdin, 1 for stdout (default),
and 2 for stderr.
Returns
-------
csbi : CONSOLE_SCREEN_BUFFER_INFO
Information about the console screen buffer. | def get_console_screen_buffer_info(fd=1):
"""Returns an screen buffer info object for the relevant stdbuf.
Parameters
----------
fd : int, optional
Standard buffer file descriptor, 0 for stdin, 1 for stdout (default),
and 2 for stderr.
Returns
-------
csbi : CONSOLE_SCREEN_BUFFER_INFO
Information about the console screen buffer.
"""
hcon = STDHANDLES[fd]
csbi = CONSOLE_SCREEN_BUFFER_INFO()
GetConsoleScreenBufferInfo(hcon, byref(csbi))
return csbi |
Gets the current cursor position as an (x, y) tuple. | def get_cursor_position(fd=1):
"""Gets the current cursor position as an (x, y) tuple."""
csbi = get_console_screen_buffer_info(fd=fd)
coord = csbi.dwCursorPosition
return (coord.X, coord.Y) |
Gets the current cursor position as a total offset value. | def get_cursor_offset(fd=1):
"""Gets the current cursor position as a total offset value."""
csbi = get_console_screen_buffer_info(fd=fd)
pos = csbi.dwCursorPosition
size = csbi.dwSize
return (pos.Y * size.X) + pos.X |
Gets the current cursor position and screen size tuple:
(x, y, columns, lines). | def get_position_size(fd=1):
"""Gets the current cursor position and screen size tuple:
(x, y, columns, lines).
"""
info = get_console_screen_buffer_info(fd)
return (
info.dwCursorPosition.X,
info.dwCursorPosition.Y,
info.dwSize.X,
info.dwSize.Y,
) |
Set screen buffer dimensions. | def SetConsoleScreenBufferSize():
"""Set screen buffer dimensions."""
scsbs = ctypes.windll.kernel32.SetConsoleScreenBufferSize
scsbs.errcheck = check_zero
scsbs.argtypes = (HANDLE, COORD) # _In_ HANDLE hConsoleOutput # _In_ COORD dwSize
scsbs.restype = BOOL
return scsbs |
Sets the console size for a standard buffer.
Parameters
----------
x : int
Number of columns.
y : int
Number of rows.
fd : int, optional
Standard buffer file descriptor, 0 for stdin, 1 for stdout (default),
and 2 for stderr. | def set_console_screen_buffer_size(x, y, fd=1):
"""Sets the console size for a standard buffer.
Parameters
----------
x : int
Number of columns.
y : int
Number of rows.
fd : int, optional
Standard buffer file descriptor, 0 for stdin, 1 for stdout (default),
and 2 for stderr.
"""
coord = COORD()
coord.X = x
coord.Y = y
hcon = STDHANDLES[fd]
rtn = SetConsoleScreenBufferSize(hcon, coord)
return rtn |
Set cursor position in console. | def SetConsoleCursorPosition():
"""Set cursor position in console."""
sccp = ctypes.windll.kernel32.SetConsoleCursorPosition
sccp.errcheck = check_zero
sccp.argtypes = (
HANDLE, # _In_ HANDLE hConsoleOutput
COORD, # _In_ COORD dwCursorPosition
)
sccp.restype = BOOL
return sccp |
Sets the console cursor position for a standard buffer.
Parameters
----------
x : int
Number of columns.
y : int
Number of rows.
fd : int, optional
Standard buffer file descriptor, 0 for stdin, 1 for stdout (default),
and 2 for stderr. | def set_console_cursor_position(x, y, fd=1):
"""Sets the console cursor position for a standard buffer.
Parameters
----------
x : int
Number of columns.
y : int
Number of rows.
fd : int, optional
Standard buffer file descriptor, 0 for stdin, 1 for stdout (default),
and 2 for stderr.
"""
coord = COORD()
coord.X = x
coord.Y = y
hcon = STDHANDLES[fd]
rtn = SetConsoleCursorPosition(hcon, coord)
return rtn |
This creates a basic condition function for use with nodes like While
or other conditions. The condition function creates and visits a TrueFalse
node and returns the result. This TrueFalse node takes the prompt and
path that is passed in here. | def create_truefalse_cond(prompt="yes or no [default: no]? ", path=None):
"""This creates a basic condition function for use with nodes like While
or other conditions. The condition function creates and visits a TrueFalse
node and returns the result. This TrueFalse node takes the prompt and
path that is passed in here.
"""
def truefalse_cond(visitor, node=None):
"""Prompts the user for a true/false condition."""
tf = TrueFalse(prompt=prompt, path=path)
rtn = visitor.visit(tf)
return rtn
return truefalse_cond |
Creates a string or int. | def ensure_str_or_int(x):
"""Creates a string or int."""
if isinstance(x, int):
return x
x = x if isinstance(x, str) else str(x)
try:
x = ast.literal_eval(x)
except (ValueError, SyntaxError):
pass
if not isinstance(x, (int, str)):
msg = f"{x!r} could not be converted to int or str"
raise ValueError(msg)
return x |
Returns the canonical form of a path, which is a tuple of str or ints.
Indices may be optionally passed in. | def canon_path(path, indices=None):
"""Returns the canonical form of a path, which is a tuple of str or ints.
Indices may be optionally passed in.
"""
if not isinstance(path, str):
return tuple(map(ensure_str_or_int, path))
if indices is not None:
path = path.format(**indices)
path = path[1:] if path.startswith("/") else path
path = path[:-1] if path.endswith("/") else path
if len(path) == 0:
return ()
return tuple(map(ensure_str_or_int, path.split("/"))) |
Makes the foreign shell part of the wizard. | def make_fs_wiz():
"""Makes the foreign shell part of the wizard."""
cond = wiz.create_truefalse_cond(prompt="Add a new foreign shell, " + wiz.YN)
fs = wiz.While(
cond=cond,
body=[
wiz.Input("shell name (e.g. bash): ", path="/foreign_shells/{idx}/shell"),
wiz.StoreNonEmpty(
"interactive shell [bool, default=True]: ",
converter=to_bool,
show_conversion=True,
path="/foreign_shells/{idx}/interactive",
),
wiz.StoreNonEmpty(
"login shell [bool, default=False]: ",
converter=to_bool,
show_conversion=True,
path="/foreign_shells/{idx}/login",
),
wiz.StoreNonEmpty(
"env command [str, default='env']: ",
path="/foreign_shells/{idx}/envcmd",
),
wiz.StoreNonEmpty(
"alias command [str, default='alias']: ",
path="/foreign_shells/{idx}/aliascmd",
),
wiz.StoreNonEmpty(
("extra command line arguments [list of str, " "default=[]]: "),
converter=ast.literal_eval,
show_conversion=True,
path="/foreign_shells/{idx}/extra_args",
),
wiz.StoreNonEmpty(
"safely handle exceptions [bool, default=True]: ",
converter=to_bool,
show_conversion=True,
path="/foreign_shells/{idx}/safe",
),
wiz.StoreNonEmpty(
"pre-command [str, default='']: ", path="/foreign_shells/{idx}/prevcmd"
),
wiz.StoreNonEmpty(
"post-command [str, default='']: ", path="/foreign_shells/{idx}/postcmd"
),
wiz.StoreNonEmpty(
"foreign function command [str, default=None]: ",
path="/foreign_shells/{idx}/funcscmd",
),
wiz.StoreNonEmpty(
"source command [str, default=None]: ",
path="/foreign_shells/{idx}/sourcer",
),
wiz.Message(message="Foreign shell added.\n"),
],
)
return fs |
Wraps paragraphs instead. | def _wrap_paragraphs(text, width=70, **kwargs):
"""Wraps paragraphs instead."""
pars = text.split("\n")
pars = ["\n".join(textwrap.wrap(p, width=width, **kwargs)) for p in pars]
s = "\n".join(pars)
return s |
Creates a message for how to exit the wizard. | def make_exit_message():
"""Creates a message for how to exit the wizard."""
shell_type = XSH.shell.shell_type
keyseq = "Ctrl-D" if shell_type == "readline" else "Ctrl-C"
msg = "To exit the wizard at any time, press {BOLD_UNDERLINE_CYAN}"
msg += keyseq + "{RESET}.\n"
m = wiz.Message(message=msg)
return m |
Makes a StoreNonEmpty node for an environment variable. | def make_envvar(name):
"""Makes a StoreNonEmpty node for an environment variable."""
env = XSH.env
vd = env.get_docs(name)
if not vd.is_configurable:
return
default = vd.doc_default
if "\n" in default:
default = "\n" + _wrap_paragraphs(default, width=69)
curr = env.get(name)
if is_string(curr) and is_template_string(curr):
curr = curr.replace("{", "{{").replace("}", "}}")
curr = pprint.pformat(curr, width=69)
if "\n" in curr:
curr = "\n" + curr
msg = ENVVAR_MESSAGE.format(
name=name,
default=default,
current=curr,
docstr=_wrap_paragraphs(vd.doc, width=69),
)
mnode = wiz.Message(message=msg)
converter = env.get_converter(name)
path = "/env/" + name
pnode = wiz.StoreNonEmpty(
ENVVAR_PROMPT,
converter=converter,
show_conversion=True,
path=path,
retry=True,
store_raw=vd.can_store_as_str,
)
return mnode, pnode |
Makes an environment variable wizard. | def make_env_wiz():
"""Makes an environment variable wizard."""
w = _make_flat_wiz(make_envvar, sorted(XSH.env.keys()))
return w |
Makes a message and StoreNonEmpty node for a xontrib. | def make_xontrib(xon_item: tuple[str, Xontrib]):
"""Makes a message and StoreNonEmpty node for a xontrib."""
name, xontrib = xon_item
name = name or "<unknown-xontrib-name>"
msg = "\n{BOLD_CYAN}" + name + "{RESET}\n"
if xontrib.url:
msg += "{RED}url:{RESET} " + xontrib.url + "\n"
if xontrib.distribution:
msg += "{RED}package:{RESET} " + xontrib.distribution.name + "\n"
if xontrib.license:
msg += "{RED}license:{RESET} " + xontrib.license + "\n"
msg += "{PURPLE}installed?{RESET} "
msg += ("no" if find_xontrib(name) is None else "yes") + "\n"
msg += _wrap_paragraphs(xontrib.get_description(), width=69)
if msg.endswith("\n"):
msg = msg[:-1]
mnode = wiz.Message(message=msg)
convert = lambda x: name if to_bool(x) else wiz.Unstorable
pnode = wiz.StoreNonEmpty(XONTRIB_PROMPT, converter=convert, path=_xontrib_path)
return mnode, pnode |
Makes a xontrib wizard. | def make_xontribs_wiz():
"""Makes a xontrib wizard."""
return _make_flat_wiz(make_xontrib, get_xontribs().items()) |
Makes a configuration wizard for xonsh config file.
Parameters
----------
default_file : str, optional
Default filename to save and load to. User will still be prompted.
confirm : bool, optional
Confirm that the main part of the wizard should be run.
no_wizard_file : str, optional
Filename for that will flag to future runs that the wizard should not be
run again. If None (default), this defaults to default_file. | def make_xonfig_wizard(default_file=None, confirm=False, no_wizard_file=None):
"""Makes a configuration wizard for xonsh config file.
Parameters
----------
default_file : str, optional
Default filename to save and load to. User will still be prompted.
confirm : bool, optional
Confirm that the main part of the wizard should be run.
no_wizard_file : str, optional
Filename for that will flag to future runs that the wizard should not be
run again. If None (default), this defaults to default_file.
"""
w = wiz.Wizard(
children=[
wiz.Message(message=WIZARD_HEAD),
make_exit_message(),
wiz.Message(message=WIZARD_FS),
make_fs_wiz(),
wiz.Message(message=WIZARD_ENV),
wiz.YesNo(question=WIZARD_ENV_QUESTION, yes=make_env_wiz(), no=wiz.Pass()),
wiz.Message(message=WIZARD_XONTRIB),
wiz.YesNo(
question=WIZARD_XONTRIB_QUESTION, yes=make_xontribs_wiz(), no=wiz.Pass()
),
wiz.Message(message="\n" + HR + "\n"),
wiz.FileInserter(
prefix="# XONSH WIZARD START",
suffix="# XONSH WIZARD END",
dump_rules=XONFIG_DUMP_RULES,
default_file=default_file,
check=True,
),
wiz.Message(message=WIZARD_TAIL),
]
)
if confirm:
q = (
"Would you like to run the xonsh configuration wizard now?\n\n"
"1. Yes (You can abort at any time)\n"
"2. No, but ask me next time.\n"
"3. No, and don't ask me again.\n\n"
"1, 2, or 3 [default: 2]? "
)
no_wizard_file = default_file if no_wizard_file is None else no_wizard_file
passer = wiz.Pass()
saver = wiz.SaveJSON(
check=False, ask_filename=False, default_file=no_wizard_file
)
w = wiz.Question(
q, {1: w, 2: passer, 3: saver}, converter=lambda x: int(x) if x != "" else 2
)
return w |
Launch configurator in terminal
Parameters
-------
rcfile : -f, --file
config file location, default=$XONSHRC
confirm : -c, --confirm
confirm that the wizard should be run. | def _wizard(
rcfile=None,
confirm=False,
):
"""Launch configurator in terminal
Parameters
-------
rcfile : -f, --file
config file location, default=$XONSHRC
confirm : -c, --confirm
confirm that the wizard should be run.
"""
env = XSH.env
shell = XSH.shell.shell
xonshrcs = env.get("XONSHRC", [])
fname = xonshrcs[-1] if xonshrcs and rcfile is None else rcfile
no_wiz = os.path.join(env.get("XONSH_CONFIG_DIR"), "no-wizard")
w = make_xonfig_wizard(default_file=fname, confirm=confirm, no_wizard_file=no_wiz)
tempenv = {"PROMPT": "", "XONSH_STORE_STDOUT": False}
pv = wiz.PromptVisitor(w, store_in_history=False, multiline=False)
@contextlib.contextmanager
def force_hide():
if env.get("XONSH_STORE_STDOUT") and hasattr(shell, "_force_hide"):
orig, shell._force_hide = shell._force_hide, False
yield
shell._force_hide = orig
else:
yield
with force_hide(), env.swap(tempenv):
try:
pv.visit()
except (KeyboardInterrupt, Exception):
print()
print_exception() |
Displays configuration information
Parameters
----------
to_json : -j, --json
reports results as json | def _info(
to_json=False,
) -> str:
"""Displays configuration information
Parameters
----------
to_json : -j, --json
reports results as json
"""
env = XSH.env
data: list[tp.Any] = [("xonsh", XONSH_VERSION)]
hash_, date_ = githash()
if hash_:
data.append(("Git SHA", hash_))
data.append(("Commit Date", date_))
data.extend(
[
("Python", "{}.{}.{}".format(*PYTHON_VERSION_INFO)),
("PLY", ply.__version__),
("have readline", is_readline_available()),
("prompt toolkit", ptk_version() or None),
("shell type", env.get("SHELL_TYPE")),
("history backend", env.get("XONSH_HISTORY_BACKEND")),
("pygments", pygments_version()),
("on posix", bool(ON_POSIX)),
("on linux", bool(ON_LINUX)),
]
)
if ON_LINUX:
data.append(("distro", linux_distro()))
data.append(("on wsl", bool(ON_WSL)))
if ON_WSL:
data.append(("wsl version", 1 if ON_WSL1 else 2))
data.extend(
[
("on darwin", bool(ON_DARWIN)),
("on windows", bool(ON_WINDOWS)),
("on cygwin", bool(ON_CYGWIN)),
("on msys2", bool(ON_MSYS)),
("is superuser", is_superuser()),
("default encoding", DEFAULT_ENCODING),
("xonsh encoding", env.get("XONSH_ENCODING")),
("encoding errors", env.get("XONSH_ENCODING_ERRORS")),
]
)
for p in XSH.builtins.events.on_xonfig_info_requested.fire():
if p is not None:
data.extend(p)
data.extend([("xontrib", xontribs_loaded())])
data.extend([("RC file", XSH.rc_files)])
formatter = _xonfig_format_json if to_json else _xonfig_format_human
s = formatter(data)
return s |
Prints available xonsh color styles
Parameters
----------
to_json: -j, --json
reports results as json | def _styles(to_json=False, _stdout=None):
"""Prints available xonsh color styles
Parameters
----------
to_json: -j, --json
reports results as json
"""
env = XSH.env
curr = env.get("XONSH_COLOR_STYLE")
styles = sorted(color_style_names())
if to_json:
s = json.dumps(styles, sort_keys=True, indent=1)
print(s)
return
lines = []
for style in styles:
if style == curr:
lines.append("* {GREEN}" + style + "{RESET}")
else:
lines.append(" " + style)
s = "\n".join(lines)
print_color(s, file=_stdout) |
Preview color style
Parameters
----------
style
name of the style to preview. If not given, current style name is used. | def _colors(
style: tp.Annotated[str, Arg(nargs="?", completer=xonfig_color_completer)] = None,
):
"""Preview color style
Parameters
----------
style
name of the style to preview. If not given, current style name is used.
"""
columns, _ = shutil.get_terminal_size()
columns -= int(bool(ON_WINDOWS))
style_stash = XSH.env["XONSH_COLOR_STYLE"]
if style is not None:
if style not in color_style_names():
print(f"Invalid style: {style}")
return
XSH.env["XONSH_COLOR_STYLE"] = style
color_map = color_style()
if not color_map:
print("Empty color map - using non-interactive shell?")
return
akey = next(iter(color_map))
if isinstance(akey, str):
s = _str_colors(color_map, columns)
else:
s = _tok_colors(color_map, columns)
print_color(s)
XSH.env["XONSH_COLOR_STYLE"] = style_stash |
Launch tutorial in browser. | def _tutorial():
"""Launch tutorial in browser."""
import webbrowser
webbrowser.open("http://xon.sh/tutorial.html") |
Launch configurator in browser.
Parameters
----------
browser : --nb, --no-browser, -n
don't open browser | def _web(
_args,
browser=True,
):
"""Launch configurator in browser.
Parameters
----------
browser : --nb, --no-browser, -n
don't open browser
"""
from xonsh.webconfig import main
main.serve(browser) |
Align and pad a color formatted string | def _align_string(string, align="<", fill=" ", width=80):
"""Align and pad a color formatted string"""
linelen = len(STRIP_COLOR_RE.sub("", string))
padlen = max(width - linelen, 0)
if align == "^":
return fill * (padlen // 2) + string + fill * (padlen // 2 + padlen % 2)
elif align == ">":
return fill * padlen + string
elif align == "<":
return string + fill * padlen
else:
return string |
Find the module and return its docstring without actual import | def get_module_docstring(module: str) -> str:
"""Find the module and return its docstring without actual import"""
import ast
spec = importlib.util.find_spec(module)
if spec and spec.has_location and spec.origin:
return ast.get_docstring(ast.parse(Path(spec.origin).read_text())) or ""
return "" |
Return xontrib definitions lazily. | def get_xontribs() -> dict[str, Xontrib]:
"""Return xontrib definitions lazily."""
return dict(_get_installed_xontribs()) |
Patch in user site packages directory.
If xonsh is installed in non-writeable location, then xontribs will end up
there, so we make them accessible. | def _patch_in_userdir():
"""
Patch in user site packages directory.
If xonsh is installed in non-writeable location, then xontribs will end up
there, so we make them accessible."""
if not os.access(os.path.dirname(sys.executable), os.W_OK):
from site import getusersitepackages
if (user_site_packages := getusersitepackages()) not in set(sys.path):
sys.path.append(user_site_packages) |
List all core packages + newly installed xontribs | def _get_installed_xontribs(pkg_name="xontrib"):
"""List all core packages + newly installed xontribs"""
_patch_in_userdir()
spec = importlib.util.find_spec(pkg_name)
def iter_paths():
for loc in spec.submodule_search_locations:
path = Path(loc)
if path.exists():
yield from path.iterdir()
def iter_modules():
# pkgutil is not finding `*.xsh` files
for path in iter_paths():
if path.suffix in {".py", ".xsh"}:
yield path.stem
elif path.is_dir():
if (path / "__init__.py").exists():
yield path.name
for name in iter_modules():
module = f"xontrib.{name}"
yield name, Xontrib(module)
for entry in _get_xontrib_entrypoints():
yield entry.name, Xontrib(entry.value, distribution=entry.dist) |
Finds a xontribution from its name. | def find_xontrib(name, full_module=False):
"""Finds a xontribution from its name."""
_patch_in_userdir()
# here the order is important. We try to run the correct cases first and then later trial cases
# that will likely fail
if name.startswith("."):
return importlib.util.find_spec(name, package="xontrib")
if full_module:
return importlib.util.find_spec(name)
autoloaded = getattr(XSH.builtins, "autoloaded_xontribs", None) or {}
if name in autoloaded:
return importlib.util.find_spec(autoloaded[name])
with contextlib.suppress(ValueError):
return importlib.util.find_spec("." + name, package="xontrib")
return importlib.util.find_spec(name) |
Return a context dictionary for a xontrib of a given name. | def xontrib_context(name, full_module=False):
"""Return a context dictionary for a xontrib of a given name."""
spec = find_xontrib(name, full_module)
if spec is None:
return None
module = importlib.import_module(spec.name)
ctx = {}
def _get__all__():
pubnames = getattr(module, "__all__", None)
if pubnames is None:
for k in dir(module):
if not k.startswith("_"):
yield k, getattr(module, k)
else:
for attr in pubnames:
yield attr, getattr(module, attr)
entrypoint = getattr(module, "_load_xontrib_", None)
if entrypoint is None:
ctx.update(dict(_get__all__()))
else:
result = entrypoint(xsh=XSH)
if result is not None:
ctx.update(result)
return ctx |
Returns a formatted string with name of xontrib package to prompt user | def prompt_xontrib_install(names: list[str]):
"""Returns a formatted string with name of xontrib package to prompt user"""
return (
"The following xontribs are enabled but not installed: \n"
f" {names}\n"
"Please make sure that they are installed correctly by checking https://xonsh.github.io/awesome-xontribs/\n"
) |
Updates a context in place from a xontrib. | def update_context(name, ctx: dict, full_module=False):
"""Updates a context in place from a xontrib."""
modctx = xontrib_context(name, full_module)
if modctx is None:
raise XontribNotInstalled(f"Xontrib - {name} is not found.")
else:
ctx.update(modctx)
return ctx |
Load xontribs from a list of names
Parameters
----------
names
names of xontribs
verbose : -v, --verbose
verbose output
full_module : -f, --full
indicates that the names are fully qualified module paths and not inside ``xontrib`` package
suppress_warnings : -s, --suppress-warnings
no warnings about missing xontribs and return code 0 | def xontribs_load(
names: Annotated[
tp.Sequence[str],
Arg(nargs="+", completer=xontrib_names_completer),
] = (),
verbose=False,
full_module=False,
suppress_warnings=False,
):
"""Load xontribs from a list of names
Parameters
----------
names
names of xontribs
verbose : -v, --verbose
verbose output
full_module : -f, --full
indicates that the names are fully qualified module paths and not inside ``xontrib`` package
suppress_warnings : -s, --suppress-warnings
no warnings about missing xontribs and return code 0
"""
ctx = {} if XSH.ctx is None else XSH.ctx
res = ExitCode.OK
stdout = None
stderr = None
bad_imports = []
for name in names:
if verbose:
print(f"loading xontrib {name!r}")
try:
update_context(name, ctx=ctx, full_module=full_module)
except XontribNotInstalled:
if not suppress_warnings:
bad_imports.append(name)
except Exception:
res = ExitCode.INIT_FAILED
print_exception(f"Failed to load xontrib {name}.")
if bad_imports:
res = ExitCode.NOT_FOUND
stderr = prompt_xontrib_install(bad_imports)
return stdout, stderr, res |
Unload the given xontribs
Parameters
----------
names
name of xontribs to unload
Notes
-----
Proper cleanup can be implemented by the xontrib. The default is equivalent to ``del sys.modules[module]``. | def xontribs_unload(
names: Annotated[
tp.Sequence[str],
Arg(nargs="+", completer=xontrib_unload_completer),
] = (),
verbose=False,
):
"""Unload the given xontribs
Parameters
----------
names
name of xontribs to unload
Notes
-----
Proper cleanup can be implemented by the xontrib. The default is equivalent to ``del sys.modules[module]``.
"""
for name in names:
if verbose:
print(f"unloading xontrib {name!r}")
spec = find_xontrib(name)
try:
if spec and spec.name in sys.modules:
module = sys.modules[spec.name]
unloader = getattr(module, "_unload_xontrib_", None)
if unloader is not None:
unloader(XSH)
del sys.modules[spec.name]
except Exception as ex:
print_exception(f"Failed to unload xontrib {name} ({ex})") |
Reload the given xontribs
Parameters
----------
names
name of xontribs to reload | def xontribs_reload(
names: Annotated[
tp.Sequence[str],
Arg(nargs="+", completer=xontrib_unload_completer),
] = (),
verbose=False,
):
"""Reload the given xontribs
Parameters
----------
names
name of xontribs to reload
"""
for name in names:
if verbose:
print(f"reloading xontrib {name!r}")
xontribs_unload([name])
xontribs_load([name]) |
Collects and returns the data about installed xontribs. | def xontrib_data():
"""Collects and returns the data about installed xontribs."""
data = {}
for xo_name, xontrib in get_xontribs().items():
data[xo_name] = {
"name": xo_name,
"loaded": xontrib.is_loaded,
"auto": xontrib.is_auto_loaded,
"module": xontrib.module,
}
return dict(sorted(data.items())) |
Returns list of loaded xontribs. | def xontribs_loaded():
"""Returns list of loaded xontribs."""
return [k for k, xontrib in get_xontribs().items() if xontrib.is_loaded] |
List installed xontribs and show whether they are loaded or not
Parameters
----------
to_json : -j, --json
reports results as json | def xontribs_list(to_json=False, _stdout=None):
"""List installed xontribs and show whether they are loaded or not
Parameters
----------
to_json : -j, --json
reports results as json
"""
data = xontrib_data()
if to_json:
s = json.dumps(data)
return s
else:
nname = max([6] + [len(x) for x in data])
s = ""
for name, d in data.items():
s += "{PURPLE}" + name + "{RESET} " + " " * (nname - len(name))
if d["loaded"]:
s += "{GREEN}loaded{RESET}" + " " * 4
if d["auto"]:
s += " {GREEN}auto{RESET}"
elif d["loaded"]:
s += " {CYAN}manual{RESET}"
else:
s += "{RED}not-loaded{RESET}"
s += "\n"
print_color(s[:-1], file=_stdout) |
Load xontrib modules exposed via setuptools's entrypoints | def auto_load_xontribs_from_entrypoints(
blocked: "tp.Sequence[str]" = (), verbose=False
):
"""Load xontrib modules exposed via setuptools's entrypoints"""
if not hasattr(XSH.builtins, "autoloaded_xontribs"):
XSH.builtins.autoloaded_xontribs = {}
def get_loadable():
for entry in _get_xontrib_entrypoints():
if entry.name not in blocked:
XSH.builtins.autoloaded_xontribs[entry.name] = entry.value
yield entry.value
modules = list(get_loadable())
return xontribs_load(modules, verbose=verbose, full_module=True) |
If the line is empty, complete based on valid commands, python names, and paths. | def complete_base(context: CompletionContext):
"""If the line is empty, complete based on valid commands, python names, and paths."""
# If we are completing the first argument, complete based on
# valid commands and python names.
if context.command is None or context.command.arg_index != 0:
# don't do unnecessary completions
return
# get and unpack python completions
python_comps = complete_python(context) or set()
if isinstance(python_comps, cabc.Sequence):
python_comps, python_comps_len = python_comps # type: ignore
yield from apply_lprefix(python_comps, python_comps_len)
else:
yield from python_comps
# add command completions
yield from complete_command(context.command)
# add paths, if needed
if not context.command.prefix:
path_comps, path_comp_len = contextual_complete_path(
context.command, cdpath=False
)
yield from apply_lprefix(path_comps, path_comp_len) |
Completes based on results from BASH completion. | def complete_from_bash(context: CommandContext):
"""Completes based on results from BASH completion."""
env = XSH.env.detype() # type: ignore
paths = XSH.env.get("BASH_COMPLETIONS", ()) # type: ignore
command = xp.bash_command()
args = [arg.value for arg in context.args]
prefix = context.prefix # without the quotes
args.insert(context.arg_index, prefix)
line = " ".join(args)
# lengths of all args + joining spaces
begidx = sum(len(a) for a in args[: context.arg_index]) + context.arg_index
endidx = begidx + len(prefix)
opening_quote = context.opening_quote
closing_quote = context.closing_quote
if closing_quote and not context.is_after_closing_quote:
# there already are closing quotes after our cursor, don't complete new ones (i.e. `ls "/pro<TAB>"`)
closing_quote = ""
elif opening_quote and not closing_quote:
# get the proper closing quote
closing_quote = xt.RE_STRING_START.sub("", opening_quote)
comps, lprefix = bash_completions(
prefix,
line,
begidx,
endidx,
env=env,
paths=paths,
command=command,
line_args=args,
opening_quote=opening_quote,
closing_quote=closing_quote,
arg_index=context.arg_index,
)
def enrich_comps(comp: str):
append_space = False
if comp.endswith(" "):
append_space = True
comp = comp.rstrip()
# ``bash_completions`` may have added closing quotes:
return RichCompletion(
comp, append_closing_quote=False, append_space=append_space
)
comps = set(map(enrich_comps, comps))
if lprefix == len(prefix):
lprefix += len(context.opening_quote)
if context.is_after_closing_quote:
# since bash doesn't see the closing quote, we need to add its length to lprefix
lprefix += len(context.closing_quote)
return comps, lprefix |
Returns the path to git for windows, if available and None otherwise. | def _git_for_windows_path():
"""Returns the path to git for windows, if available and None otherwise."""
import winreg
try:
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\GitForWindows")
gfwp, _ = winreg.QueryValueEx(key, "InstallPath")
except FileNotFoundError:
gfwp = None
return gfwp |
Determines the command for Bash on windows. | def _windows_bash_command(env=None):
"""Determines the command for Bash on windows."""
wbc = "bash"
path = None if env is None else env.get("PATH", None)
bash_on_path = shutil.which("bash", path=path)
if bash_on_path:
try:
out = subprocess.check_output(
[bash_on_path, "--version"],
stderr=subprocess.PIPE,
text=True,
)
except subprocess.CalledProcessError:
bash_works = False
else:
# Check if Bash is from the "Windows Subsystem for Linux" (WSL)
# which can't be used by xonsh foreign-shell/completer
bash_works = out and "pc-linux-gnu" not in out.splitlines()[0]
if bash_works:
wbc = bash_on_path
else:
gfwp = _git_for_windows_path()
if gfwp:
bashcmd = os.path.join(gfwp, "bin\\bash.exe")
if os.path.isfile(bashcmd):
wbc = bashcmd
return wbc |
Determines the command for Bash on the current plaform. | def _bash_command(env=None):
"""Determines the command for Bash on the current plaform."""
if platform.system() == "Windows":
bc = _windows_bash_command(env=None)
else:
bc = "bash"
return bc |
A possibly empty tuple with default paths to Bash completions known for
the current platform. | def _bash_completion_paths_default():
"""A possibly empty tuple with default paths to Bash completions known for
the current platform.
"""
platform_sys = platform.system()
if platform_sys == "Linux" or sys.platform == "cygwin":
bcd = ("/usr/share/bash-completion/bash_completion",)
elif platform_sys == "Darwin":
bcd = (
"/usr/local/share/bash-completion/bash_completion", # v2.x
"/usr/local/etc/bash_completion",
) # v1.x
elif platform_sys == "Windows":
gfwp = _git_for_windows_path()
if gfwp:
bcd = (
os.path.join(gfwp, "usr\\share\\bash-completion\\" "bash_completion"),
os.path.join(
gfwp, "mingw64\\share\\git\\completion\\" "git-completion.bash"
),
)
else:
bcd = ()
else:
bcd = ()
return bcd |
Returns the appropriate filepath separator char depending on OS and
xonsh options set | def _bash_get_sep():
"""Returns the appropriate filepath separator char depending on OS and
xonsh options set
"""
if platform.system() == "Windows":
return os.altsep
else:
return os.sep |
Takes a string path and expands ~ to home and environment vars. | def _bash_expand_path(s):
"""Takes a string path and expands ~ to home and environment vars."""
# expand ~ according to Bash unquoted rules "Each variable assignment is
# checked for unquoted tilde-prefixes immediately following a ':' or the
# first '='". See the following for more details.
# https://www.gnu.org/software/bash/manual/html_node/Tilde-Expansion.html
pre, char, post = s.partition("=")
if char:
s = os.path.expanduser(pre) + char
s += os.pathsep.join(map(os.path.expanduser, post.split(os.pathsep)))
else:
s = os.path.expanduser(s)
return s |
Completes based on results from BASH completion.
Parameters
----------
prefix : str
The string to match
line : str
The line that prefix appears on.
begidx : int
The index in line that prefix starts on.
endidx : int
The index in line that prefix ends on.
env : Mapping, optional
The environment dict to execute the Bash subprocess in.
paths : list or tuple of str or None, optional
This is a list (or tuple) of strings that specifies where the
``bash_completion`` script may be found. The first valid path will
be used. For better performance, bash-completion v2.x is recommended
since it lazy-loads individual completion scripts. For both
bash-completion v1.x and v2.x, paths of individual completion scripts
(like ``.../completes/ssh``) do not need to be included here. The
default values are platform dependent, but reasonable.
command : str or None, optional
The /path/to/bash to use. If None, it will be selected based on the
from the environment and platform.
quote_paths : callable, optional
A functions that quotes file system paths. You shouldn't normally need
this as the default is acceptable 99+% of the time. This function should
return a set of the new paths and a boolean for whether the paths were
quoted.
line_args : list of str, optional
A list of the args in the current line to be used instead of ``line.split()``.
This is usefull with a space in an argument, e.g. ``ls 'a dir/'<TAB>``.
opening_quote : str, optional
The current argument's opening quote. This is passed to the `quote_paths` function.
closing_quote : str, optional
The closing quote that **should** be used. This is also passed to the `quote_paths` function.
arg_index : int, optional
The current prefix's index in the args.
Returns
-------
rtn : set of str
Possible completions of prefix
lprefix : int
Length of the prefix to be replaced in the completion. | def bash_completions(
prefix,
line,
begidx,
endidx,
env=None,
paths=None,
command=None,
quote_paths=_bash_quote_paths,
line_args=None,
opening_quote="",
closing_quote="",
arg_index=None,
**kwargs,
):
"""Completes based on results from BASH completion.
Parameters
----------
prefix : str
The string to match
line : str
The line that prefix appears on.
begidx : int
The index in line that prefix starts on.
endidx : int
The index in line that prefix ends on.
env : Mapping, optional
The environment dict to execute the Bash subprocess in.
paths : list or tuple of str or None, optional
This is a list (or tuple) of strings that specifies where the
``bash_completion`` script may be found. The first valid path will
be used. For better performance, bash-completion v2.x is recommended
since it lazy-loads individual completion scripts. For both
bash-completion v1.x and v2.x, paths of individual completion scripts
(like ``.../completes/ssh``) do not need to be included here. The
default values are platform dependent, but reasonable.
command : str or None, optional
The /path/to/bash to use. If None, it will be selected based on the
from the environment and platform.
quote_paths : callable, optional
A functions that quotes file system paths. You shouldn't normally need
this as the default is acceptable 99+% of the time. This function should
return a set of the new paths and a boolean for whether the paths were
quoted.
line_args : list of str, optional
A list of the args in the current line to be used instead of ``line.split()``.
This is usefull with a space in an argument, e.g. ``ls 'a dir/'<TAB>``.
opening_quote : str, optional
The current argument's opening quote. This is passed to the `quote_paths` function.
closing_quote : str, optional
The closing quote that **should** be used. This is also passed to the `quote_paths` function.
arg_index : int, optional
The current prefix's index in the args.
Returns
-------
rtn : set of str
Possible completions of prefix
lprefix : int
Length of the prefix to be replaced in the completion.
"""
source = _get_bash_completions_source(paths) or ""
if prefix.startswith("$"): # do not complete env variables
return set(), 0
splt = line_args or line.split()
cmd = splt[0]
cmd = os.path.basename(cmd)
prev = ""
if arg_index is not None:
n = arg_index
if arg_index > 0:
prev = splt[arg_index - 1]
else:
# find `n` and `prev` by ourselves
idx = n = 0
for n, tok in enumerate(splt): # noqa
if tok == prefix:
idx = line.find(prefix, idx)
if idx >= begidx:
break
prev = tok
if len(prefix) == 0:
n += 1
prefix_quoted = shlex.quote(prefix)
script = BASH_COMPLETE_SCRIPT.format(
source=source,
line=" ".join(shlex.quote(p) for p in splt if p),
comp_line=shlex.quote(line),
n=n,
cmd=shlex.quote(cmd),
end=endidx + 1,
prefix=prefix_quoted,
prev=shlex.quote(prev),
)
if command is None:
command = _bash_command(env=env)
try:
out = subprocess.check_output(
[command, "-c", script],
text=True,
stderr=subprocess.PIPE,
env=env,
)
if not out:
raise ValueError
except (
subprocess.CalledProcessError,
FileNotFoundError,
ValueError,
):
return set(), 0
out = out.splitlines()
complete_stmt = out[0]
out = set(out[1:])
# From GNU Bash document: The results of the expansion are prefix-matched
# against the word being completed
# Ensure input to `commonprefix` is a list (now required by Python 3.6)
commprefix = os.path.commonprefix(list(out))
if prefix.startswith("~") and commprefix and prefix not in commprefix:
home_ = os.path.expanduser("~")
out = {f"~/{os.path.relpath(p, home_)}" for p in out}
commprefix = f"~/{os.path.relpath(commprefix, home_)}"
strip_len = 0
strip_prefix = prefix.strip("\"'")
while strip_len < len(strip_prefix) and strip_len < len(commprefix):
if commprefix[strip_len] == strip_prefix[strip_len]:
break
strip_len += 1
if "-o noquote" not in complete_stmt:
out, need_quotes = quote_paths(out, opening_quote, closing_quote)
if "-o nospace" in complete_stmt:
out = {x.rstrip() for x in out}
# For arguments like 'status=progress', the completion script only returns
# the part after '=' in the completion results. This causes the strip_len
# to be incorrectly calculated, so it needs to be fixed here
if "=" in prefix and "=" not in commprefix:
strip_len = prefix.index("=") + 1
# Fix case where remote git branch is being deleted
# (e.g. 'git push origin :dev-branch')
elif ":" in prefix and ":" not in commprefix:
strip_len = prefix.index(":") + 1
return out, max(len(prefix) - strip_len, 0) |
Provides the completion from the end of the line.
Parameters
----------
line : str
Line to complete
return_line : bool, optional
If true (default), will return the entire line, with the completion added.
If false, this will instead return the strings to append to the original line.
kwargs : optional
All other keyword arguments are passed to the bash_completions() function.
Returns
-------
rtn : set of str
Possible completions of prefix | def bash_complete_line(line, return_line=True, **kwargs):
"""Provides the completion from the end of the line.
Parameters
----------
line : str
Line to complete
return_line : bool, optional
If true (default), will return the entire line, with the completion added.
If false, this will instead return the strings to append to the original line.
kwargs : optional
All other keyword arguments are passed to the bash_completions() function.
Returns
-------
rtn : set of str
Possible completions of prefix
"""
# set up for completing from the end of the line
split = line.split()
if len(split) > 1 and not line.endswith(" "):
prefix = split[-1]
begidx = len(line.rsplit(prefix)[0])
else:
prefix = ""
begidx = len(line)
endidx = len(line)
# get completions
out, lprefix = bash_completions(prefix, line, begidx, endidx, **kwargs)
# reformat output
if return_line:
preline = line[:-lprefix]
rtn = {preline + o for o in out}
else:
rtn = {o[lprefix:] for o in out}
return rtn |
Runs complete_line() and prints the output. | def _bc_main(args=None):
"""Runs complete_line() and prints the output."""
from argparse import ArgumentParser
p = ArgumentParser("bash_completions")
p.add_argument(
"--return-line",
action="store_true",
dest="return_line",
default=True,
help="will return the entire line, with the completion added",
)
p.add_argument(
"--no-return-line",
action="store_false",
dest="return_line",
help="will instead return the strings to append to the original line",
)
p.add_argument("line", help="line to complete")
ns = p.parse_args(args=args)
out = bash_complete_line(ns.line, return_line=ns.return_line)
for o in sorted(out):
print(o) |
Returns a list of valid commands starting with the first argument | def complete_command(command: CommandContext):
"""
Returns a list of valid commands starting with the first argument
"""
cmd = command.prefix
show_desc = (XSH.env or {}).get("CMD_COMPLETIONS_SHOW_DESC", False)
for s, (path, is_alias) in XSH.commands_cache.iter_commands():
if get_filter_function()(s, cmd):
kwargs = {}
if show_desc:
kwargs["description"] = "Alias" if is_alias else path
yield RichCompletion(s, append_space=True, **kwargs)
if xp.ON_WINDOWS:
for i in xt.executables_in("."):
if i.startswith(cmd):
yield RichCompletion(i, append_space=True)
base = os.path.basename(cmd)
if os.path.isdir(base):
for i in xt.executables_in(base):
if i.startswith(cmd):
yield RichCompletion(os.path.join(base, i)) |
Skip over several tokens (e.g., sudo) and complete based on the rest of the command. | def complete_skipper(command_context: CommandContext):
"""
Skip over several tokens (e.g., sudo) and complete based on the rest of the command.
"""
# Contextual completers don't need us to skip tokens since they get the correct completion context -
# meaning we only need to skip commands like ``sudo``.
skip_part_num = 0
# all the args before the current argument
for arg in command_context.args[: command_context.arg_index]:
if arg.value not in SKIP_TOKENS:
break
skip_part_num += 1
if skip_part_num == 0:
return None
skipped_command_context = command_context._replace(
args=command_context.args[skip_part_num:],
arg_index=command_context.arg_index - skip_part_num,
)
if skipped_command_context.arg_index == 0:
# completing the command after a SKIP_TOKEN
return complete_command(skipped_command_context)
completer: Completer = XSH.shell.shell.completer # type: ignore
return completer.complete_from_context(CompletionContext(skipped_command_context)) |
If there's no space following '|', '&', or ';' - insert one. | def complete_end_proc_tokens(command_context: CommandContext):
"""If there's no space following '|', '&', or ';' - insert one."""
if command_context.opening_quote or not command_context.prefix:
return None
prefix = command_context.prefix
# for example `echo a|`, `echo a&&`, `echo a ;`
if any(prefix.endswith(ending) for ending in END_PROC_TOKENS):
return {RichCompletion(prefix, append_space=True)}
return None |
If there's no space following 'and' or 'or' - insert one. | def complete_end_proc_keywords(command_context: CommandContext):
"""If there's no space following 'and' or 'or' - insert one."""
if command_context.opening_quote or not command_context.prefix:
return None
prefix = command_context.prefix
if prefix in END_PROC_KEYWORDS:
return {RichCompletion(prefix, append_space=True)}
return None |
List the active completers | def list_completers():
"""List the active completers"""
o = "Registered Completer Functions: (NX = Non Exclusive)\n\n"
non_exclusive = " [NX]"
_comp = XSH.completers
ml = max((len(i) for i in _comp), default=0)
exclusive_len = ml + len(non_exclusive) + 1
_strs = []
for c in _comp:
if _comp[c].__doc__ is None:
doc = "No description provided"
else:
doc = " ".join(_comp[c].__doc__.split())
doc = justify(doc, 80, exclusive_len + 3)
if is_exclusive_completer(_comp[c]):
_strs.append("{: <{}} : {}".format(c, exclusive_len, doc))
else:
_strs.append("{: <{}} {} : {}".format(c, ml, non_exclusive, doc))
return o + "\n".join(_strs) + "\n" |
Complete all loaded completer names | def complete_completer_names(xsh, **_):
"""Complete all loaded completer names"""
for name, comp in xsh.completers.items():
doc = NumpyDoc(comp)
yield RichCompletion(name, description=doc.description) |
Removes a completer from xonsh
Parameters
----------
name:
NAME is a unique name of a completer (run "completer list" to see the current
completers in order) | def remove_completer(
name: Annotated[str, Arg(completer=complete_completer_names)],
):
"""Removes a completer from xonsh
Parameters
----------
name:
NAME is a unique name of a completer (run "completer list" to see the current
completers in order)
"""
err = None
if name not in XSH.completers:
err = f"The name {name} is not a registered completer function."
if err is None:
del XSH.completers[name]
return
else:
return None, err + "\n", 1 |
Completes environment variables. | def complete_environment_vars(context: CompletionContext):
"""Completes environment variables."""
if context.command:
prefix = context.command.prefix
elif context.python:
prefix = context.python.prefix
else:
return None
dollar_location = prefix.rfind("$")
if dollar_location == -1:
return None
key = prefix[dollar_location + 1 :]
lprefix = len(key) + 1
if context.command is not None and context.command.is_after_closing_quote:
lprefix += 1
filter_func = get_filter_function()
env = XSH.env
return (
RichCompletion(
"$" + k,
display=f"${k} [{type(v).__name__}]",
description=env.get_docs(k).doc,
)
for k, v in env.items()
if filter_func(k, key)
), lprefix |
Return the list containing the names of the modules available in the given
folder. | def module_list(path):
"""
Return the list containing the names of the modules available in the given
folder.
"""
# sys.path has the cwd as an empty string, but isdir/listdir need it as '.'
if path == "":
path = "."
# A few local constants to be used in loops below
pjoin = os.path.join
if os.path.isdir(path):
# Build a list of all files in the directory and all files
# in its subdirectories. For performance reasons, do not
# recurse more than one level into subdirectories.
files = []
for root, dirs, nondirs in os.walk(path, followlinks=True):
subdir = root[len(path) + 1 :]
if subdir:
files.extend(pjoin(subdir, f) for f in nondirs)
dirs[:] = [] # Do not recurse into additional subdirectories.
else:
files.extend(nondirs)
else:
try:
files = list(zipimporter(path)._files.keys())
except: # noqa
files = []
# Build a list of modules which match the import_re regex.
modules = []
for f in files:
m = IMPORT_RE.match(f)
if m:
modules.append(m.group("name"))
return list(set(modules)) |
Returns a list containing the names of all the modules available in the
folders of the pythonpath. | def get_root_modules():
"""
Returns a list containing the names of all the modules available in the
folders of the pythonpath.
"""
rootmodules_cache = XSH.modules_cache
rootmodules = list(sys.builtin_module_names)
start_time = time()
for path in sys.path:
try:
modules = rootmodules_cache[path]
except KeyError:
modules = module_list(path)
try:
modules.remove("__init__")
except ValueError:
pass
if path not in ("", "."): # cwd modules should not be cached
rootmodules_cache[path] = modules
if time() - start_time > TIMEOUT_GIVEUP:
print("\nwarning: Getting root modules is taking too long, we give up")
return []
rootmodules.extend(modules)
rootmodules = list(set(rootmodules))
return rootmodules |
Try to import given module and return list of potential completions. | def try_import(mod: str, only_modules=False) -> list[str]:
"""
Try to import given module and return list of potential completions.
"""
mod = mod.rstrip(".")
try:
m = import_module(mod)
except Exception:
return []
m_is_init = "__init__" in (getattr(m, "__file__", "") or "")
completions = []
if (not hasattr(m, "__file__")) or (not only_modules) or m_is_init:
completions.extend(
[attr for attr in dir(m) if is_importable(m, attr, only_modules)]
)
m_all = getattr(m, "__all__", [])
if only_modules:
completions.extend(attr for attr in m_all if is_possible_submodule(m, attr))
else:
completions.extend(m_all)
if m_is_init:
if m.__file__:
completions.extend(module_list(os.path.dirname(m.__file__)))
completions_set = {c for c in completions if isinstance(c, str)}
completions_set.discard("__init__")
return list(completions_set) |
Completes module names and objects for "import ..." and "from ... import
...". | def complete_import(context: CompletionContext):
"""
Completes module names and objects for "import ..." and "from ... import
...".
"""
if not (context.command and context.python):
# Imports are only possible in independent lines (not in `$()` or `@()`).
# This means it's python code, but also can be a command as far as the parser is concerned.
return None
command = context.command
if command.opening_quote:
# can't have a quoted import
return None
arg_index = command.arg_index
prefix = command.prefix
args = command.args
if arg_index == 1 and args[0].value == "from":
# completing module to import
return complete_module(prefix)
if arg_index >= 1 and args[0].value == "import":
# completing module to import, might be multiple modules
prefix = prefix.rsplit(",", 1)[-1]
return complete_module(prefix), len(prefix)
if arg_index == 2 and args[0].value == "from":
return {RichCompletion("import", append_space=True)}
if arg_index > 2 and args[0].value == "from" and args[2].value == "import":
# complete thing inside a module, might be multiple objects
module = args[1].value
prefix = prefix.rsplit(",", 1)[-1]
return filter_completions(prefix, try_import(module)), len(prefix)
return set() |
Creates a copy of the default completers. | def default_completers(cmd_cache):
"""Creates a copy of the default completers."""
defaults = [
# non-exclusive completers:
("end_proc_tokens", complete_end_proc_tokens),
("end_proc_keywords", complete_end_proc_keywords),
("environment_vars", complete_environment_vars),
# exclusive completers:
("base", complete_base),
("skip", complete_skipper),
("alias", complete_aliases),
("xompleter", complete_xompletions),
("import", complete_import),
]
for cmd, func in [
("bash", complete_from_bash),
("man", complete_from_man),
]:
if cmd in cmd_cache:
defaults.append((cmd, func))
defaults.extend(
[
("python", complete_python),
("path", complete_path),
]
)
return collections.OrderedDict(defaults) |
without control characters | def _get_man_page(cmd: str):
"""without control characters"""
env = XSH.env.detype()
manpage = subprocess.Popen(
["man", cmd], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, env=env
)
# This is a trick to get rid of reverse line feeds
return subprocess.check_output(["col", "-b"], stdin=manpage.stdout, env=env) |
Completes an option name, based on the contents of the associated man
page. | def complete_from_man(context: CommandContext):
"""
Completes an option name, based on the contents of the associated man
page.
"""
if context.arg_index == 0 or not context.prefix.startswith("-"):
return
cmd = context.args[0].value
def completions():
for desc, opts in _parse_man_page_options(cmd).items():
yield RichCompletion(
value=opts[-1], display=", ".join(opts), description=desc
)
return completions(), False |
Returns True if "cd" is a token in the line, False otherwise. | def cd_in_command(line):
"""Returns True if "cd" is a token in the line, False otherwise."""
lexer = XSH.execer.parser.lexer
lexer.reset()
lexer.input(line)
have_cd = False
for tok in lexer:
if tok.type == "NAME" and tok.value == "cd":
have_cd = True
break
return have_cd |
Wraps os.normpath() to avoid removing './' at the beginning
and '/' at the end. On windows it does the same with backslashes | def _normpath(p):
"""
Wraps os.normpath() to avoid removing './' at the beginning
and '/' at the end. On windows it does the same with backslashes
"""
initial_dotslash = p.startswith(os.curdir + os.sep)
initial_dotslash |= xp.ON_WINDOWS and p.startswith(os.curdir + os.altsep)
p = p.rstrip()
trailing_slash = p.endswith(os.sep)
trailing_slash |= xp.ON_WINDOWS and p.endswith(os.altsep)
p = os.path.normpath(p)
if initial_dotslash and p != ".":
p = os.path.join(os.curdir, p)
if trailing_slash:
p = os.path.join(p, "")
if xp.ON_WINDOWS and XSH.env.get("FORCE_POSIX_PATHS"):
p = p.replace(os.sep, os.altsep)
return p |
Completes current prefix using CDPATH | def _add_cdpaths(paths, prefix):
"""Completes current prefix using CDPATH"""
env = XSH.env
csc = env.get("CASE_SENSITIVE_COMPLETIONS")
glob_sorted = env.get("GLOB_SORTED")
for cdp in env.get("CDPATH"):
test_glob = os.path.join(cdp, prefix) + "*"
for s in xt.iglobpath(
test_glob, ignore_case=(not csc), sort_result=glob_sorted
):
if os.path.isdir(s):
paths.add(os.path.relpath(s, cdp)) |
Detects whether typed is a subsequence of ref.
Returns ``True`` if the characters in ``typed`` appear (in order) in
``ref``, regardless of exactly where in ``ref`` they occur. If ``csc`` is
``False``, ignore the case of ``ref`` and ``typed``.
Used in "subsequence" path completion (e.g., ``~/u/ro`` expands to
``~/lou/carcohl``) | def subsequence_match(ref, typed, csc):
"""
Detects whether typed is a subsequence of ref.
Returns ``True`` if the characters in ``typed`` appear (in order) in
``ref``, regardless of exactly where in ``ref`` they occur. If ``csc`` is
``False``, ignore the case of ``ref`` and ``typed``.
Used in "subsequence" path completion (e.g., ``~/u/ro`` expands to
``~/lou/carcohl``)
"""
if csc:
return _subsequence_match_iter(ref, typed)
else:
return _subsequence_match_iter(ref.lower(), typed.lower()) |
Completes path names. | def complete_path(context):
"""Completes path names."""
if context.command:
return contextual_complete_path(context.command)
elif context.python:
line = context.python.prefix
# simple prefix _complete_path_raw will handle gracefully:
prefix = line.rsplit(" ", 1)[-1]
return _complete_path_raw(prefix, line, len(line) - len(prefix), len(line), {})
return set(), 0 |
Completes based on the contents of the current Python environment,
the Python built-ins, and xonsh operators. | def complete_python(context: CompletionContext) -> CompleterResult:
"""
Completes based on the contents of the current Python environment,
the Python built-ins, and xonsh operators.
"""
# If there are no matches, split on common delimiters and try again.
if context.python is None:
return None
if context.command and context.command.arg_index != 0:
# this can be a command (i.e. not a subexpression)
first = context.command.args[0].value
ctx = context.python.ctx or {}
if first in XSH.commands_cache and first not in ctx: # type: ignore
# this is a known command, so it won't be python code
return None
line = context.python.multiline_code
prefix = (line.rsplit(maxsplit=1) or [""])[-1]
rtn = _complete_python(prefix, context.python)
if not rtn:
prefix = (
re.split(r"\(|=|{|\[|,", prefix)[-1]
if not prefix.startswith(",")
else prefix
)
rtn = _complete_python(prefix, context.python)
return rtn, len(prefix) |
Completes based on the contents of the current Python environment,
the Python built-ins, and xonsh operators. | def _complete_python(prefix, context: PythonContext):
"""
Completes based on the contents of the current Python environment,
the Python built-ins, and xonsh operators.
"""
line = context.multiline_code
end = context.cursor_index
ctx = context.ctx
filt = get_filter_function()
rtn = set()
if ctx is not None:
if "." in prefix:
rtn |= attr_complete(prefix, ctx, filt)
args = python_signature_complete(prefix, line, end, ctx, filt)
rtn |= args
rtn |= {s for s in ctx if filt(s, prefix)}
else:
args = ()
if len(args) == 0:
# not in a function call, so we can add non-expression tokens
rtn |= {s for s in XONSH_TOKENS if filt(s, prefix)}
else:
rtn |= {s for s in XONSH_EXPR_TOKENS if filt(s, prefix)}
rtn |= {s for s in dir(builtins) if filt(s, prefix)}
return rtn |
Decorator to turn off warning temporarily. | def _turn_off_warning(func):
"""Decorator to turn off warning temporarily."""
def wrapper(*args, **kwargs):
warnings.filterwarnings("ignore")
r = func(*args, **kwargs)
warnings.filterwarnings("once", category=DeprecationWarning)
return r
return wrapper |
Safely tries to evaluate an expression. If this fails, it will return
a (None, None) tuple. | def _safe_eval(expr, ctx):
"""Safely tries to evaluate an expression. If this fails, it will return
a (None, None) tuple.
"""
_ctx = None
xonsh_safe_eval = XSH.execer.eval
try:
val = xonsh_safe_eval(expr, ctx, ctx, transform=False)
_ctx = ctx
except Exception:
try:
val = xonsh_safe_eval(expr, builtins.__dict__, transform=False)
_ctx = builtins.__dict__
except Exception:
val = _ctx = None
return val, _ctx |