response
stringlengths 1
33.1k
| instruction
stringlengths 22
582k
|
---|---|
Return parsed values from ``git status --porcelain`` | def porcelain(fld, ctx: PromptFields):
"""Return parsed values from ``git status --porcelain``"""
status = _get_sp_output(ctx.xsh, "git", "status", "--porcelain", "--branch")
branch = ""
ahead, behind = 0, 0
untracked, changed, deleted, conflicts, staged = 0, 0, 0, 0, 0
for line in status.splitlines():
if line.startswith("##"):
line = line[2:].strip()
if "Initial commit on" in line:
branch = line.split()[-1]
elif "no branch" in line:
branch = ctx.pick(tag_or_hash) or ""
elif "..." not in line:
branch = line
else:
branch, rest = line.split("...")
if " " in rest:
divergence = rest.split(" ", 1)[-1]
divergence = divergence.strip("[]")
for div in divergence.split(", "):
if "ahead" in div:
ahead = int(div[len("ahead ") :].strip())
elif "behind" in div:
behind = int(div[len("behind ") :].strip())
elif line.startswith("??"):
untracked += 1
else:
if len(line) > 1:
if line[1] == "M":
changed += 1
elif line[1] == "D":
deleted += 1
if len(line) > 0 and line[0] == "U":
conflicts += 1
elif len(line) > 0 and line[0] != " ":
staged += 1
fld.value = {
"branch": branch,
"ahead": ahead,
"behind": behind,
"untracked": untracked,
"changed": changed,
"deleted": deleted,
"conflicts": conflicts,
"staged": staged,
} |
Get individual fields from $PROMPT_FIELDS['gitstatus.porcelain'] | def get_gitstatus_info(fld: "_GSInfo", ctx: PromptFields) -> None:
"""Get individual fields from $PROMPT_FIELDS['gitstatus.porcelain']"""
info = ctx.pick_val(porcelain)
fld.value = info[fld.info] |
Attempts to find the current git branch. If this could not
be determined (timeout, not in a git repo, etc.) then this returns None. | def get_git_branch():
"""Attempts to find the current git branch. If this could not
be determined (timeout, not in a git repo, etc.) then this returns None.
"""
branch = None
timeout = XSH.env.get("VC_BRANCH_TIMEOUT")
q = queue.Queue()
t = threading.Thread(target=_get_git_branch, args=(q,))
t.start()
t.join(timeout=timeout)
try:
branch = q.get_nowait()
if branch:
branch = RE_REMOVE_ANSI.sub("", branch)
except queue.Empty:
branch = None
return branch |
Try to get the mercurial branch of the current directory,
return None if not in a repo or subprocess.TimeoutExpired if timed out. | def get_hg_branch(root=None):
"""Try to get the mercurial branch of the current directory,
return None if not in a repo or subprocess.TimeoutExpired if timed out.
"""
env = XSH.env
timeout = env["VC_BRANCH_TIMEOUT"]
q = queue.Queue()
t = threading.Thread(target=_get_hg_root, args=(q,))
t.start()
t.join(timeout=timeout)
try:
root = pathlib.Path(q.get_nowait())
except queue.Empty:
return None
if env.get("VC_HG_SHOW_BRANCH"):
# get branch name
branch_path = root / ".hg" / "branch"
if branch_path.exists():
with open(branch_path) as branch_file:
branch = branch_file.read().strip()
else:
branch = "default"
else:
branch = ""
# add activated bookmark and topic
for filename in ["bookmarks.current", "topic"]:
feature_branch_path = root / ".hg" / filename
if feature_branch_path.exists():
with open(feature_branch_path) as file:
feature_branch = file.read().strip()
if feature_branch:
if branch:
if filename == "topic":
branch = f"{branch}/{feature_branch}"
else:
branch = f"{branch}, {feature_branch}"
else:
branch = feature_branch
return branch |
Attempts to find the current fossil branch. If this could not
be determined (timeout, not in a fossil checkout, etc.) then this returns None. | def get_fossil_branch():
"""Attempts to find the current fossil branch. If this could not
be determined (timeout, not in a fossil checkout, etc.) then this returns None.
"""
# from fossil branch --help: "fossil branch current: Print the name of the branch for the current check-out"
cmd = "fossil branch current".split()
try:
branch = xt.decode_bytes(_run_fossil_cmd(cmd))
except (subprocess.CalledProcessError, OSError):
branch = None
else:
branch = RE_REMOVE_ANSI.sub("", branch.splitlines()[0])
return branch |
This allows us to locate binaries after git only if necessary | def _vc_has(binary):
"""This allows us to locate binaries after git only if necessary"""
cmds = XSH.commands_cache
if cmds.is_empty():
return bool(cmds.locate_binary(binary, ignore_alias=True))
else:
return bool(cmds.lazy_locate_binary(binary, ignore_alias=True)) |
Gets the branch for a current working directory. Returns an empty string
if the cwd is not a repository. This currently only works for git, hg, and fossil
and should be extended in the future. If a timeout occurred, the string
'<branch-timeout>' is returned. | def current_branch():
"""Gets the branch for a current working directory. Returns an empty string
if the cwd is not a repository. This currently only works for git, hg, and fossil
and should be extended in the future. If a timeout occurred, the string
'<branch-timeout>' is returned.
"""
branch = None
if _vc_has("git"):
branch = get_git_branch()
if not branch and _vc_has("hg"):
branch = get_hg_branch()
if not branch and _vc_has("fossil"):
branch = get_fossil_branch()
if isinstance(branch, subprocess.TimeoutExpired):
branch = "<branch-timeout>"
_first_branch_timeout_message()
return branch or None |
Returns whether or not the git directory is dirty. If this could not
be determined (timeout, file not found, etc.) then this returns None. | def git_dirty_working_directory():
"""Returns whether or not the git directory is dirty. If this could not
be determined (timeout, file not found, etc.) then this returns None.
"""
env = XSH.env
timeout = env.get("VC_BRANCH_TIMEOUT")
include_untracked = env.get("VC_GIT_INCLUDE_UNTRACKED")
q = queue.Queue()
t = threading.Thread(
target=_git_dirty_working_directory, args=(q, include_untracked)
)
t.start()
t.join(timeout=timeout)
try:
return q.get_nowait()
except queue.Empty:
return None |
Computes whether or not the mercurial working directory is dirty or not.
If this cannot be determined, None is returned. | def hg_dirty_working_directory():
"""Computes whether or not the mercurial working directory is dirty or not.
If this cannot be determined, None is returned.
"""
env = XSH.env
cwd = env["PWD"]
denv = env.detype()
vcbt = env["VC_BRANCH_TIMEOUT"]
# Override user configurations settings and aliases
denv["HGRCPATH"] = ""
try:
s = subprocess.check_output(
["hg", "identify", "--id"],
stderr=subprocess.PIPE,
cwd=cwd,
timeout=vcbt,
text=True,
env=denv,
)
return s.strip(os.linesep).endswith("+")
except (
subprocess.CalledProcessError,
subprocess.TimeoutExpired,
FileNotFoundError,
):
return None |
Returns whether the fossil checkout is dirty. If this could not
be determined (timeout, file not found, etc.) then this returns None. | def fossil_dirty_working_directory():
"""Returns whether the fossil checkout is dirty. If this could not
be determined (timeout, file not found, etc.) then this returns None.
"""
cmd = ["fossil", "changes"]
try:
status = _run_fossil_cmd(cmd)
except (subprocess.CalledProcessError, OSError):
status = None
else:
status = bool(status)
return status |
Returns a boolean as to whether there are uncommitted files in version
control repository we are inside. If this cannot be determined, returns
None. Currently supports git and hg. | def dirty_working_directory():
"""Returns a boolean as to whether there are uncommitted files in version
control repository we are inside. If this cannot be determined, returns
None. Currently supports git and hg.
"""
dwd = None
if _vc_has("git"):
dwd = git_dirty_working_directory()
if dwd is None and _vc_has("hg"):
dwd = hg_dirty_working_directory()
if dwd is None and _vc_has("fossil"):
dwd = fossil_dirty_working_directory()
return dwd |
Return red if the current branch is dirty, yellow if the dirtiness can
not be determined, and green if it clean. These are bold, intense colors
for the foreground. | def branch_color():
"""Return red if the current branch is dirty, yellow if the dirtiness can
not be determined, and green if it clean. These are bold, intense colors
for the foreground.
"""
dwd = dirty_working_directory()
if dwd is None:
color = "{BOLD_INTENSE_YELLOW}"
elif dwd:
color = "{BOLD_INTENSE_RED}"
else:
color = "{BOLD_INTENSE_GREEN}"
return color |
Return red if the current branch is dirty, yellow if the dirtiness can
not be determined, and green if it clean. These are background colors. | def branch_bg_color():
"""Return red if the current branch is dirty, yellow if the dirtiness can
not be determined, and green if it clean. These are background colors.
"""
dwd = dirty_working_directory()
if dwd is None:
color = "{BACKGROUND_YELLOW}"
elif dwd:
color = "{BACKGROUND_RED}"
else:
color = "{BACKGROUND_GREEN}"
return color |
Custom history search method for prompt_toolkit that matches previous
commands anywhere on a line, not just at the start.
This gets monkeypatched into the prompt_toolkit prompter if
``XONSH_HISTORY_MATCH_ANYWHERE=True`` | def _cust_history_matches(self, i):
"""Custom history search method for prompt_toolkit that matches previous
commands anywhere on a line, not just at the start.
This gets monkeypatched into the prompt_toolkit prompter if
``XONSH_HISTORY_MATCH_ANYWHERE=True``"""
return (
self.history_search_text is None
or self.history_search_text in self._working_lines[i]
) |
Preliminary parser to determine if 'Enter' key should send command to the
xonsh parser for execution or should insert a newline for continued input.
Current 'triggers' for inserting a newline are:
- Not on first line of buffer and line is non-empty
- Previous character is a colon (covers if, for, etc...)
- User is in an open paren-block
- Line ends with backslash
- Any text exists below cursor position (relevant when editing previous
multiline blocks) | def carriage_return(b, cli, *, autoindent=True):
"""Preliminary parser to determine if 'Enter' key should send command to the
xonsh parser for execution or should insert a newline for continued input.
Current 'triggers' for inserting a newline are:
- Not on first line of buffer and line is non-empty
- Previous character is a colon (covers if, for, etc...)
- User is in an open paren-block
- Line ends with backslash
- Any text exists below cursor position (relevant when editing previous
multiline blocks)
"""
doc = b.document
at_end_of_line = _is_blank(doc.current_line_after_cursor)
current_line_blank = _is_blank(doc.current_line)
env = XSH.env
indent = env.get("INDENT") if autoindent else ""
partial_string_info = check_for_partial_string(doc.text)
in_partial_string = (
partial_string_info[0] is not None and partial_string_info[1] is None
)
# indent after a colon
if ends_with_colon_token(doc.current_line_before_cursor) and at_end_of_line:
b.newline(copy_margin=autoindent)
b.insert_text(indent, fire_event=False)
# if current line isn't blank, check dedent tokens
elif (
not current_line_blank
and doc.current_line.split(maxsplit=1)[0] in DEDENT_TOKENS
and doc.line_count > 1
):
b.newline(copy_margin=autoindent)
b.delete_before_cursor(count=len(indent))
elif not doc.on_first_line and not current_line_blank:
b.newline(copy_margin=autoindent)
elif doc.current_line.endswith(get_line_continuation()):
b.newline(copy_margin=autoindent)
elif doc.find_next_word_beginning() is not None and (
any(not _is_blank(i) for i in doc.lines_from_current[1:])
):
b.newline(copy_margin=autoindent)
elif not current_line_blank and not can_compile(doc.text):
b.newline(copy_margin=autoindent)
elif current_line_blank and in_partial_string:
b.newline(copy_margin=autoindent)
else:
b.validate_and_handle() |
Returns whether the code can be compiled, i.e. it is valid xonsh. | def can_compile(src):
"""Returns whether the code can be compiled, i.e. it is valid xonsh."""
src = src if src.endswith("\n") else src + "\n"
src = transform_command(src, show_diff=False)
src = src.lstrip()
try:
XSH.execer.compile(src, mode="single", glbs=None, locs=XSH.ctx)
rtn = True
except SyntaxError:
rtn = False
except Exception:
rtn = True
return rtn |
Check if <Tab> should insert indent instead of starting autocompletion.
Checks if there are only whitespaces before the cursor - if so indent
should be inserted, otherwise autocompletion. | def tab_insert_indent():
"""Check if <Tab> should insert indent instead of starting autocompletion.
Checks if there are only whitespaces before the cursor - if so indent
should be inserted, otherwise autocompletion.
"""
before_cursor = get_app().current_buffer.document.current_line_before_cursor
return bool(before_cursor.isspace()) |
Checks whether completion mode is `menu-complete` | def tab_menu_complete():
"""Checks whether completion mode is `menu-complete`"""
return XSH.env.get("COMPLETION_MODE") == "menu-complete" |
Check if cursor is at beginning of a line other than the first line in a
multiline document | def beginning_of_line():
"""Check if cursor is at beginning of a line other than the first line in a
multiline document
"""
app = get_app()
before_cursor = app.current_buffer.document.current_line_before_cursor
return bool(
len(before_cursor) == 0 and not app.current_buffer.document.on_first_line
) |
Check if cursor is at the end of a line other than the last line in a
multiline document | def end_of_line():
"""Check if cursor is at the end of a line other than the last line in a
multiline document
"""
d = get_app().current_buffer.document
at_end = d.is_cursor_at_the_end_of_line
last_line = d.is_cursor_at_the_end
return bool(at_end and not last_line) |
Check if completion needs confirmation | def should_confirm_completion():
"""Check if completion needs confirmation"""
return (
XSH.env.get("COMPLETIONS_CONFIRM") and get_app().current_buffer.complete_state
) |
Ctrl-D binding is only active when the default buffer is selected and
empty. | def ctrl_d_condition():
"""Ctrl-D binding is only active when the default buffer is selected and
empty.
"""
if XSH.env.get("IGNOREEOF"):
return False
else:
app = get_app()
buffer_name = app.current_buffer.name
return buffer_name == DEFAULT_BUFFER and not app.current_buffer.text |
Check if XONSH_AUTOPAIR is set | def autopair_condition():
"""Check if XONSH_AUTOPAIR is set"""
return XSH.env.get("XONSH_AUTOPAIR", False) |
Check if there is whitespace or an opening
bracket to the left of the cursor | def whitespace_or_bracket_before():
"""Check if there is whitespace or an opening
bracket to the left of the cursor"""
d = get_app().current_buffer.document
return bool(
d.cursor_position == 0
or d.char_before_cursor.isspace()
or d.char_before_cursor in "([{"
) |
Check if there is whitespace or a closing
bracket to the right of the cursor | def whitespace_or_bracket_after():
"""Check if there is whitespace or a closing
bracket to the right of the cursor"""
d = get_app().current_buffer.document
return bool(
d.is_cursor_at_the_end_of_line
or d.current_char.isspace()
or d.current_char in ")]}"
) |
Load custom key bindings.
Parameters
----------
ptk_bindings :
The default prompt toolkit bindings. We need these to add aliases to them. | def load_xonsh_bindings(ptk_bindings: KeyBindingsBase) -> KeyBindingsBase:
"""
Load custom key bindings.
Parameters
----------
ptk_bindings :
The default prompt toolkit bindings. We need these to add aliases to them.
"""
key_bindings = KeyBindings()
handle = key_bindings.add
has_selection = HasSelection()
insert_mode = ViInsertMode() | EmacsInsertMode()
if XSH.env["XONSH_CTRL_BKSP_DELETION"]:
# Not all terminal emulators emit the same keys for backspace, therefore
# ptk always maps backspace ("\x7f") to ^H ("\x08"), and all the backspace bindings are registered for ^H.
# This means we can't re-map backspace and instead we register a new "real-ctrl-bksp" key.
# See https://github.com/xonsh/xonsh/issues/4407
if ON_WINDOWS:
# On windows BKSP is "\x08" and CTRL-BKSP is "\x7f"
REAL_CTRL_BKSP = "\x7f"
# PTK uses a second mapping
from prompt_toolkit.input import win32 as ptk_win32
ptk_win32.ConsoleInputReader.mappings[b"\x7f"] = REAL_CTRL_BKSP # type: ignore
else:
REAL_CTRL_BKSP = "\x08"
# Prompt-toolkit allows using single-character keys that aren't in the `Keys` enum.
ansi_escape_sequences.ANSI_SEQUENCES[REAL_CTRL_BKSP] = REAL_CTRL_BKSP # type: ignore
ansi_escape_sequences.REVERSE_ANSI_SEQUENCES[REAL_CTRL_BKSP] = REAL_CTRL_BKSP # type: ignore
@handle(REAL_CTRL_BKSP, filter=insert_mode)
def delete_word(event):
"""Delete a single word (like ALT-backspace)"""
get_by_name("backward-kill-word").call(event)
@handle(Keys.Tab, filter=tab_insert_indent)
def insert_indent(event):
"""
If there are only whitespaces before current cursor position insert
indent instead of autocompleting.
"""
env = XSH.env
event.cli.current_buffer.insert_text(env.get("INDENT"))
@handle(Keys.Tab, filter=~tab_insert_indent & tab_menu_complete)
def menu_complete_select(event):
"""Start completion in menu-complete mode, or tab to next completion"""
b = event.current_buffer
if b.complete_state:
b.complete_next()
else:
b.start_completion(select_first=True)
@handle(Keys.ControlX, Keys.ControlE, filter=~has_selection)
def open_editor(event):
"""Open current buffer in editor"""
event.current_buffer.open_in_editor(event.cli)
@handle(Keys.BackTab, filter=insert_mode)
def insert_literal_tab(event):
"""Insert literal tab on Shift+Tab instead of autocompleting"""
b = event.current_buffer
if b.complete_state:
b.complete_previous()
else:
env = XSH.env
event.cli.current_buffer.insert_text(env.get("INDENT"))
def generate_parens_handlers(left, right):
@handle(left, filter=autopair_condition)
def insert_left_paren(event):
buffer = event.cli.current_buffer
if has_selection():
wrap_selection(buffer, left, right)
elif whitespace_or_bracket_after():
buffer.insert_text(left)
buffer.insert_text(right, move_cursor=False)
else:
buffer.insert_text(left)
@handle(right, filter=autopair_condition)
def overwrite_right_paren(event):
buffer = event.cli.current_buffer
if buffer.document.current_char == right:
buffer.cursor_position += 1
else:
buffer.insert_text(right)
generate_parens_handlers("(", ")")
generate_parens_handlers("[", "]")
generate_parens_handlers("{", "}")
def generate_quote_handler(quote):
@handle(quote, filter=autopair_condition)
def insert_quote(event):
buffer = event.cli.current_buffer
if has_selection():
wrap_selection(buffer, quote, quote)
elif buffer.document.current_char == quote:
buffer.cursor_position += 1
elif whitespace_or_bracket_before() and whitespace_or_bracket_after():
buffer.insert_text(quote)
buffer.insert_text(quote, move_cursor=False)
else:
buffer.insert_text(quote)
generate_quote_handler("'")
generate_quote_handler('"')
@handle(Keys.Backspace, filter=autopair_condition)
def delete_brackets_or_quotes(event):
"""Delete empty pair of brackets or quotes"""
buffer = event.cli.current_buffer
before = buffer.document.char_before_cursor
after = buffer.document.current_char
if any(
[before == b and after == a for (b, a) in ["()", "[]", "{}", "''", '""']]
):
buffer.delete(1)
buffer.delete_before_cursor(1)
@handle(Keys.ControlD, filter=ctrl_d_condition)
def call_exit_alias(event):
"""Use xonsh exit function"""
b = event.cli.current_buffer
b.validate_and_handle()
xonsh_exit([])
@handle(Keys.ControlJ, filter=IsMultiline() & insert_mode)
@handle(Keys.ControlM, filter=IsMultiline() & insert_mode)
def multiline_carriage_return(event):
"""Wrapper around carriage_return multiline parser"""
b = event.cli.current_buffer
carriage_return(b, event.cli)
@handle(Keys.ControlJ, filter=should_confirm_completion)
@handle(Keys.ControlM, filter=should_confirm_completion)
def enter_confirm_completion(event):
"""Ignore <enter> (confirm completion)"""
event.current_buffer.complete_state = None
@handle(Keys.Escape, filter=should_confirm_completion)
def esc_cancel_completion(event):
"""Use <ESC> to cancel completion"""
event.cli.current_buffer.cancel_completion()
@handle(Keys.Escape, Keys.ControlJ)
def execute_block_now(event):
"""Execute a block of text irrespective of cursor position"""
b = event.cli.current_buffer
b.validate_and_handle()
@handle(Keys.Left, filter=beginning_of_line)
def wrap_cursor_back(event):
"""Move cursor to end of previous line unless at beginning of
document
"""
b = event.cli.current_buffer
b.cursor_up(count=1)
relative_end_index = b.document.get_end_of_line_position()
b.cursor_right(count=relative_end_index)
@handle(Keys.Right, filter=end_of_line)
def wrap_cursor_forward(event):
"""Move cursor to beginning of next line unless at end of document"""
b = event.cli.current_buffer
relative_begin_index = b.document.get_start_of_line_position()
b.cursor_left(count=abs(relative_begin_index))
b.cursor_down(count=1)
@handle(Keys.ControlM, filter=IsSearching())
@handle(Keys.ControlJ, filter=IsSearching())
def accept_search(event):
search.accept_search()
@handle(Keys.ControlZ)
def skip_control_z(event):
"""Prevents the writing of ^Z to the prompt, if Ctrl+Z was pressed
during the previous command.
"""
pass
@handle(Keys.ControlX, Keys.ControlX, filter=has_selection)
def _cut(event):
"""Cut selected text."""
data = event.current_buffer.cut_selection()
event.app.clipboard.set_data(data)
@handle(Keys.ControlX, Keys.ControlC, filter=has_selection)
def _copy(event):
"""Copy selected text."""
data = event.current_buffer.copy_selection()
event.app.clipboard.set_data(data)
@handle(Keys.ControlV, filter=insert_mode | has_selection)
def _yank(event):
"""Paste selected text."""
buff = event.current_buffer
if buff.selection_state:
buff.cut_selection()
get_by_name("yank").call(event)
def create_alias(new_keys, original_keys):
bindings = ptk_bindings.get_bindings_for_keys(tuple(original_keys))
for original_binding in bindings:
handle(*new_keys, filter=original_binding.filter)(original_binding.handler)
# Complete a single auto-suggestion word
create_alias([Keys.ControlRight], ["escape", "f"])
# since macOS uses Control as reserved, then we use the alt/option key instead
# which is mapped as the "escape" key
create_alias(["escape", "right"], ["escape", "f"])
return key_bindings |
Checks a list of (token, str) tuples for ANSI escape sequences and
extends the token list with the new formatted entries.
During processing tokens are converted to ``prompt_toolkit.FormattedText``.
Returns a list of similar (token, str) tuples. | def tokenize_ansi(tokens):
"""Checks a list of (token, str) tuples for ANSI escape sequences and
extends the token list with the new formatted entries.
During processing tokens are converted to ``prompt_toolkit.FormattedText``.
Returns a list of similar (token, str) tuples.
"""
formatted_tokens = to_formatted_text(tokens)
ansi_tokens = []
for style, text in formatted_tokens:
if "\x1b" in text:
formatted_ansi = to_formatted_text(ANSI(text))
ansi_text = ""
prev_style = ""
for ansi_style, ansi_text_part in formatted_ansi:
if prev_style == ansi_style:
ansi_text += ansi_text_part
else:
ansi_tokens.append((prev_style or style, ansi_text))
prev_style = ansi_style
ansi_text = ansi_text_part
ansi_tokens.append((prev_style or style, ansi_text))
else:
ansi_tokens.append((style, text))
return ansi_tokens |
Converts pygments Tokens, token names (strings) to PTK style names. | def _pygments_token_to_classname(token):
"""Converts pygments Tokens, token names (strings) to PTK style names."""
if token and isinstance(token, str):
# if starts with non capital letter => leave it as it is
if token[0].islower():
return token
# if starts with capital letter => pygments token name
if token.startswith("Token."):
token = token[6:]
# short colors - all caps
if token == token.upper():
token = "color." + token
return "pygments." + token.lower()
return pygments_token_to_classname(token) |
Custom implementation of ``style_from_pygments_dict`` that supports PTK specific
(``Token.PTK``) styles. | def _style_from_pygments_dict(pygments_dict):
"""Custom implementation of ``style_from_pygments_dict`` that supports PTK specific
(``Token.PTK``) styles.
"""
pygments_style = []
for token, style in pygments_dict.items():
# if ``Token.PTK`` then add it as "native" PTK style too
if str(token).startswith("Token.PTK"):
key = CAPITAL_PATTERN.sub(r"\1-\2", str(token)[10:]).lower()
pygments_style.append((key, style))
pygments_style.append((_pygments_token_to_classname(token), style))
return Style(pygments_style) |
Custom implementation of ``style_from_pygments_cls`` that supports PTK specific
(``Token.PTK``) styles. | def _style_from_pygments_cls(pygments_cls):
"""Custom implementation of ``style_from_pygments_cls`` that supports PTK specific
(``Token.PTK``) styles.
"""
return _style_from_pygments_dict(pygments_cls.styles) |
Move xsh test first to work around a bug in normal
pytest cleanup. The order of tests are otherwise preserved. | def pytest_collection_modifyitems(items):
"""Move xsh test first to work around a bug in normal
pytest cleanup. The order of tests are otherwise preserved.
"""
items.sort(key=lambda item: -isinstance(item, XshFunction)) |
Return a formatted traceback with all the stack
from this frame (i.e __file__) up removed | def _limited_traceback(excinfo):
"""Return a formatted traceback with all the stack
from this frame (i.e __file__) up removed
"""
tb = extract_tb(excinfo.tb)
try:
idx = [__file__ in e for e in tb].index(True)
return format_list(tb[idx + 1 :])
except ValueError:
return format_list(tb) |
Get the xonsh source path. | def source_path():
"""Get the xonsh source path."""
pwd = os.path.dirname(__file__)
return os.path.dirname(pwd) |
Initiate the Execer with a mocked nop `load_builtins` | def xonsh_execer(monkeypatch, xonsh_session):
"""Initiate the Execer with a mocked nop `load_builtins`"""
yield xonsh_session.execer |
Monkeypath sys.stderr with no ResourceWarning. | def monkeypatch_stderr(monkeypatch):
"""Monkeypath sys.stderr with no ResourceWarning."""
with open(os.devnull, "w") as fd:
monkeypatch.setattr(sys, "stderr", fd)
yield |
Env with values from os.environ like real session | def session_os_env():
"""Env with values from os.environ like real session"""
from xonsh.environ import Env, default_env
return Env(default_env()) |
Env with some initial values that doesn't load from os.environ | def session_env():
"""Env with some initial values that doesn't load from os.environ"""
from xonsh.environ import Env
initial_vars = {
"UPDATE_OS_ENVIRON": False,
"XONSH_DEBUG": 1,
"XONSH_COLOR_STYLE": "default",
"VC_BRANCH_TIMEOUT": 1,
"XONSH_ENCODING": "utf-8",
"XONSH_ENCODING_ERRORS": "strict",
"COMMANDS_CACHE_SAVE_INTERMEDIATE": False,
}
env = Env(initial_vars)
return env |
A mutable copy of Original session_os_env | def os_env(session_os_env):
"""A mutable copy of Original session_os_env"""
return copy_env(session_os_env) |
a mutable copy of session_env | def env(tmp_path, session_env):
"""a mutable copy of session_env"""
env_copy = copy_env(session_env)
initial_vars = {"XONSH_DATA_DIR": str(tmp_path), "XONSH_CACHE_DIR": str(tmp_path)}
env_copy.update(initial_vars)
return env_copy |
a fixture to use where XonshSession is fully loaded without any mocks | def xonsh_session(xonsh_events, session_execer, os_env, monkeypatch):
"""a fixture to use where XonshSession is fully loaded without any mocks"""
XSH.load(
ctx={},
execer=session_execer,
env=os_env,
)
yield XSH
XSH.unload()
get_tasks().clear() |
Mock out most of the builtins xonsh attributes. | def mock_xonsh_session(monkeypatch, xonsh_events, xonsh_session, env):
"""Mock out most of the builtins xonsh attributes."""
# make sure that all other fixtures call this mock only one time
session = []
def factory(*attrs_to_skip: str):
"""
Parameters
----------
attrs_to_skip
do not mock the given attributes
Returns
-------
XonshSession
with most of the attributes mocked out
"""
if session:
raise RuntimeError("The factory should be called only once per test")
aliases = None if "aliases" in attrs_to_skip else Aliases()
for attr, val in [
("env", env),
("shell", DummyShell()),
("help", lambda x: x),
("exit", False),
("history", DummyHistory()),
(
"commands_cache",
commands_cache.CommandsCache(env, aliases),
), # since env,aliases change , patch cmds-cache
# ("subproc_captured", sp),
("subproc_uncaptured", sp),
("subproc_captured_stdout", sp),
("subproc_captured_inject", sp),
("subproc_captured_object", sp),
("subproc_captured_hiddenobject", sp),
]:
if attr in attrs_to_skip:
continue
monkeypatch.setattr(xonsh_session, attr, val)
for attr, val in [
("evalx", eval),
("execx", None),
("compilex", None),
# Unlike all the other stuff, this has to refer to the "real" one because all modules that would
# be firing events on the global instance.
("events", xonsh_events),
]:
# attributes to builtins are dynamicProxy and should pickup the following
monkeypatch.setattr(xonsh_session.builtins, attr, val)
session.append(xonsh_session)
return xonsh_session
yield factory
session.clear() |
Mock out most of the builtins xonsh attributes. | def xession(mock_xonsh_session) -> XonshSession:
"""Mock out most of the builtins xonsh attributes."""
return mock_xonsh_session() |
Xonsh mock-session with default set of aliases | def xsh_with_aliases(mock_xonsh_session) -> XonshSession:
"""Xonsh mock-session with default set of aliases"""
return mock_xonsh_session("aliases") |
Xonsh mock-session with os.environ | def xsh_with_env(mock_xonsh_session) -> XonshSession:
"""Xonsh mock-session with os.environ"""
return mock_xonsh_session("env") |
Helper function to run completer and parse the results as set of strings | def check_completer(completer_obj):
"""Helper function to run completer and parse the results as set of strings"""
completer = completer_obj
def _factory(
line: str, prefix: "None|str" = "", send_original=False, complete_fn=None
):
"""
Parameters
----------
line
prefix
send_original
if True, return the original result from the completer (e.g. RichCompletion instances ...)
complete_fn
if given, use that to get the completions
Returns
-------
completions as set of string if not send
"""
if prefix is not None:
line += " " + prefix
if complete_fn is None:
completions, _ = completer.complete_line(line)
else:
ctx = completer_obj.parse(line)
out = complete_fn(ctx)
if isinstance(out, tuple):
completions = out[0]
else:
completions = out
values = {getattr(i, "value", i).strip() for i in completions}
if send_original:
# just return the bare completions without appended-space for easier assertions
return values, completions
return values
return _factory |
Turns config dict into xonsh code (str). | def config_to_xonsh(
config: dict,
prefix="# XONSH WEBCONFIG START",
current_lines: "tp.Iterable[str]" = (),
suffix="# XONSH WEBCONFIG END",
):
"""Turns config dict into xonsh code (str)."""
yield prefix
renderers = set(RENDERERS)
for existing in current_lines:
if start := next(filter(lambda x: existing.startswith(x), renderers), None):
renderers.remove(start)
key, func = RENDERERS[start]
if value := config.get(key):
yield start + func(value, existing.strip(start))
else:
yield existing
else:
yield existing
for start in renderers:
key, func = RENDERERS[start]
if value := config.get(key):
yield start + func(value, "")
yield suffix |
Places a config dict into the xonshrc. | def insert_into_xonshrc(
config: dict,
xonshrc=None,
prefix="# XONSH WEBCONFIG START",
suffix="# XONSH WEBCONFIG END",
):
"""Places a config dict into the xonshrc."""
if xonshrc is None:
xonshrc = RC_FILE
current_lines = []
# get current contents
fname = os.path.expanduser(xonshrc)
if os.path.isfile(fname):
with open(fname) as f:
s = f.read()
before, _, s = s.partition(prefix)
current, _, after = s.partition(suffix)
current_lines = current.strip().splitlines(keepends=False)
else:
before = after = ""
dname = os.path.dirname(fname)
if dname:
os.makedirs(dname, exist_ok=True)
# compute new values
lines = config_to_xonsh(
config,
prefix=prefix,
current_lines=current_lines,
suffix=suffix,
)
# write out the file
with open(fname, "w", encoding="utf-8") as f:
f.write(before + re.sub(r"\\r", "", "\n".join(lines)) + after)
return fname |
standalone entry point for webconfig. | def main(browser=False):
"""standalone entry point for webconfig."""
from xonsh.main import setup
setup()
serve(browser) |
A cat command for xonsh. | def cat(args, stdin, stdout, stderr):
"""A cat command for xonsh."""
opts = _cat_parse_args(args)
if opts is None:
print(CAT_HELP_STR, file=stdout)
return 0
line_count = 1
errors = False
if len(args) == 0:
args = ["-"]
for i in args:
o = _cat_single_file(opts, i, stdin, stdout, stderr, line_count)
if o is None:
return -1
_e, line_count = o
errors = _e or errors
return int(errors) |
A simple echo command. | def echo(args, stdin, stdout, stderr):
"""A simple echo command."""
opts = _echo_parse_args(args)
if opts is None:
return
if opts["help"]:
print(ECHO_HELP, file=stdout)
return 0
ender = opts["end"]
args = map(str, args)
if opts["escapes"]:
args = map(lambda x: x.encode().decode("unicode_escape"), args)
print(*args, end=ender, file=stdout) |
A pwd implementation | def pwd(args, stdin, stdout, stderr):
"""A pwd implementation"""
e = XSH.env["PWD"]
if "-h" in args or "--help" in args:
print(PWD_HELP, file=stdout)
return 0
if "-P" in args:
e = os.path.realpath(e)
print(e, file=stdout)
return 0 |
A tee command for xonsh. | def tee(args, stdin, stdout, stderr):
"""A tee command for xonsh."""
mode = "w"
if "-a" in args:
args.remove("-a")
mode = "a"
if "--append" in args:
args.remove("--append")
mode = "a"
if "--help" in args:
print(TEE_HELP, file=stdout)
return 0
if stdin is None:
msg = "tee was not piped stdin, must have input stream to read from."
print(msg, file=stderr)
return 1
errors = False
files = []
for i in args:
if i == "-":
files.append(stdout)
else:
try:
files.append(open(i, mode))
except:
print(f"tee: failed to open {i}", file=stderr)
errors = True
files.append(stdout)
while True:
r = stdin.read(1024)
if r == "":
break
for i in files:
i.write(r)
for i in files:
if i != stdout:
i.close()
return int(errors) |
A tty command for xonsh. | def tty(args, stdin, stdout, stderr):
"""A tty command for xonsh."""
if "--help" in args:
print(TTY_HELP, file=stdout)
return 0
silent = False
for i in ("-s", "--silent", "--quiet"):
if i in args:
silent = True
args.remove(i)
if len(args) > 0:
if not silent:
for i in args:
print(f"tty: Invalid option: {i}", file=stderr)
print("Try 'tty --help' for more information", file=stderr)
return 2
try:
fd = stdin.fileno()
except:
fd = sys.stdin.fileno()
if not os.isatty(fd):
if not silent:
print("not a tty", file=stdout)
return 1
if not silent:
try:
print(os.ttyname(fd), file=stdout)
except:
return 3
return 0 |
Set resource limit | def _ul_set(res, soft=None, hard=None, **kwargs):
"""Set resource limit"""
if soft == "unlimited":
soft = resource.RLIM_INFINITY
if hard == "unlimited":
hard = resource.RLIM_INFINITY
if soft is None or hard is None or isinstance(soft, str) or isinstance(hard, str):
current_soft, current_hard = resource.getrlimit(res)
if soft in (None, "soft"):
soft = current_soft
elif soft == "hard":
soft = current_hard
if hard in (None, "hard"):
hard = current_hard
elif hard == "soft":
hard = current_soft
resource.setrlimit(res, (soft, hard)) |
Print out resource limit | def _ul_show(res, res_type, desc, unit, opt, long=False, **kwargs):
"""Print out resource limit"""
limit = resource.getrlimit(res)[1 if res_type == _UL_HARD else 0]
str_limit = "unlimited" if limit == resource.RLIM_INFINITY else str(limit)
# format line to mimic bash
if long:
pre = "{:21} {:>14} ".format(
desc, "({}{})".format((unit + ", -") if unit else "-", opt)
)
else:
pre = ""
print(f"{pre}{str_limit}", file=kwargs["stdout"]) |
Create new and append it to the actions list | def _ul_add_action(actions, opt, res_type, stderr):
"""Create new and append it to the actions list"""
r = _UL_RES[opt]
if r[0] is None:
_ul_unsupported_opt(opt, stderr)
return False
# we always assume the 'show' action to be requested and eventually change it later
actions.append(
[
_ul_show,
{"res": r[0], "res_type": res_type, "desc": r[3], "unit": r[4], "opt": opt},
]
)
return True |
Add all supported resources; handles (-a, --all) | def _ul_add_all_actions(actions, res_type, stderr):
"""Add all supported resources; handles (-a, --all)"""
for k in _UL_RES:
if _UL_RES[k][0] is None:
continue
_ul_add_action(actions, k, res_type, stderr) |
Print an invalid option message to stderr | def _ul_unknown_opt(arg, stderr):
"""Print an invalid option message to stderr"""
print(f"ulimit: Invalid option: {arg}", file=stderr, flush=True)
print("Try 'ulimit --help' for more information", file=stderr, flush=True) |
Print an unsupported option message to stderr | def _ul_unsupported_opt(opt, stderr):
"""Print an unsupported option message to stderr"""
print(f"ulimit: Unsupported option: -{opt}", file=stderr, flush=True)
print("Try 'ulimit --help' for more information", file=stderr, flush=True) |
Parse arguments and return a list of actions to be performed | def _ul_parse_args(args, stderr):
"""Parse arguments and return a list of actions to be performed"""
if len(args) == 1 and args[0] in ("-h", "--help"):
return (True, [])
long_opts = {}
for k in _UL_RES:
long_opts[_UL_RES[k][1]] = k
actions = []
# mimic bash and default to 'soft' limits
res_type = _UL_SOFT
for arg in args:
if arg in long_opts:
opt = long_opts[arg]
if not _ul_add_action(actions, opt, res_type, stderr):
return (False, [])
elif arg == "--all":
_ul_add_all_actions(actions, res_type, stderr)
elif arg == "--soft":
res_type = _UL_SOFT
elif arg == "--hard":
res_type = _UL_HARD
elif arg[0] == "-":
for opt in arg[1:]:
if opt == "a":
_ul_add_all_actions(actions, res_type, stderr)
elif opt in _UL_RES:
if not _ul_add_action(actions, opt, res_type, stderr):
return (False, [])
elif opt == "S":
res_type = _UL_SOFT
elif opt == "H":
res_type = _UL_HARD
else:
_ul_unknown_opt(arg, stderr)
return (False, [])
# this is a request to change limit selected by the previous argument; change the last action to _ul_set
elif arg.isnumeric() or (arg in ("unlimited", "hard", "soft")):
if arg.isnumeric():
limit = int(arg)
else:
limit = arg
# mimic bash and default to '-f' if no resource was specified
if not actions:
if not _ul_add_action(actions, "f", res_type, stderr):
return (False, [])
a = actions[-1]
a[0] = _ul_set
a[1]["soft"] = limit if (_UL_SOFT & res_type) else None
a[1]["hard"] = limit if (_UL_HARD & res_type) else None
else:
_ul_unknown_opt(arg, stderr)
return (False, [])
else:
# mimic bash and default to '-f' if no resource was specified
if not actions:
if not _ul_add_action(actions, "f", res_type, stderr):
return (False, [])
return (True, actions) |
Print out our help | def _ul_show_usage(file):
"""Print out our help"""
print("Usage: ulimit [-h] [-SH] [-a] [-", end="", file=file)
print("".join([k for k in _UL_RES]), end="", file=file)
print("] [LIMIT]\n", file=file)
print(
"""Set or get shell resource limits.
Provides control over the resources available to the shell and processes it
creates, on systems that allow such control.
Options:""",
file=file,
)
print("-h, --help\n show this help message and exit", file=file)
print(
"-S, --soft\n use the 'soft' resource limit for the following arguments",
file=file,
)
print(
"-H, --hard\n use the 'hard' resource limit for the following arguments (default)",
file=file,
)
print("-a, --all\n show all current limits", file=file)
for k in _UL_RES:
r = _UL_RES[k]
opts = f"-{k}, {r[1]}"
if r[0] is None:
opts += " (unsupported)"
print(f"{opts}\n {r[2]}", file=file)
print(
"""
Not all options are available on all platforms.
If LIMIT is given, it is the new value of the specified resource; the special
LIMIT values `soft', `hard', and `unlimited' stand for the current soft limit,
the current hard limit, and no limit, respectively. Otherwise, the current
value of the specified resource is printed. If no option is given, then -f is
assumed.
""",
file=file,
) |
An ulimit implementation | def ulimit(args, stdin, stdout, stderr):
"""An ulimit implementation"""
rc, actions = _ul_parse_args(args, stderr)
# could not parse arguments; message already printed to stderr
if not rc:
return 1
# args OK, but nothing to do; print help
elif not actions:
_ul_show_usage(stdout)
return 0
# if there's more than one resource to be printed, use the long format
long = len([a for a in actions if a[0] == _ul_show]) > 1
try:
for fn, args in actions:
fn(stdout=stdout, long=long, **args)
return 0
except:
print_exception()
return 2 |
Separate a given integer into its three components | def get_oct_digits(mode):
"""
Separate a given integer into its three components
"""
if not 0 <= mode <= 0o777:
raise ValueError("expected a value between 000 and 777")
return {"u": (mode & 0o700) >> 6, "g": (mode & 0o070) >> 3, "o": mode & 0o007} |
Given a single octal digit, return the appropriate string representation.
For example, 6 becomes "rw". | def get_symbolic_rep_single(digit):
"""
Given a single octal digit, return the appropriate string representation.
For example, 6 becomes "rw".
"""
o = ""
for sym in "rwx":
num = name_to_value[sym]
if digit & num:
o += sym
digit -= num
return o |
Given a string representation, return the appropriate octal digit.
For example, "rw" becomes 6. | def get_numeric_rep_single(rep):
"""
Given a string representation, return the appropriate octal digit.
For example, "rw" becomes 6.
"""
o = 0
for sym in set(rep):
o += name_to_value[sym]
return o |
This version of uname was written in Python for the xonsh project: https://xon.sh
Based on uname from GNU coreutils: http://www.gnu.org/software/coreutils/
Parameters
----------
all : -a, --all
print all information, in the following order, except omit -p and -i if unknown
kernel_name : -s, --kernel-name
print the kernel name
node_name : -n, --nodename
print the network node hostname
kernel_release : -r, --kernel-release
print the kernel release
kernel_version : -v, --kernel-version
print the kernel version
machine : -m, --machine
print the machine hardware name
processor : -p, --processor
print the processor type (non-portable)
hardware_platform : -i, --hardware-platform
print the hardware platform (non-portable)
operating_system : -o, --operating-system
print the operating system | def uname_fn(
all=False,
kernel_name=False,
node_name=False,
kernel_release=False,
kernel_version=False,
machine=False,
processor=False,
hardware_platform=False,
operating_system=False,
):
"""This version of uname was written in Python for the xonsh project: https://xon.sh
Based on uname from GNU coreutils: http://www.gnu.org/software/coreutils/
Parameters
----------
all : -a, --all
print all information, in the following order, except omit -p and -i if unknown
kernel_name : -s, --kernel-name
print the kernel name
node_name : -n, --nodename
print the network node hostname
kernel_release : -r, --kernel-release
print the kernel release
kernel_version : -v, --kernel-version
print the kernel version
machine : -m, --machine
print the machine hardware name
processor : -p, --processor
print the processor type (non-portable)
hardware_platform : -i, --hardware-platform
print the hardware platform (non-portable)
operating_system : -o, --operating-system
print the operating system
"""
info = platform.uname()
def gen_lines():
if all or node_name:
yield info.node
if all or kernel_release:
yield info.release
if all or kernel_version:
yield info.version
if all or machine:
yield info.machine
if all or processor:
yield info.processor or "unknown"
if all or hardware_platform:
yield "unknown"
if all or operating_system:
yield sys.platform
lines = list(gen_lines())
if all or kernel_name or (not lines):
lines.insert(0, info.system)
line = " ".join(lines)
return line |
Returns the uptime on mac / darwin. | def _boot_time_osx() -> "float|None":
"""Returns the uptime on mac / darwin."""
bt = xlimps.macutils.sysctlbyname(b"kern.boottime", return_str=False)
if len(bt) == 4:
bt = struct.unpack_from("@hh", bt)
elif len(bt) == 8:
bt = struct.unpack_from("@ii", bt)
elif len(bt) == 16:
bt = struct.unpack_from("@qq", bt)
else:
raise ValueError("length of boot time not understood: " + repr(bt))
bt = bt[0] + bt[1] * 1e-6
if bt == 0.0:
return None
return bt |
A way to figure out the boot time directly on Linux. | def _boot_time_linux() -> "float|None":
"""A way to figure out the boot time directly on Linux."""
# from the answer here -
# https://stackoverflow.com/questions/42471475/fastest-way-to-get-system-uptime-in-python-in-linux
bt_flag = getattr(time, "CLOCK_BOOTTIME", None)
if bt_flag is not None:
return time.clock_gettime(bt_flag)
try:
with open("/proc/stat") as f:
for line in f:
if line.startswith("btime"):
return float(line.split()[1])
except (OSError, IndexError):
return None |
Returns uptime in seconds or None, on AmigaOS. | def _boot_time_amiga() -> "float|None":
"""Returns uptime in seconds or None, on AmigaOS."""
try:
return os.stat("RAM:").st_ctime
except (NameError, OSError):
return None |
Returns uptime in seconds on None, on BeOS/Haiku. | def _boot_time_beos() -> "float|None":
"""Returns uptime in seconds on None, on BeOS/Haiku."""
if not hasattr(xp.LIBC, "system_time"):
return None
xp.LIBC.system_time.restype = ctypes.c_int64
return time.time() - (xp.LIBC.system_time() / 1000000.0) |
Returns uptime in seconds or None, on BSD (including OS X). | def _boot_time_bsd() -> "float|None":
"""Returns uptime in seconds or None, on BSD (including OS X)."""
# https://docs.python.org/3/library/time.html#time.CLOCK_UPTIME
with contextlib.suppress(Exception):
ut_flag = getattr(time, "CLOCK_UPTIME", None)
if ut_flag is not None:
ut = time.clock_gettime(ut_flag)
return time.time() - ut
if not hasattr(xp.LIBC, "sysctlbyname"):
# Not BSD.
return None
# Determine how much space we need for the response.
sz = ctypes.c_uint(0)
xp.LIBC.sysctlbyname(b"kern.boottime", None, ctypes.byref(sz), None, 0)
if sz.value != struct.calcsize("@LL"):
# Unexpected, let's give up.
return None
# For real now.
buf = ctypes.create_string_buffer(sz.value)
xp.LIBC.sysctlbyname(b"kern.boottime", buf, ctypes.byref(sz), None, 0)
sec, usec = struct.unpack_from("@LL", buf.raw)
# OS X disagrees what that second value is.
if usec > 1000000:
usec = 0.0
return sec + usec / 1000000.0 |
Returns uptime in seconds or None, on MINIX. | def _boot_time_minix():
"""Returns uptime in seconds or None, on MINIX."""
try:
with open("/proc/uptime") as f:
up = float(f.read())
return time.time() - up
except (OSError, ValueError):
return None |
Returns uptime in seconds or None, on Plan 9. | def _boot_time_plan9():
"""Returns uptime in seconds or None, on Plan 9."""
# Apparently Plan 9 only has Python 2.2, which I'm not prepared to
# support. Maybe some Linuxes implement /dev/time, though, someone was
# talking about it somewhere.
try:
# The time file holds one 32-bit number representing the sec-
# onds since start of epoch and three 64-bit numbers, repre-
# senting nanoseconds since start of epoch, clock ticks, and
# clock frequency.
# -- cons(3)
with open("/dev/time") as f:
s, ns, ct, cf = f.read().split()
return time.time() - (float(ct) / float(cf))
except (OSError, ValueError):
return None |
Returns uptime in seconds or None, on Solaris. | def _boot_time_solaris():
"""Returns uptime in seconds or None, on Solaris."""
try:
kstat = ctypes.CDLL("libkstat.so")
except (AttributeError, OSError):
return None
_BOOTTIME = None
# kstat doesn't have uptime, but it does have boot time.
# Unfortunately, getting at it isn't perfectly straightforward.
# First, let's pretend to be kstat.h
# Constant
KSTAT_STRLEN = 31 # According to every kstat.h I could find.
# Data structures
class anon_union(ctypes.Union):
# The ``value'' union in kstat_named_t actually has a bunch more
# members, but we're only using it for boot_time, so we only need
# the padding and the one we're actually using.
_fields_ = [("c", ctypes.c_char * 16), ("time", ctypes.c_int)]
class kstat_named_t(ctypes.Structure):
_fields_ = [
("name", ctypes.c_char * KSTAT_STRLEN),
("data_type", ctypes.c_char),
("value", anon_union),
]
# Function signatures
kstat.kstat_open.restype = ctypes.c_void_p
kstat.kstat_lookup.restype = ctypes.c_void_p
kstat.kstat_lookup.argtypes = [
ctypes.c_void_p,
ctypes.c_char_p,
ctypes.c_int,
ctypes.c_char_p,
]
kstat.kstat_read.restype = ctypes.c_int
kstat.kstat_read.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]
kstat.kstat_data_lookup.restype = ctypes.POINTER(kstat_named_t)
kstat.kstat_data_lookup.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
# Now, let's do something useful.
# Initialise kstat control structure.
kc = kstat.kstat_open()
if not kc:
return None
# We're looking for unix:0:system_misc:boot_time.
ksp = kstat.kstat_lookup(kc, "unix", 0, "system_misc")
if ksp and kstat.kstat_read(kc, ksp, None) != -1:
data = kstat.kstat_data_lookup(ksp, "boot_time")
if data:
_BOOTTIME = data.contents.value.time
# Clean-up.
kstat.kstat_close(kc)
return _BOOTTIME |
Returns uptime in seconds or None, on Syllable. | def _boot_time_syllable():
"""Returns uptime in seconds or None, on Syllable."""
try:
return os.stat("/dev/pty/mst/pty0").st_mtime
except (NameError, OSError):
return None |
Returns uptime in seconds or None, on Windows. Warning: may return
incorrect answers after 49.7 days on versions older than Vista. | def _boot_time_windows():
"""
Returns uptime in seconds or None, on Windows. Warning: may return
incorrect answers after 49.7 days on versions older than Vista.
"""
uptime = None
if hasattr(xp.LIBC, "GetTickCount64"):
# Vista/Server 2008 or later.
xp.LIBC.GetTickCount64.restype = ctypes.c_uint64
uptime = xp.LIBC.GetTickCount64() / 1000.0
if hasattr(xp.LIBC, "GetTickCount"):
# WinCE and Win2k or later; gives wrong answers after 49.7 days.
xp.LIBC.GetTickCount.restype = ctypes.c_uint32
uptime = xp.LIBC.GetTickCount() / 1000.0
if uptime:
return time.time() - uptime
return None |
Returns uptime in seconds if even remotely possible, or None if not. | def uptime(args):
"""Returns uptime in seconds if even remotely possible, or None if not."""
bt = boottime()
return str(time.time() - bt) |
Returns boot time if remotely possible, or None if not. | def boottime() -> "float":
"""Returns boot time if remotely possible, or None if not."""
func = _get_boot_time_func()
btime = func()
if btime is None:
return _boot_time_monotonic()
return btime |
A simple argument handler for xoreutils. | def arg_handler(args, out, short, key, val, long=None):
"""A simple argument handler for xoreutils."""
if short in args:
args.remove(short)
if isinstance(key, (list, tuple)):
for k in key:
out[k] = val
else:
out[key] = val
if long is not None and long in args:
args.remove(long)
if isinstance(key, (list, tuple)):
for k in key:
out[k] = val
else:
out[key] = val |
Print the object. | def print_global_object(arg, stdout):
"""Print the object."""
obj = XSH.ctx.get(arg)
print(f"global object of {type(obj)}", file=stdout) |
Print the name and path of the command. | def print_path(abs_name, from_where, stdout, verbose=False, captured=False):
"""Print the name and path of the command."""
if xp.ON_WINDOWS:
# Use list dir to get correct case for the filename
# i.e. windows is case insensitive but case preserving
p, f = os.path.split(abs_name)
f = next(s.name for s in os.scandir(p) if s.name.lower() == f.lower())
abs_name = os.path.join(p, f)
if XSH.env.get("FORCE_POSIX_PATHS", False):
abs_name.replace(os.sep, os.altsep)
if verbose:
print(f"{abs_name} ({from_where})", file=stdout)
else:
end = "" if captured else "\n"
print(abs_name, end=end, file=stdout) |
Print the alias. | def print_alias(arg, stdout, verbose=False):
"""Print the alias."""
alias = XSH.aliases[arg]
if not verbose:
if not callable(alias):
print(" ".join(alias), file=stdout)
elif isinstance(alias, xonsh.aliases.ExecAlias):
print(alias.src, file=stdout)
else:
print(alias, file=stdout)
else:
print(
f"aliases['{arg}'] = {alias}",
flush=True,
file=stdout,
)
if callable(alias) and not isinstance(alias, xonsh.aliases.ExecAlias):
XSH.superhelp(alias) |
Checks if each arguments is a xonsh aliases, then if it's an executable,
then finally return an error code equal to the number of misses.
If '-a' flag is passed, run both to return both `xonsh` match and
`which` match. | def which(args, stdin=None, stdout=None, stderr=None, spec=None):
"""
Checks if each arguments is a xonsh aliases, then if it's an executable,
then finally return an error code equal to the number of misses.
If '-a' flag is passed, run both to return both `xonsh` match and
`which` match.
"""
parser = _which_create_parser()
if len(args) == 0:
parser.print_usage(file=stderr)
return -1
pargs = parser.parse_args(args)
verbose = pargs.verbose or pargs.all
if spec is not None:
captured = spec.captured in xpp.STDOUT_CAPTURE_KINDS
else:
captured = False
if pargs.plain:
verbose = False
if xp.ON_WINDOWS:
if pargs.exts:
exts = pargs.exts
else:
exts = XSH.env["PATHEXT"]
else:
exts = None
failures = []
for arg in pargs.args:
nmatches = 0
if pargs.all and arg in XSH.ctx:
print_global_object(arg, stdout)
nmatches += 1
if arg in XSH.aliases and not pargs.skip:
print_alias(arg, stdout, verbose)
nmatches += 1
if not pargs.all:
continue
# which.whichgen gives the nicest 'verbose' output if PATH is taken
# from os.environ so we temporarily override it with
# __xosnh_env__['PATH']
original_os_path = xp.os_environ["PATH"]
xp.os_environ["PATH"] = XSH.env.detype()["PATH"]
matches = _which.whichgen(arg, exts=exts, verbose=verbose)
for match in matches:
if match is None:
continue
abs_name, from_where = match
print_path(abs_name, from_where, stdout, verbose, captured)
nmatches += 1
if not pargs.all:
break
xp.os_environ["PATH"] = original_os_path
if not nmatches:
failures.append(arg)
if len(failures) == 0:
return 0
else:
print("{} not in ".format(", ".join(failures)), file=stderr, end="")
if pargs.all:
print("globals or ", file=stderr, end="")
print("$PATH", file=stderr, end="")
if not pargs.skip:
print(" or xonsh.builtins.aliases", file=stderr, end="")
print("", file=stderr, end="\n")
return len(failures) |
A yes command. | def yes(args, stdin, stdout, stderr):
"""A yes command."""
if "--help" in args:
print(YES_HELP, file=stdout)
return 0
to_print = ["y"] if len(args) == 0 else [str(i) for i in args]
while True:
print(*to_print, file=stdout)
return 0 |
Windows allow application paths to be registered in the registry. | def _getRegisteredExecutable(exeName):
"""Windows allow application paths to be registered in the registry."""
registered = None
if sys.platform.startswith("win"):
if os.path.splitext(exeName)[1].lower() != ".exe":
exeName += ".exe"
try:
import winreg as _winreg
except ImportError:
import _winreg
try:
key = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\" + exeName
value = _winreg.QueryValue(_winreg.HKEY_LOCAL_MACHINE, key)
registered = (value, "from HKLM\\" + key)
except _winreg.error:
pass
if registered and not os.path.exists(registered[0]):
registered = None
return registered |
Cull inappropriate matches. Possible reasons:
- a duplicate of a previous match
- not a disk file
- not executable (non-Windows)
If 'potential' is approved it is returned and added to 'matches'.
Otherwise, None is returned. | def _cull(potential, matches, verbose=0):
"""Cull inappropriate matches. Possible reasons:
- a duplicate of a previous match
- not a disk file
- not executable (non-Windows)
If 'potential' is approved it is returned and added to 'matches'.
Otherwise, None is returned.
"""
for match in matches: # don't yield duplicates
if _samefile(potential[0], match[0]):
if verbose:
sys.stderr.write("duplicate: {} ({})\n".format(*potential))
return None
else:
if not stat.S_ISREG(os.stat(potential[0]).st_mode):
if verbose:
sys.stderr.write("not a regular file: {} ({})\n".format(*potential))
elif sys.platform != "win32" and not os.access(potential[0], os.X_OK):
if verbose:
sys.stderr.write("no executable access: {} ({})\n".format(*potential))
else:
matches.append(potential)
return potential |
Return a generator of full paths to the given command.
"command" is a the name of the executable to search for.
"path" is an optional alternate path list to search. The default it
to use the PATH environment variable.
"verbose", if true, will cause a 2-tuple to be returned for each
match. The second element is a textual description of where the
match was found.
"exts" optionally allows one to specify a list of extensions to use
instead of the standard list for this system. This can
effectively be used as an optimization to, for example, avoid
stat's of "foo.vbs" when searching for "foo" and you know it is
not a VisualBasic script but ".vbs" is on PATHEXT. This option
is only supported on Windows.
This method returns a generator which yields tuples of the form (<path to
command>, <where path found>). | def whichgen(command, path=None, verbose=0, exts=None):
"""Return a generator of full paths to the given command.
"command" is a the name of the executable to search for.
"path" is an optional alternate path list to search. The default it
to use the PATH environment variable.
"verbose", if true, will cause a 2-tuple to be returned for each
match. The second element is a textual description of where the
match was found.
"exts" optionally allows one to specify a list of extensions to use
instead of the standard list for this system. This can
effectively be used as an optimization to, for example, avoid
stat's of "foo.vbs" when searching for "foo" and you know it is
not a VisualBasic script but ".vbs" is on PATHEXT. This option
is only supported on Windows.
This method returns a generator which yields tuples of the form (<path to
command>, <where path found>).
"""
matches = []
if path is None:
usingGivenPath = 0
path = os.environ.get("PATH", "").split(os.pathsep)
if sys.platform.startswith("win"):
path.insert(0, os.curdir) # implied by Windows shell
else:
usingGivenPath = 1
# Windows has the concept of a list of extensions (PATHEXT env var).
if sys.platform.startswith("win"):
if exts is None:
exts = XSH.env["PATHEXT"]
# If '.exe' is not in exts then obviously this is Win9x and
# or a bogus PATHEXT, then use a reasonable default.
for ext in exts:
if ext.lower() == ".exe":
break
else:
exts = [".COM", ".EXE", ".BAT", ".CMD"]
elif not isinstance(exts, cabc.Sequence):
raise TypeError("'exts' argument must be a sequence or None")
else:
if exts is not None:
raise WhichError(
f"'exts' argument is not supported on platform {sys.platform!r}"
)
exts = []
# File name cannot have path separators because PATH lookup does not
# work that way.
if os.sep in command or os.altsep and os.altsep in command:
if os.path.exists(command):
match = _cull((command, "explicit path given"), matches, verbose)
yield match
else:
for i in range(len(path)):
dirName = path[i]
# On windows the dirName *could* be quoted, drop the quotes
if (
sys.platform.startswith("win")
and len(dirName) >= 2
and dirName[0] == '"'
and dirName[-1] == '"'
):
dirName = dirName[1:-1]
for ext in [""] + exts:
absName = os.path.abspath(
os.path.normpath(os.path.join(dirName, command + ext))
)
if os.path.isfile(absName):
if usingGivenPath:
fromWhere = "from given path element %d" % i
elif not sys.platform.startswith("win"):
fromWhere = "from PATH element %d" % i
elif i == 0:
fromWhere = "from current directory"
else:
fromWhere = "from PATH element %d" % (i - 1)
match = _cull((absName, fromWhere), matches, verbose)
if match:
yield match
match = _getRegisteredExecutable(command)
if match is not None:
match = _cull(match, matches, verbose)
if match:
yield match |
Return the full path to the first match of the given command on
the path.
"command" is a the name of the executable to search for.
"path" is an optional alternate path list to search. The default it
to use the PATH environment variable.
"verbose", if true, will cause a 2-tuple to be returned. The second
element is a textual description of where the match was found.
"exts" optionally allows one to specify a list of extensions to use
instead of the standard list for this system. This can
effectively be used as an optimization to, for example, avoid
stat's of "foo.vbs" when searching for "foo" and you know it is
not a VisualBasic script but ".vbs" is on PATHEXT. This option
is only supported on Windows.
If no match is found for the command, a WhichError is raised. | def which(command, path=None, verbose=0, exts=None):
"""Return the full path to the first match of the given command on
the path.
"command" is a the name of the executable to search for.
"path" is an optional alternate path list to search. The default it
to use the PATH environment variable.
"verbose", if true, will cause a 2-tuple to be returned. The second
element is a textual description of where the match was found.
"exts" optionally allows one to specify a list of extensions to use
instead of the standard list for this system. This can
effectively be used as an optimization to, for example, avoid
stat's of "foo.vbs" when searching for "foo" and you know it is
not a VisualBasic script but ".vbs" is on PATHEXT. This option
is only supported on Windows.
If no match is found for the command, a WhichError is raised.
"""
try:
absName, fromWhere = next(whichgen(command, path, verbose, exts))
except StopIteration as ex:
raise WhichError(f"Could not find {command!r} on the path.") from ex
if verbose:
return absName, fromWhere
else:
return absName |
Return a list of full paths to all matches of the given command
on the path.
"command" is a the name of the executable to search for.
"path" is an optional alternate path list to search. The default it
to use the PATH environment variable.
"verbose", if true, will cause a 2-tuple to be returned for each
match. The second element is a textual description of where the
match was found.
"exts" optionally allows one to specify a list of extensions to use
instead of the standard list for this system. This can
effectively be used as an optimization to, for example, avoid
stat's of "foo.vbs" when searching for "foo" and you know it is
not a VisualBasic script but ".vbs" is on PATHEXT. This option
is only supported on Windows. | def whichall(command, path=None, verbose=0, exts=None):
"""Return a list of full paths to all matches of the given command
on the path.
"command" is a the name of the executable to search for.
"path" is an optional alternate path list to search. The default it
to use the PATH environment variable.
"verbose", if true, will cause a 2-tuple to be returned for each
match. The second element is a textual description of where the
match was found.
"exts" optionally allows one to specify a list of extensions to use
instead of the standard list for this system. This can
effectively be used as an optimization to, for example, avoid
stat's of "foo.vbs" when searching for "foo" and you know it is
not a VisualBasic script but ".vbs" is on PATHEXT. This option
is only supported on Windows.
"""
if verbose:
return list(whichgen(command, path, verbose, exts))
else:
return list(absName for absName, _ in whichgen(command, path, verbose, exts)) |
Scans through a string for substrings matched some patterns (first-subgroups only).
Args:
text: A string to be scanned.
patterns: Arbitrary number of regex patterns.
Returns:
When only one pattern is given, returns a string (None if no match found).
When more than one pattern are given, returns a list of strings ([] if no match found). | def match1(text, *patterns):
"""Scans through a string for substrings matched some patterns (first-subgroups only).
Args:
text: A string to be scanned.
patterns: Arbitrary number of regex patterns.
Returns:
When only one pattern is given, returns a string (None if no match found).
When more than one pattern are given, returns a list of strings ([] if no match found).
"""
if len(patterns) == 1:
pattern = patterns[0]
match = re.search(pattern, text)
if match:
return match.group(1)
else:
return None
else:
ret = []
for pattern in patterns:
match = re.search(pattern, text)
if match:
ret.append(match.group(1))
return ret |
Scans through a string for substrings matched some patterns.
Args:
text: A string to be scanned.
patterns: a list of regex pattern.
Returns:
a list if matched. empty if not. | def matchall(text, patterns):
"""Scans through a string for substrings matched some patterns.
Args:
text: A string to be scanned.
patterns: a list of regex pattern.
Returns:
a list if matched. empty if not.
"""
ret = []
for pattern in patterns:
match = re.findall(pattern, text)
ret += match
return ret |
Parses the query string of a URL and returns the value of a parameter.
Args:
url: A URL.
param: A string representing the name of the parameter.
Returns:
The value of the parameter. | def parse_query_param(url, param):
"""Parses the query string of a URL and returns the value of a parameter.
Args:
url: A URL.
param: A string representing the name of the parameter.
Returns:
The value of the parameter.
"""
try:
return parse.parse_qs(parse.urlparse(url).query)[param][0]
except:
return None |
Decompresses data for Content-Encoding: gzip.
| def ungzip(data):
"""Decompresses data for Content-Encoding: gzip.
"""
from io import BytesIO
import gzip
buffer = BytesIO(data)
f = gzip.GzipFile(fileobj=buffer)
return f.read() |
Decompresses data for Content-Encoding: deflate.
(the zlib compression is used.) | def undeflate(data):
"""Decompresses data for Content-Encoding: deflate.
(the zlib compression is used.)
"""
import zlib
decompressobj = zlib.decompressobj(-zlib.MAX_WBITS)
return decompressobj.decompress(data)+decompressobj.flush() |
Gets the content of a URL via sending a HTTP GET request.
Args:
url: A URL.
headers: Request headers used by the client.
decoded: Whether decode the response body using UTF-8 or the charset specified in Content-Type.
Returns:
The content as a string. | def get_content(url, headers={}, decoded=True):
"""Gets the content of a URL via sending a HTTP GET request.
Args:
url: A URL.
headers: Request headers used by the client.
decoded: Whether decode the response body using UTF-8 or the charset specified in Content-Type.
Returns:
The content as a string.
"""
logging.debug('get_content: %s' % url)
req = request.Request(url, headers=headers)
if cookies:
# NOTE: Do not use cookies.add_cookie_header(req)
# #HttpOnly_ cookies were not supported by CookieJar and MozillaCookieJar properly until python 3.10
# See also:
# - https://github.com/python/cpython/pull/17471
# - https://bugs.python.org/issue2190
# Here we add cookies to the request headers manually
cookie_strings = []
for cookie in list(cookies):
cookie_strings.append(cookie.name + '=' + cookie.value)
cookie_headers = {'Cookie': '; '.join(cookie_strings)}
req.headers.update(cookie_headers)
response = urlopen_with_retry(req)
data = response.read()
# Handle HTTP compression for gzip and deflate (zlib)
content_encoding = response.getheader('Content-Encoding')
if content_encoding == 'gzip':
data = ungzip(data)
elif content_encoding == 'deflate':
data = undeflate(data)
# Decode the response body
if decoded:
charset = match1(
response.getheader('Content-Type', ''), r'charset=([\w-]+)'
)
if charset is not None:
data = data.decode(charset, 'ignore')
else:
data = data.decode('utf-8', 'ignore')
return data |
Post the content of a URL via sending a HTTP POST request.
Args:
url: A URL.
headers: Request headers used by the client.
decoded: Whether decode the response body using UTF-8 or the charset specified in Content-Type.
Returns:
The content as a string. | def post_content(url, headers={}, post_data={}, decoded=True, **kwargs):
"""Post the content of a URL via sending a HTTP POST request.
Args:
url: A URL.
headers: Request headers used by the client.
decoded: Whether decode the response body using UTF-8 or the charset specified in Content-Type.
Returns:
The content as a string.
"""
if kwargs.get('post_data_raw'):
logging.debug('post_content: %s\npost_data_raw: %s' % (url, kwargs['post_data_raw']))
else:
logging.debug('post_content: %s\npost_data: %s' % (url, post_data))
req = request.Request(url, headers=headers)
if cookies:
# NOTE: Do not use cookies.add_cookie_header(req)
# #HttpOnly_ cookies were not supported by CookieJar and MozillaCookieJar properly until python 3.10
# See also:
# - https://github.com/python/cpython/pull/17471
# - https://bugs.python.org/issue2190
# Here we add cookies to the request headers manually
cookie_strings = []
for cookie in list(cookies):
cookie_strings.append(cookie.name + '=' + cookie.value)
cookie_headers = {'Cookie': '; '.join(cookie_strings)}
req.headers.update(cookie_headers)
if kwargs.get('post_data_raw'):
post_data_enc = bytes(kwargs['post_data_raw'], 'utf-8')
else:
post_data_enc = bytes(parse.urlencode(post_data), 'utf-8')
response = urlopen_with_retry(req, data=post_data_enc)
data = response.read()
# Handle HTTP compression for gzip and deflate (zlib)
content_encoding = response.getheader('Content-Encoding')
if content_encoding == 'gzip':
data = ungzip(data)
elif content_encoding == 'deflate':
data = undeflate(data)
# Decode the response body
if decoded:
charset = match1(
response.getheader('Content-Type'), r'charset=([\w-]+)'
)
if charset is not None:
data = data.decode(charset)
else:
data = data.decode('utf-8')
return data |
Parses host name and port number from a string.
| def parse_host(host):
"""Parses host name and port number from a string.
"""
if re.match(r'^(\d+)$', host) is not None:
return ("0.0.0.0", int(host))
if re.match(r'^(\w+)://', host) is None:
host = "//" + host
o = parse.urlparse(host)
hostname = o.hostname or "0.0.0.0"
port = o.port or 0
return (hostname, port) |
Main entry point.
you-get-dev | def main_dev(**kwargs):
"""Main entry point.
you-get-dev
"""
# Get (branch, commit) if running from a git repo.
head = git.get_head(kwargs['repo_path'])
# Get options and arguments.
try:
opts, args = getopt.getopt(sys.argv[1:], _short_options, _options)
except getopt.GetoptError as e:
log.wtf("""
[Fatal] {}.
Try '{} --help' for more options.""".format(e, script_name))
if not opts and not args:
# Display help.
print(_help)
# Enter GUI mode.
#from .gui import gui_main
#gui_main()
else:
conf = {}
for opt, arg in opts:
if opt in ('-h', '--help'):
# Display help.
print(_help)
elif opt in ('-V', '--version'):
# Display version.
log.println("you-get:", log.BOLD)
log.println(" version: {}".format(__version__))
if head is not None:
log.println(" branch: {}\n commit: {}".format(*head))
else:
log.println(" branch: {}\n commit: {}".format("(stable)", "(tag v{})".format(__version__)))
log.println(" platform: {}".format(platform.platform()))
log.println(" python: {}".format(sys.version.split('\n')[0]))
elif opt in ('-g', '--gui'):
# Run using GUI.
conf['gui'] = True
elif opt in ('-f', '--force'):
# Force download.
conf['force'] = True
elif opt in ('-l', '--playlist', '--playlists'):
# Download playlist whenever possible.
conf['playlist'] = True
if args:
if 'gui' in conf and conf['gui']:
# Enter GUI mode.
from .gui import gui_main
gui_main(*args, **conf)
else:
# Enter console mode.
from .console import console_main
console_main(*args, **conf) |
Main entry point.
you-get (legacy) | def main(**kwargs):
"""Main entry point.
you-get (legacy)
"""
from .common import main
main(**kwargs) |
Downloads CBS videos by URL.
| def cbs_download(url, output_dir='.', merge=True, info_only=False, **kwargs):
"""Downloads CBS videos by URL.
"""
html = get_content(url)
pid = match1(html, r'video\.settings\.pid\s*=\s*\'([^\']+)\'')
title = match1(html, r'video\.settings\.title\s*=\s*\"([^\"]+)\"')
theplatform_download_by_pid(pid, title, output_dir=output_dir, merge=merge, info_only=info_only) |