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.split... |
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,))... |
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... |
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 bra... |
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... |
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 ... |
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... |
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... |
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()
... |
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:
... |
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 = "{BACKGROUN... |
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_... |
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 ... | 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
... |
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 = Tr... |
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
... |
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_... |
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_... |
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
... |
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 ... |
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 lette... |
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 s... |
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 for... |
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",
... |
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_... |
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... |
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(... |
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(xo... |
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(opt... |
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:... |
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... |
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:
... |
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_sof... |
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} {:... |
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(
... |
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... |
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 t... |
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)... |
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
pri... | 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
B... |
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:
... |
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:
... |
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 = ... |
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 rep... |
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 per... |
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 =... |
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 ... |
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... |
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:
... |
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.
"""
... |
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
... |
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... |
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... | 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... |
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
elemen... | 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.
... |
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.... | 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 variab... |
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... | 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).
... |
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.finda... |
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... |
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:
... |
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... |
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 =... |
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.GetoptErro... |
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_pi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.