response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Build the lexer/parser modules.
def build_tables(): """Build the lexer/parser modules.""" print("Building lexer and parser tables.", file=sys.stderr) root_dir = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, root_dir) from xonsh.parser import Parser from xonsh.parsers.completion_context import CompletionContextParser Parser( yacc_table="parser_table", outputdir=os.path.join(root_dir, "xonsh"), yacc_debug=True, ) CompletionContextParser( yacc_table="completion_parser_table", outputdir=os.path.join(root_dir, "xonsh"), debug=True, ) sys.path.pop(0)
If install/sdist is run from a git directory (not a conda install), add a devN suffix to reported version number and write a gitignored file that holds the git hash of the current state of the repo to be queried by ``xonfig``
def dirty_version(): """ If install/sdist is run from a git directory (not a conda install), add a devN suffix to reported version number and write a gitignored file that holds the git hash of the current state of the repo to be queried by ``xonfig`` """ try: _version = subprocess.check_output(["git", "describe", "--tags"]) except Exception: print("failed to find git tags", file=sys.stderr) return False _version = _version.decode("ascii") try: _, N, sha = _version.strip().split("-") except ValueError: # tag name may contain "-" print("failed to parse git version", file=sys.stderr) return False sha = sha.strip("g") replace_version(N) _cmd = ["git", "show", "-s", "--format=%cd", "--date=local", sha] try: _date = subprocess.check_output(_cmd) _date = _date.decode("ascii") # remove weekday name for a shorter string _date = " ".join(_date.split()[1:]) except: _date = "" print("failed to get commit date", file=sys.stderr) with open("xonsh/dev.githash", "w") as f: f.write(f"{sha}|{_date}") print("wrote git version: " + sha, file=sys.stderr) return True
Replace version in `__init__.py` with devN suffix
def replace_version(N): """Replace version in `__init__.py` with devN suffix""" global ORIGINAL_VERSION_LINE with open("xonsh/__init__.py") as f: raw = f.read() lines = raw.splitlines() msg_assert = "__version__ must be the first line of the __init__.py" assert "__version__" in lines[0], msg_assert ORIGINAL_VERSION_LINE = lines[0] lines[0] = lines[0].rstrip(' "') + f'.dev{N}"' upd = "\n".join(lines) + "\n" with open("xonsh/__init__.py", "w") as f: f.write(upd)
If we touch the version in __init__.py discard changes after install.
def restore_version(): """If we touch the version in __init__.py discard changes after install.""" if ORIGINAL_VERSION_LINE is None: return with open("xonsh/__init__.py") as f: raw = f.read() lines = raw.splitlines() lines[0] = ORIGINAL_VERSION_LINE upd = "\n".join(lines) + "\n" with open("xonsh/__init__.py", "w") as f: f.write(upd)
The main entry point.
def main(): """The main entry point.""" try: if "--name" not in sys.argv: logo_fname = os.path.join(os.path.dirname(__file__), "logo.txt") with open(logo_fname, "rb") as f: logo = f.read().decode("utf-8") print(logo) except UnicodeEncodeError: pass setup( cmdclass=cmdclass, )
Render our pages as a jinja template for fancy templating goodness.
def rstjinja(app, docname, source): """ Render our pages as a jinja template for fancy templating goodness. """ # Make sure we're outputting HTML if app.builder.format != "html": return print(docname) page_ctx = app.config.jinja_contexts.get(docname) if page_ctx is not None: ctx = { "rst": rst_helpers, } ctx.update(page_ctx) environment = jinja2.Environment( trim_blocks=True, lstrip_blocks=True, ) src = source[0] rendered = environment.from_string(src).render(**ctx) # rendered = app.builder.templates.render_string(src, ctx) source[0] = rendered # for debugging purpose write output Path(utils.docs_dir / "_build" / f"{docname}.rst.out").write_text(rendered)
Test that running an empty line or a comment does not append to history
def test_default_append_history(cmd, exp_append_history, xonsh_session, monkeypatch): """Test that running an empty line or a comment does not append to history""" append_history_calls = [] def mock_append_history(**info): append_history_calls.append(info) monkeypatch.setattr( xonsh_session.shell.shell, "_append_history", mock_append_history ) xonsh_session.shell.default(cmd) if exp_append_history: assert len(append_history_calls) == 1 else: assert len(append_history_calls) == 0
Set `__xonsh__.env ` to a new Env instance on `xonsh_builtins`
def home_env(xession): """Set `__xonsh__.env ` to a new Env instance on `xonsh_builtins`""" xession.env["HOME"] = HOME_PATH return xession
func doc multi-line Parameters ---------- param param doc multi param doc multi line optional : -o, --opt an optional parameter with flags defined in description Returns ------- str return doc
def func_with_doc(param: str, multi: str, optional=False): """func doc multi-line Parameters ---------- param param doc multi param doc multi line optional : -o, --opt an optional parameter with flags defined in description Returns ------- str return doc """ return param + multi, optional
See ``Completer.complete`` in ``xonsh/completer.py``
def test_cursor_after_closing_quote(completer, completers_mock): """See ``Completer.complete`` in ``xonsh/completer.py``""" @contextual_command_completer def comp(context: CommandContext): return {context.prefix + "1", context.prefix + "2"} completers_mock["a"] = comp assert completer.complete( "", "", 0, 0, {}, multiline_text="'test'", cursor_index=6 ) == (("test1'", "test2'"), 5) assert completer.complete( "", "", 0, 0, {}, multiline_text="'''test'''", cursor_index=10 ) == (("test1'''", "test2'''"), 7)
Test overriding the default values
def test_cursor_after_closing_quote_override(completer, completers_mock): """Test overriding the default values""" @contextual_command_completer def comp(context: CommandContext): return { # replace the closing quote with "a" RichCompletion( "a", prefix_len=len(context.closing_quote), append_closing_quote=False ), # add text after the closing quote RichCompletion(context.prefix + "_no_quote", append_closing_quote=False), # sanity RichCompletion(context.prefix + "1"), } completers_mock["a"] = comp assert completer.complete( "", "", 0, 0, {}, multiline_text="'test'", cursor_index=6 ) == ( ( "a", "test1'", "test_no_quote", ), 5, ) assert completer.complete( "", "", 0, 0, {}, multiline_text="'''test'''", cursor_index=10 ) == ( ( "a", "test1'''", "test_no_quote", ), 7, )
create some shares to play with on current machine. Yield (to test case) array of structs: [uncPath, driveLetter, equivLocalPath] Side effect: `os.chdir(TEST_WORK_DIR)`
def shares_setup(tmpdir_factory): """create some shares to play with on current machine. Yield (to test case) array of structs: [uncPath, driveLetter, equivLocalPath] Side effect: `os.chdir(TEST_WORK_DIR)` """ if not ON_WINDOWS: return [] shares = [ [r"uncpushd_test_HERE", TEMP_DRIVE[1], HERE], [r"uncpushd_test_PARENT", TEMP_DRIVE[3], PARENT], ] for ( s, d, l, ) in shares: # set up some shares on local machine. dirs already exist test case must invoke wd_setup. rtn = subprocess.call( ["NET", "SHARE", s, "/delete"], universal_newlines=True ) # clean up from previous run after good, long wait. if rtn != 0: yield None return rtn = subprocess.call(["NET", "SHARE", s + "=" + l], universal_newlines=True) if rtn != 0: yield None return rtn = subprocess.call( ["NET", "USE", d, r"\\localhost" + "\\" + s], universal_newlines=True ) if rtn != 0: yield None return yield [[r"\\localhost" + "\\" + s[0], s[1], s[2]] for s in shares] # we want to delete the test shares we've created, but can't do that if unc shares in DIRSTACK # (left over from assert fail aborted test) os.chdir(HERE) for dl in _unc_tempDrives: subprocess.call(["net", "use", dl, "/delete"], universal_newlines=True) for _, d, _ in shares: subprocess.call(["net", "use", d, "/delete"], universal_newlines=True)
Simple non-UNC push/pop to verify we didn't break nonUNC case.
def test_pushdpopd(xession): """Simple non-UNC push/pop to verify we didn't break nonUNC case.""" xession.env.update(dict(CDPATH=PARENT, PWD=HERE)) dirstack.cd([PARENT]) owd = os.getcwd() assert owd.casefold() == xession.env["PWD"].casefold() dirstack.pushd([HERE]) wd = os.getcwd() assert wd.casefold() == HERE.casefold() dirstack.popd([]) assert owd.casefold() == os.getcwd().casefold(), "popd returned cwd to expected dir"
push to a, then to b. verify drive letter is TEMP_DRIVE[2], skipping already used TEMP_DRIVE[1] Then push to a again. Pop (check b unmapped and a still mapped), pop, pop (check a is unmapped)
def test_uncpushd_push_other_push_same(xession, shares_setup): """push to a, then to b. verify drive letter is TEMP_DRIVE[2], skipping already used TEMP_DRIVE[1] Then push to a again. Pop (check b unmapped and a still mapped), pop, pop (check a is unmapped) """ if shares_setup is None: return xession.env.update(dict(CDPATH=PARENT, PWD=HERE)) dirstack.cd([PARENT]) owd = os.getcwd() assert owd.casefold() == xession.env["PWD"].casefold() dirstack.pushd([r"\\localhost\uncpushd_test_HERE"]) assert os.getcwd().casefold() == TEMP_DRIVE[0] + "\\" assert len(_unc_tempDrives) == 1 assert len(DIRSTACK) == 1 dirstack.pushd([r"\\localhost\uncpushd_test_PARENT"]) os.getcwd() assert os.getcwd().casefold() == TEMP_DRIVE[2] + "\\" assert len(_unc_tempDrives) == 2 assert len(DIRSTACK) == 2 dirstack.pushd([r"\\localhost\uncpushd_test_HERE"]) assert os.getcwd().casefold() == TEMP_DRIVE[0] + "\\" assert len(_unc_tempDrives) == 2 assert len(DIRSTACK) == 3 dirstack.popd([]) assert os.getcwd().casefold() == TEMP_DRIVE[2] + "\\" assert len(_unc_tempDrives) == 2 assert len(DIRSTACK) == 2 assert os.path.isdir(TEMP_DRIVE[2] + "\\") assert os.path.isdir(TEMP_DRIVE[0] + "\\") dirstack.popd([]) assert os.getcwd().casefold() == TEMP_DRIVE[0] + "\\" assert len(_unc_tempDrives) == 1 assert len(DIRSTACK) == 1 assert not os.path.isdir(TEMP_DRIVE[2] + "\\") assert os.path.isdir(TEMP_DRIVE[0] + "\\") dirstack.popd([]) assert os.getcwd().casefold() == owd.casefold() assert len(_unc_tempDrives) == 0 assert len(DIRSTACK) == 0 assert not os.path.isdir(TEMP_DRIVE[2] + "\\") assert not os.path.isdir(TEMP_DRIVE[0] + "\\")
push to subdir under share, verify mapped path includes subdir
def test_uncpushd_push_base_push_rempath(xession): """push to subdir under share, verify mapped path includes subdir""" pass
Test that a registered envvar without any type is treated permissively.
def test_register_custom_var_generic(): """Test that a registered envvar without any type is treated permissively. """ env = Env() assert "MY_SPECIAL_VAR" not in env env.register("MY_SPECIAL_VAR") assert "MY_SPECIAL_VAR" in env env["MY_SPECIAL_VAR"] = 32 assert env["MY_SPECIAL_VAR"] == 32 env["MY_SPECIAL_VAR"] = True assert env["MY_SPECIAL_VAR"] is True
Verify the rather complex rules for env.get("<envvar>",default) value when envvar is not defined.
def test_env_get_defaults(): """Verify the rather complex rules for env.get("<envvar>",default) value when envvar is not defined.""" env = Env(TEST1=0) env.register("TEST_REG", default="abc") env.register("TEST_REG_DNG", default=DefaultNotGiven) # var is defined, registered is don't-care => value is defined value assert env.get("TEST1", 22) == 0 # var not defined, not registered => value is immediate default assert env.get("TEST2", 22) == 22 assert "TEST2" not in env # var not defined, is registered, reg default is not sentinel => value is *registered* default assert env.get("TEST_REG", 22) == "abc" assert "TEST_REG" in env # var not defined, is registered, reg default is sentinel => value is *immediate* default assert env.get("TEST_REG_DNG", 22) == 22 assert "TEST_REG_DNG" not in env
Test initialization of the shell history.
def test_hist_init(hist, xession): """Test initialization of the shell history.""" with LazyJSON(hist.filename) as lj: obs = lj["here"] assert "yup" == obs
Verify appending to the history works.
def test_hist_append(hist, xession): """Verify appending to the history works.""" xession.env["HISTCONTROL"] = set() hf = hist.append({"inp": "still alive", "rtn": 0}) assert hf is None assert "still alive" == hist.buffer[0]["inp"] assert 0 == hist.buffer[0]["rtn"] assert 0 == hist.rtns[-1] hf = hist.append({"inp": "dead now", "rtn": 1}) assert "dead now" == hist.buffer[1]["inp"] assert 1 == hist.buffer[1]["rtn"] assert 1 == hist.rtns[-1] hf = hist.append({"inp": "reborn", "rtn": 0}) assert "reborn" == hist.buffer[2]["inp"] assert 0 == hist.buffer[2]["rtn"] assert 0 == hist.rtns[-1]
Verify explicit flushing of the history works.
def test_hist_flush(hist, xession): """Verify explicit flushing of the history works.""" hf = hist.flush() assert hf is None xession.env["HISTCONTROL"] = set() hist.append({"inp": "still alive?", "rtn": 0, "out": "yes"}) hf = hist.flush() assert hf is not None while hf.is_alive(): pass with LazyJSON(hist.filename) as lj: assert len(lj["cmds"]) == 1 cmd = lj["cmds"][0] assert cmd["inp"] == "still alive?" assert not cmd.get("out", None)
Verify explicit flushing of the history works.
def test_hist_flush_with_store_stdout(hist, xession): """Verify explicit flushing of the history works.""" hf = hist.flush() assert hf is None xession.env["HISTCONTROL"] = set() xession.env["XONSH_STORE_STDOUT"] = True hist.append({"inp": "still alive?", "rtn": 0, "out": "yes"}) hf = hist.flush() assert hf is not None while hf.is_alive(): pass with LazyJSON(hist.filename) as lj: assert len(lj["cmds"]) == 1 assert lj["cmds"][0]["inp"] == "still alive?" assert lj["cmds"][0]["out"].strip() == "yes"
Verify explicit flushing of the history works.
def test_hist_flush_with_hist_control(hist, xession): """Verify explicit flushing of the history works.""" hf = hist.flush() assert hf is None xession.env["HISTCONTROL"] = IGNORE_OPTS hist.append({"inp": "ls foo1", "rtn": 0}) hist.append({"inp": "ls foo1", "rtn": 1}) hist.append({"inp": "ls foo1", "rtn": 0}) hist.append({"inp": "ls foo2", "rtn": 2}) hist.append({"inp": "ls foo3", "rtn": 0}) hist.append({"inp": "ls secret", "rtn": 0, "spc": True}) hf = hist.flush() assert hf is not None while hf.is_alive(): pass assert len(hist.buffer) == 0 with LazyJSON(hist.filename) as lj: cmds = list(lj["cmds"]) assert len(cmds) == 2 assert [x["inp"] for x in cmds] == ["ls foo1", "ls foo3"] assert [x["rtn"] for x in cmds] == [0, 0]
Verify that CLI history commands work.
def test_show_cmd_numerate(inp, commands, offset, hist, xession, capsys): """Verify that CLI history commands work.""" base_idx, step = offset xession.env["HISTCONTROL"] = set() for ts, cmd in enumerate(CMDS): # populate the shell history hist.append({"inp": cmd, "rtn": 0, "ts": (ts + 1, ts + 1.5)}) exp = (f"{base_idx + idx * step}: {cmd}" for idx, cmd in enumerate(list(commands))) exp = "\n".join(exp) history_main(["show", "-n"] + shlex.split(inp)) out, err = capsys.readouterr() assert out.rstrip() == exp
Test HISTCONTROL=ignoredups,ignoreerr,ignorespacee
def test_histcontrol(hist, xession): """Test HISTCONTROL=ignoredups,ignoreerr,ignorespacee""" xession.env["HISTCONTROL"] = IGNORE_OPTS assert len(hist.buffer) == 0 # An error, buffer remains empty hist.append({"inp": "ls foo", "rtn": 2}) assert len(hist.buffer) == 1 assert hist.rtns[-1] == 2 assert hist.inps[-1] == "ls foo" # Success hist.append({"inp": "ls foobazz", "rtn": 0}) assert len(hist.buffer) == 2 assert "ls foobazz" == hist.buffer[-1]["inp"] assert 0 == hist.buffer[-1]["rtn"] assert hist.rtns[-1] == 0 assert hist.inps[-1] == "ls foobazz" # Error hist.append({"inp": "ls foo", "rtn": 2}) assert len(hist.buffer) == 3 assert "ls foo" == hist.buffer[-1]["inp"] assert 2 == hist.buffer[-1]["rtn"] assert hist.rtns[-1] == 2 assert hist.inps[-1] == "ls foo" # File now exists, success hist.append({"inp": "ls foo", "rtn": 0}) assert len(hist.buffer) == 4 assert "ls foo" == hist.buffer[-1]["inp"] assert 0 == hist.buffer[-1]["rtn"] assert hist.rtns[-1] == 0 assert hist.inps[-1] == "ls foo" # Success hist.append({"inp": "ls", "rtn": 0}) assert len(hist.buffer) == 5 assert "ls" == hist.buffer[-1]["inp"] assert 0 == hist.buffer[-1]["rtn"] assert hist.rtns[-1] == 0 assert hist.inps[-1] == "ls" # Dup hist.append({"inp": "ls", "rtn": 0}) assert len(hist.buffer) == 6 assert hist.rtns[-1] == 0 assert hist.inps[-1] == "ls" # Success hist.append({"inp": "/bin/ls", "rtn": 0}) assert len(hist.buffer) == 7 assert "/bin/ls" == hist.buffer[-1]["inp"] assert 0 == hist.buffer[-1]["rtn"] assert hist.rtns[-1] == 0 assert hist.inps[-1] == "/bin/ls" # Error hist.append({"inp": "ls bazz", "rtn": 1}) assert len(hist.buffer) == 8 assert "ls bazz" == hist.buffer[-1]["inp"] assert 1 == hist.buffer[-1]["rtn"] assert hist.rtns[-1] == 1 assert hist.inps[-1] == "ls bazz" # Error hist.append({"inp": "ls bazz", "rtn": -1}) assert len(hist.buffer) == 9 assert "ls bazz" == hist.buffer[-1]["inp"] assert -1 == hist.buffer[-1]["rtn"] assert hist.rtns[-1] == -1 assert hist.inps[-1] == "ls bazz" # Success hist.append({"inp": "echo not secret", "rtn": 0, "spc": False}) assert len(hist.buffer) == 10 assert "echo not secret" == hist.buffer[-1]["inp"] assert 0 == hist.buffer[-1]["rtn"] assert hist.rtns[-1] == 0 assert hist.inps[-1] == "echo not secret" # Space hist.append({"inp": "echo secret command", "rtn": 0, "spc": True}) assert len(hist.buffer) == 10 assert hist.rtns[-1] == 0 assert hist.inps[-1] == "echo not secret"
Generate a list of history file tuples
def history_files_list(gen_count) -> (float, int, str, int): """Generate a list of history file tuples""" # generate test list: # 2 files every day in range # morning file has 100 commands, evening 50 # first file size 10000, 2nd 2500 # first file time 0900, 2nd 2300 # for sanity in reproducable test results, all date arithmetic ignores astronomy. # time zone is UTC, all days have 24 h and 0 sec, no leap year or leap sec. retval = [] for i in range(int((gen_count + 1) / 2)): retval.append( ( # first day in sec + #days * 24hr + #hr * 60min + # sec * 60sec + sec= sec to date. HF_FIRST_DAY + (((((i * 24) + 9) * 60) + 0) * 60) + 0, # mod dt, 100, f".argle/xonsh-{2*i:05n}.json", 10000, ) ) retval.append( ( # first day in sec + #days * 24hr + #hr * 60min + # sec * 60sec + sec= sec to date. HF_FIRST_DAY + (((((i * 24) + 23) * 60) + 0) * 60) + 0, # mod dt, 50, f".argle/xonsh-{2*i+1:05n}.json", 2500, ) ) return retval
Verify that the CLI history clear command works.
def test_hist_clear_cmd(hist, xession, capsys, tmpdir): """Verify that the CLI history clear command works.""" xession.env.update({"XONSH_DATA_DIR": str(tmpdir)}) xession.env["HISTCONTROL"] = set() for ts, cmd in enumerate(CMDS): # populate the shell history hist.append({"inp": cmd, "rtn": 0, "ts": (ts + 1, ts + 1.5)}) assert len(xession.history) == 6 history_main(["clear"]) out, err = capsys.readouterr() assert err.rstrip() == "History cleared" assert len(xession.history) == 0
Verify that the CLI history off command works.
def test_hist_off_cmd(hist, xession, capsys, tmpdir): """Verify that the CLI history off command works.""" xession.env.update({"XONSH_DATA_DIR": str(tmpdir)}) xession.env["HISTCONTROL"] = set() for ts, cmd in enumerate(CMDS): # populate the shell history hist.append({"inp": cmd, "rtn": 0, "ts": (ts + 1, ts + 1.5)}) assert len(xession.history) == 6 history_main(["off"]) out, err = capsys.readouterr() assert err.rstrip() == "History off" assert len(xession.history) == 0 for ts, cmd in enumerate(CMDS): # attempt to populate the shell history hist.append({"inp": cmd, "rtn": 0, "ts": (ts + 1, ts + 1.5)}) assert len(xession.history) == 0
Verify that the CLI history on command works.
def test_hist_on_cmd(hist, xession, capsys, tmpdir): """Verify that the CLI history on command works.""" xession.env.update({"XONSH_DATA_DIR": str(tmpdir)}) xession.env["HISTCONTROL"] = set() for ts, cmd in enumerate(CMDS): # populate the shell history hist.append({"inp": cmd, "rtn": 0, "ts": (ts + 1, ts + 1.5)}) assert len(xession.history) == 6 history_main(["off"]) history_main(["on"]) out, err = capsys.readouterr() assert err.rstrip().endswith("History on") assert len(xession.history) == 0 for ts, cmd in enumerate(CMDS): # populate the shell history hist.append({"inp": cmd, "rtn": 0, "ts": (ts + 1, ts + 1.5)}) assert len(xession.history) == 6
Verify appending to the history works.
def test_hist_append(hist, xession): """Verify appending to the history works.""" xession.env["HISTCONTROL"] = set() hf = hist.append({"inp": "still alive", "rtn": 1}) assert hf is None items = list(hist.items()) assert len(items) == 1 assert "still alive" == items[0]["inp"] assert 1 == items[0]["rtn"] hist.append({"inp": "still alive", "rtn": 0}) items = list(hist.items()) assert len(items) == 2 assert "still alive" == items[1]["inp"] assert 0 == items[1]["rtn"] assert list(hist.all_items()) == items _clean_up(hist)
Verify that CLI history commands work.
def test_show_cmd_numerate(inp, commands, offset, hist, xession, capsys): """Verify that CLI history commands work.""" base_idx, step = offset xession.history = hist xession.env["HISTCONTROL"] = set() for ts, cmd in enumerate(CMDS): # populate the shell history hist.append({"inp": cmd, "rtn": 0, "ts": (ts + 1, ts + 1.5)}) exp = (f"{base_idx + idx * step}: {cmd}" for idx, cmd in enumerate(list(commands))) exp = "\n".join(exp) history_main(["show", "-n"] + shlex.split(inp)) out, err = capsys.readouterr() assert out.rstrip() == exp _clean_up(hist)
Test HISTCONTROL=ignoredups,ignoreerr
def test_histcontrol(hist, xession): """Test HISTCONTROL=ignoredups,ignoreerr""" ignore_opts = ",".join(["ignoredups", "ignoreerr", "ignorespace"]) xession.env["HISTCONTROL"] = ignore_opts assert len(hist) == 0 # An error, items() remains empty hist.append({"inp": "ls foo", "rtn": 2}) assert len(hist) == 0 assert len(hist.inps) == 1 assert len(hist.rtns) == 1 assert 2 == hist.rtns[-1] # Success hist.append({"inp": "ls foobazz", "rtn": 0}) assert len(hist) == 1 assert len(hist.inps) == 2 assert len(hist.rtns) == 2 items = list(hist.items()) assert "ls foobazz" == items[-1]["inp"] assert 0 == items[-1]["rtn"] assert 0 == hist.rtns[-1] # Error hist.append({"inp": "ls foo", "rtn": 2}) assert len(hist) == 1 items = list(hist.items()) assert "ls foobazz" == items[-1]["inp"] assert 0 == items[-1]["rtn"] assert 2 == hist.rtns[-1] # File now exists, success hist.append({"inp": "ls foo", "rtn": 0}) assert len(hist) == 2 items = list(hist.items()) assert "ls foo" == items[-1]["inp"] assert 0 == items[-1]["rtn"] assert 0 == hist.rtns[-1] # Success hist.append({"inp": "ls", "rtn": 0}) assert len(hist) == 3 items = list(hist.items()) assert "ls" == items[-1]["inp"] assert 0 == items[-1]["rtn"] assert 0 == hist.rtns[-1] # Dup hist.append({"inp": "ls", "rtn": 0}) assert len(hist) == 3 # Success hist.append({"inp": "/bin/ls", "rtn": 0}) assert len(hist) == 4 items = list(hist.items()) assert "/bin/ls" == items[-1]["inp"] assert 0 == items[-1]["rtn"] assert 0 == hist.rtns[-1] # Error hist.append({"inp": "ls bazz", "rtn": 1}) assert len(hist) == 4 items = list(hist.items()) assert "/bin/ls" == items[-1]["inp"] assert 0 == items[-1]["rtn"] assert "ls bazz" == hist.inps[-1] assert 1 == hist.rtns[-1] # Error hist.append({"inp": "ls bazz", "rtn": -1}) assert len(hist) == 4 items = list(hist.items()) assert "/bin/ls" == items[-1]["inp"] assert 0 == items[-1]["rtn"] assert -1 == hist.rtns[-1] # Success hist.append({"inp": "echo not secret", "rtn": 0, "spc": False}) assert len(hist) == 5 items = list(hist.items()) assert "echo not secret" == items[-1]["inp"] assert 0 == items[-1]["rtn"] assert 0 == hist.rtns[-1] # Space hist.append({"inp": "echo secret command", "rtn": 0, "spc": True}) assert len(hist) == 5 items = list(hist.items()) assert "echo not secret" == items[-1]["inp"] assert 0 == items[-1]["rtn"] assert 0 == hist.rtns[-1] _clean_up(hist)
Test HISTCONTROL=erasedups
def test_histcontrol_erase_dup(hist, xession): """Test HISTCONTROL=erasedups""" xession.env["HISTCONTROL"] = "erasedups" assert len(hist) == 0 hist.append({"inp": "ls foo", "rtn": 2}) hist.append({"inp": "ls foobazz", "rtn": 0}) hist.append({"inp": "ls foo", "rtn": 0}) hist.append({"inp": "ls foobazz", "rtn": 0}) hist.append({"inp": "ls foo", "rtn": 0}) assert len(hist) == 2 assert len(hist.inps) == 5 items = list(hist.items()) assert "ls foo" == items[-1]["inp"] assert "ls foobazz" == items[-2]["inp"] assert items[-2]["frequency"] == 2 assert items[-1]["frequency"] == 3 _clean_up(hist)
Verify that the CLI history clear command works.
def test_hist_clear_cmd(hist, xession, capsys, tmpdir): """Verify that the CLI history clear command works.""" xession.env.update({"XONSH_DATA_DIR": str(tmpdir)}) xession.history = hist xession.env["HISTCONTROL"] = set() for ts, cmd in enumerate(CMDS): # populate the shell history hist.append({"inp": cmd, "rtn": 0, "ts": (ts + 1, ts + 1.5)}) assert len(xession.history) == 6 history_main(["clear"]) out, err = capsys.readouterr() assert err.rstrip() == "History cleared" assert len(xession.history) == 0 _clean_up(hist)
Verify that the CLI history off command works.
def test_hist_off_cmd(hist, xession, capsys, tmpdir): """Verify that the CLI history off command works.""" xession.env.update({"XONSH_DATA_DIR": str(tmpdir)}) xession.history = hist xession.env["HISTCONTROL"] = set() for ts, cmd in enumerate(CMDS): # populate the shell history hist.append({"inp": cmd, "rtn": 0, "ts": (ts + 1, ts + 1.5)}) assert len(xession.history) == 6 history_main(["off"]) out, err = capsys.readouterr() assert err.rstrip() == "History off" assert len(xession.history) == 0 for ts, cmd in enumerate(CMDS): # attempt to populate the shell history hist.append({"inp": cmd, "rtn": 0, "ts": (ts + 1, ts + 1.5)}) assert len(xession.history) == 0 _clean_up(hist)
Verify that the CLI history on command works.
def test_hist_on_cmd(hist, xession, capsys, tmpdir): """Verify that the CLI history on command works.""" xession.env.update({"XONSH_DATA_DIR": str(tmpdir)}) xession.history = hist xession.env["HISTCONTROL"] = set() for ts, cmd in enumerate(CMDS): # populate the shell history hist.append({"inp": cmd, "rtn": 0, "ts": (ts + 1, ts + 1.5)}) assert len(xession.history) == 6 history_main(["off"]) history_main(["on"]) out, err = capsys.readouterr() assert err.rstrip().endswith("History on") assert len(xession.history) == 0 for ts, cmd in enumerate(CMDS): # populate the shell history hist.append({"inp": cmd, "rtn": 0, "ts": (ts + 1, ts + 1.5)}) assert len(xession.history) == 6 _clean_up(hist)
The ``fmt`` parameter is a function that formats the output of cmd, can be None.
def check_run_xonsh(cmd, fmt, exp, exp_rtn=0): """The ``fmt`` parameter is a function that formats the output of cmd, can be None. """ out, err, rtn = run_xonsh(cmd, stderr=sp.PIPE) if callable(fmt): out = fmt(out) if callable(exp): exp = exp() assert out == exp, err assert rtn == exp_rtn, err
Ensures syntax errors for EOF appear on last line.
def test_eof_syntax_error(): """Ensures syntax errors for EOF appear on last line.""" script = "x = 1\na = (1, 0\n" out, err, rtn = run_xonsh(script, stderr=sp.PIPE) assert "line 0" not in err assert "EOF in multi-line statement" in err and "line 2" in err
verify pipe between subprocesses doesn't throw an exception
def test_pipe_between_subprocs(cmd, fmt, exp): """verify pipe between subprocesses doesn't throw an exception""" check_run_xonsh(cmd, fmt, exp)
Ensure we can run an executable in the current folder when file is not on path
def test_run_currentfolder(monkeypatch): """Ensure we can run an executable in the current folder when file is not on path """ batfile = Path(__file__).parent / "bin" / "hello_world.bat" monkeypatch.chdir(batfile.parent) cmd = batfile.name out, _, _ = run_xonsh(cmd, stdout=sp.PIPE, stderr=sp.PIPE, path=os.environ["PATH"]) assert out.strip() == "hello world"
Ensure we can run an executable which is added to the path after xonsh is loaded
def test_run_dynamic_on_path(): """Ensure we can run an executable which is added to the path after xonsh is loaded """ batfile = Path(__file__).parent / "bin" / "hello_world.bat" cmd = f"$PATH.add(r'{batfile.parent}');![hello_world.bat]" out, _, _ = run_xonsh(cmd, path=os.environ["PATH"]) assert out.strip() == "hello world"
Test that xonsh fails to run an executable when not on path or in current folder
def test_run_fail_not_on_path(): """Test that xonsh fails to run an executable when not on path or in current folder """ cmd = "hello_world.bat" out, _, _ = run_xonsh(cmd, stdout=sp.PIPE, stderr=sp.PIPE, path=os.environ["PATH"]) assert out != "Hello world"
Tests whether two token are equal.
def tokens_equal(x, y): """Tests whether two token are equal.""" xtup = ensure_tuple(x) ytup = ensure_tuple(y) return xtup == ytup
Asserts that two tokens are equal.
def assert_token_equal(x, y): """Asserts that two tokens are equal.""" if not tokens_equal(x, y): msg = f"The tokens differ: {x!r} != {y!r}" pytest.fail(msg) return True
Asserts that two token sequences are equal.
def assert_tokens_equal(x, y): """Asserts that two token sequences are equal.""" if len(x) != len(y): msg = "The tokens sequences have different lengths: {0!r} != {1!r}\n" msg += "# x\n{2}\n\n# y\n{3}" pytest.fail(msg.format(len(x), len(y), pformat(x), pformat(y))) diffs = [(a, b) for a, b in zip(x, y) if not tokens_equal(a, b)] if len(diffs) > 0: msg = ["The token sequences differ: "] for a, b in diffs: msg += ["", "- " + repr(a), "+ " + repr(b)] msg = "\n".join(msg) pytest.fail(msg) return True
Xonsh Shell Mock
def shell(xession, monkeypatch): """Xonsh Shell Mock""" gc.collect() Shell.shell_type_aliases = {"rl": "readline"} monkeypatch.setattr(xonsh.main, "Shell", Shell)
Test that an RC file can load modules inside the same folder it is located in.
def test_rc_with_modules(shell, tmpdir, monkeypatch, capsys, xession): """Test that an RC file can load modules inside the same folder it is located in.""" monkeypatch.setattr(sys.stdin, "isatty", lambda: True) monkeypatch.setitem(os.environ, "XONSH_CACHE_SCRIPTS", "False") tmpdir.join("my_python_module.py").write("print('Hello,')") tmpdir.join("my_xonsh_module.xsh").write("print('World!')") rc = tmpdir.join("rc.xsh") rc.write("from my_python_module import *\nfrom my_xonsh_module import *") xonsh.main.premain(["--rc", rc.strpath]) assert rc.strpath in xession.rc_files stdout, stderr = capsys.readouterr() assert "Hello,\nWorld!" in stdout assert len(stderr) == 0 # Check that the temporary rc's folder is not left behind on the path assert tmpdir.strpath not in sys.path
Test that python based control files are executed using Python's parser
def test_python_rc(shell, tmpdir, monkeypatch, capsys, xession, mocker): """Test that python based control files are executed using Python's parser""" monkeypatch.setattr(sys.stdin, "isatty", lambda: True) monkeypatch.setitem(os.environ, "XONSH_CACHE_SCRIPTS", "False") # spy on xonsh's compile method spy = mocker.spy(xession.execer, "compile") rc = tmpdir.join("rc.py") rc.write("print('Hello World!')") xonsh.main.premain(["--rc", rc.strpath]) assert rc.strpath in xession.rc_files stdout, stderr = capsys.readouterr() assert "Hello World!" in stdout assert len(stderr) == 0 # Check that the temporary rc's folder is not left behind on the path assert tmpdir.strpath not in sys.path assert not spy.called
Test that files are loaded from an rcdir, after a normal rc file, and in lexographic order.
def test_rcdir(shell, tmpdir, monkeypatch, capsys): """ Test that files are loaded from an rcdir, after a normal rc file, and in lexographic order. """ rcdir = tmpdir.join("rc.d") rcdir.mkdir() monkeypatch.setattr(sys.stdin, "isatty", lambda: True) monkeypatch.setitem(os.environ, "XONSHRC_DIR", str(rcdir)) monkeypatch.setitem(os.environ, "XONSHRC", str(tmpdir.join("rc.xsh"))) monkeypatch.setitem(os.environ, "XONSH_CACHE_SCRIPTS", "False") rcdir.join("2.xsh").write("print('2.xsh')") rcdir.join("0.xsh").write("print('0.xsh')") rcdir.join("1.xsh").write("print('1.xsh')") tmpdir.join("rc.xsh").write("print('rc.xsh')") xonsh.main.premain([]) stdout, stderr = capsys.readouterr() assert "rc.xsh\n0.xsh\n1.xsh\n2.xsh" in stdout assert len(stderr) == 0
Test that --rc DIR works
def test_rcdir_cli(shell, tmpdir, xession, monkeypatch): """Test that --rc DIR works""" rcdir = tmpdir.join("rcdir") rcdir.mkdir() rc = rcdir.join("test.xsh") rc.write("print('test.xsh')") monkeypatch.setattr(sys.stdin, "isatty", lambda: True) xargs = xonsh.main.premain(["--rc", rcdir.strpath]) assert len(xargs.rc) == 1 and xargs.rc[0] == rcdir.strpath assert rc.strpath in xession.rc_files
Test that an empty XONSHRC_DIR is not an error
def test_rcdir_empty(shell, tmpdir, monkeypatch, capsys): """Test that an empty XONSHRC_DIR is not an error""" rcdir = tmpdir.join("rc.d") rcdir.mkdir() rc = tmpdir.join("rc.xsh") rc.write_binary(b"") monkeypatch.setattr(sys.stdin, "isatty", lambda: True) monkeypatch.setitem(os.environ, "XONSHRC", str(rc)) monkeypatch.setitem(os.environ, "XONSHRC_DIR", str(rcdir)) xonsh.main.premain([]) stdout, stderr = capsys.readouterr() assert len(stderr) == 0
Test the correct scripts are loaded, in the correct order, for different combinations of CLI arguments. See https://github.com/xonsh/xonsh/issues/4096 This sets up a standard set of RC files which will be loaded, and tests whether they print their payloads at all, or in the right order, depending on the CLI arguments chosen.
def test_script_startup(shell, tmpdir, monkeypatch, capsys, args, expected): """ Test the correct scripts are loaded, in the correct order, for different combinations of CLI arguments. See https://github.com/xonsh/xonsh/issues/4096 This sets up a standard set of RC files which will be loaded, and tests whether they print their payloads at all, or in the right order, depending on the CLI arguments chosen. """ rcdir = tmpdir.join("rc.d") rcdir.mkdir() # XONSHRC_DIR files, in order rcdir.join("d0.xsh").write("print('D0')") rcdir.join("d1.xsh").write("print('D1')") # XONSHRC files, in order f0 = tmpdir.join("f0.xsh") f0.write("print('F0')") f1 = tmpdir.join("f1.xsh") f1.write("print('F1')") # RC files which can be explicitly loaded with --rc r0 = tmpdir.join("r0.xsh") r0.write("print('R0')") r1 = tmpdir.join("r1.xsh") r1.write("print('R1')") # a (non-RC) script which can be loaded sc = tmpdir.join("sc.xsh") sc.write("print('SC')") monkeypatch.setitem(os.environ, "XONSHRC", f"{f0}:{f1}") monkeypatch.setitem(os.environ, "XONSHRC_DIR", str(rcdir)) # replace <RC> with the path to rc.xsh and <SC> with sc.xsh args = [ a.replace("<R0>", str(r0)).replace("<R1>", str(r1)).replace("<SC>", str(sc)) for a in args ] # since we only test xonsh.premain here, a script file (SC) # won't actually get run here, so won't appear in the stdout, # so don't check for it (but check for a .file in the parsed args) check_for_script = "SC" in expected expected = [e for e in expected if e != "SC"] xargs = xonsh.main.premain(args) stdout, stderr = capsys.readouterr() assert "\n".join(expected) in stdout if check_for_script: assert xargs.file is not None
Test that --rc suppresses loading XONSHRC_DIRs
def test_rcdir_ignored_with_rc(shell, tmpdir, monkeypatch, capsys, xession): """Test that --rc suppresses loading XONSHRC_DIRs""" rcdir = tmpdir.join("rc.d") rcdir.mkdir() monkeypatch.setattr(sys.stdin, "isatty", lambda: True) monkeypatch.setitem(os.environ, "XONSHRC_DIR", str(rcdir)) rcdir.join("rcd.xsh").write("print('RCDIR')") tmpdir.join("rc.xsh").write("print('RCFILE')") xonsh.main.premain(["--rc", str(tmpdir.join("rc.xsh"))]) stdout, stderr = capsys.readouterr() assert "RCDIR" not in stdout assert "RCFILE" in stdout assert str(rcdir.join("rcd.xsh")) not in xession.rc_files
Test that an RC file can edit the sys.path variable without losing those values.
def test_rc_with_modified_path(shell, tmpdir, monkeypatch, capsys, xession): """Test that an RC file can edit the sys.path variable without losing those values.""" monkeypatch.setattr(sys.stdin, "isatty", lambda: True) monkeypatch.setitem(os.environ, "XONSH_CACHE_SCRIPTS", "False") rc = tmpdir.join("rc.xsh") rc.write(f"import sys\nsys.path.append('{tmpdir.strpath}')\nprint('Hello, World!')") xonsh.main.premain(["--rc", rc.strpath]) assert rc.strpath in xession.rc_files stdout, stderr = capsys.readouterr() assert "Hello, World!" in stdout assert len(stderr) == 0 # Check that the path that was explicitly added is not accidentally deleted assert tmpdir.strpath in sys.path
Test that an RC file which imports a module that throws an exception .
def test_rc_with_failing_module(shell, tmpdir, monkeypatch, capsys, xession): """Test that an RC file which imports a module that throws an exception .""" monkeypatch.setattr(sys.stdin, "isatty", lambda: True) monkeypatch.setitem(os.environ, "XONSH_CACHE_SCRIPTS", "False") tmpdir.join("my_failing_module.py").write("raise RuntimeError('Unexpected error')") rc = tmpdir.join("rc.xsh") rc.write("from my_failing_module import *") xonsh.main.premain(["--rc", rc.strpath]) assert rc.strpath not in xession.rc_files stdout, stderr = capsys.readouterr() assert len(stdout) == 0 assert "Unexpected error" in stderr # Check that the temporary rc's folder is not left behind on the path assert tmpdir.strpath not in sys.path
Calling a custom RC file on a script-call with the interactive flag should run interactively
def test_force_interactive_custom_rc_with_script(shell, tmpdir, monkeypatch, xession): """Calling a custom RC file on a script-call with the interactive flag should run interactively """ monkeypatch.setitem(os.environ, "XONSH_CACHE_SCRIPTS", "False") f = tmpdir.join("wakkawakka") f.write("print('hi')") args = xonsh.main.premain(["-i", "--rc", f.strpath, "tests/sample.xsh"]) assert args.mode == XonshMode.interactive assert f.strpath in xession.rc_files
Calling a custom RC file on a script-call without the interactive flag should not run interactively
def test_custom_rc_with_script(shell, tmpdir, xession): """Calling a custom RC file on a script-call without the interactive flag should not run interactively """ f = tmpdir.join("wakkawakka") f.write("print('hi')") args = xonsh.main.premain(["--rc", f.strpath, "tests/sample.xsh"]) assert not (args.mode == XonshMode.interactive) assert f.strpath in xession.rc_files
Calling a custom RC file on a script-call without the interactive flag and no-rc should not run interactively and should not have any rc_files
def test_custom_rc_with_script_and_no_rc(shell, tmpdir, xession): """Calling a custom RC file on a script-call without the interactive flag and no-rc should not run interactively and should not have any rc_files """ f = tmpdir.join("wakkawakka") f.write("print('hi')") args = xonsh.main.premain(["--no-rc", "--rc", f.strpath, "tests/sample.xsh"]) assert not (args.mode == XonshMode.interactive) assert len(xession.rc_files) == 0
Verify colorizer returns Token.Text if file type not defined in LS_COLORS
def test_color_on_lscolors_change(tmpdir, xonsh_builtins_ls_colors, check_token): """Verify colorizer returns Token.Text if file type not defined in LS_COLORS""" lsc = xonsh_builtins_ls_colors.env["LS_COLORS"] test_dir = str(tmpdir.mkdir("xonsh-test-highlight-path")) lsc["di"] = ("GREEN",) check_token(f"cd {test_dir}", [(Name.Builtin, "cd"), (Color.GREEN, test_dir)]) del lsc["di"] check_token(f"cd {test_dir}", [(Name.Builtin, "cd"), (Text, test_dir)])
Instantiate `PromptToolkitHistory` and append a line string
def history_obj(): """Instantiate `PromptToolkitHistory` and append a line string""" from xonsh.ptk_shell.history import PromptToolkitHistory hist = PromptToolkitHistory(load_prev=False) hist.append_string("line10") return hist
Context in which the ptk multiline functionality will be tested.
def ctx(xession): """Context in which the ptk multiline functionality will be tested.""" xession.env["INDENT"] = " " from xonsh.ptk_shell.key_bindings import carriage_return ptk_buffer = Buffer() ptk_buffer.accept_action = MagicMock(name="accept") cli = MagicMock(name="cli", spec=Application) yield Context( indent=" ", buffer=ptk_buffer, accept=ptk_buffer.accept_action, cli=cli, cr=carriage_return, )
don't dedent if first line of ctx.buffer
def test_nodedent(ctx): """don't dedent if first line of ctx.buffer""" mock = MagicMock(return_value=True) with patch("xonsh.ptk_shell.key_bindings.can_compile", mock): document = Document("pass") ctx.buffer.set_document(document) ctx.cr(ctx.buffer, ctx.cli) assert ctx.accept.mock_calls is not None mock = MagicMock(return_value=True) with patch("xonsh.ptk_shell.key_bindings.can_compile", mock): document = Document(ctx.indent + "pass") ctx.buffer.set_document(document) ctx.cr(ctx.buffer, ctx.cli) assert ctx.accept.mock_calls is not None
Test that running an empty line or a comment does not append to history. This test is necessary because the prompt-toolkit shell uses a custom _push() method that is different from the base shell's push() method.
def test_ptk_default_append_history(cmd, exp_append_history, ptk_shell, monkeypatch): """Test that running an empty line or a comment does not append to history. This test is necessary because the prompt-toolkit shell uses a custom _push() method that is different from the base shell's push() method. """ inp, out, shell = ptk_shell append_history_calls = [] def mock_append_history(**info): append_history_calls.append(info) monkeypatch.setattr(shell, "_append_history", mock_append_history) shell.default(cmd) if exp_append_history: assert len(append_history_calls) == 1 else: assert len(append_history_calls) == 0
Xonsh environment including LS_COLORS
def xs_LS_COLORS(xession, os_env, monkeypatch): """Xonsh environment including LS_COLORS""" # original env is needed on windows. since it will skip enhanced coloring # for some emulators monkeypatch.setattr(xession, "env", os_env) lsc = LsColors(LsColors.default_settings) xession.env["LS_COLORS"] = lsc # todo: a separate test for this as True xession.env["INTENSIFY_COLORS_ON_WIN"] = False xession.shell.shell_type = "prompt_toolkit" xession.shell.shell.styler = XonshStyle() # default style yield xession
populate temp dir with sample files. (too hard to emit indivual test cases when fixture invoked in mark.parametrize)
def colorizable_files(): """populate temp dir with sample files. (too hard to emit indivual test cases when fixture invoked in mark.parametrize)""" with TemporaryDirectory() as tempdir: for k, v in _cf.items(): if v is None: continue if v.startswith("/"): file_path = v else: file_path = tempdir + "/" + v try: os.lstat(file_path) except FileNotFoundError: if file_path.endswith("_dir"): os.mkdir(file_path) else: open(file_path, "a").close() if k in ("di", "fi"): pass elif k == "ex": os.chmod(file_path, stat.S_IRWXU) # tmpdir on windows need u+w elif k == "ln": # cook ln test case. os.chmod(file_path, stat.S_IRWXU) # link to *executable* file os.rename(file_path, file_path + "_target") os.symlink(file_path + "_target", file_path) elif k == "or": os.rename(file_path, file_path + "_target") os.symlink(file_path + "_target", file_path) os.remove(file_path + "_target") elif k == "pi": # not on Windows os.remove(file_path) os.mkfifo(file_path) elif k == "su": os.chmod(file_path, stat.S_ISUID) elif k == "sg": os.chmod(file_path, stat.S_ISGID) elif k == "st": os.chmod( file_path, stat.S_ISVTX | stat.S_IRUSR | stat.S_IWUSR ) # TempDir requires o:r elif k == "tw": os.chmod( file_path, stat.S_ISVTX | stat.S_IWOTH | stat.S_IRUSR | stat.S_IWUSR, ) elif k == "ow": os.chmod(file_path, stat.S_IWOTH | stat.S_IRUSR | stat.S_IWUSR) elif k == "mh": os.rename(file_path, file_path + "_target") os.link(file_path + "_target", file_path) else: pass # cauterize those elseless ifs! os.symlink(file_path, file_path + "_symlink") yield tempdir pass
test proper file codes with symlinks colored normally
def test_colorize_file(key, file_path, colorizable_files, xs_LS_COLORS): """test proper file codes with symlinks colored normally""" ffp = colorizable_files + "/" + file_path stat_result = os.lstat(ffp) color_token, color_key = color_file(ffp, stat_result) assert color_key == key, "File classified as expected kind" assert color_token == file_color_tokens[key], "Color token is as expected"
test proper file codes with symlinks colored target.
def test_colorize_file_symlink(key, file_path, colorizable_files, xs_LS_COLORS): """test proper file codes with symlinks colored target.""" xs_LS_COLORS.env["LS_COLORS"]["ln"] = "target" ffp = colorizable_files + "/" + file_path + "_symlink" stat_result = os.lstat(ffp) assert stat.S_ISLNK(stat_result.st_mode) _, color_key = color_file(ffp, stat_result) try: tar_stat_result = os.stat(ffp) # stat the target of the link tar_ffp = str(pathlib.Path(ffp).resolve()) _, tar_color_key = color_file(tar_ffp, tar_stat_result) if tar_color_key.startswith("*"): tar_color_key = ( "fi" # all the *.* zoo, link is colored 'fi', not target type. ) except FileNotFoundError: # orphan symlinks always colored 'or' tar_color_key = "or" # Fake if for missing file assert color_key == tar_color_key, "File classified as expected kind, via symlink"
Check that shell successfully load JSON history from file.
def test_shell_with_json_history(xession, xonsh_execer, tmpdir_factory): """ Check that shell successfully load JSON history from file. """ tempdir = str(tmpdir_factory.mktemp("history")) history_file = os.path.join(tempdir, "history.json") h = JsonHistory(filename=history_file) h.append( { "inp": "echo Hello world 1\n", "rtn": 0, "ts": [1615887820.7329783, 1615887820.7513437], } ) h.append( { "inp": "echo Hello world 2\n", "rtn": 0, "ts": [1615887820.7329783, 1615887820.7513437], } ) h.flush() xession.env.update( dict( XONSH_DATA_DIR=tempdir, XONSH_INTERACTIVE=True, XONSH_HISTORY_BACKEND="json", XONSH_HISTORY_FILE=history_file, # XONSH_DEBUG=1 # to show errors ) ) Shell(xonsh_execer, shell_type="none") assert len([i for i in xession.history.all_items()]) == 2
Check that shell successfully load SQLite history from file.
def test_shell_with_sqlite_history(xession, xonsh_execer, tmpdir_factory): """ Check that shell successfully load SQLite history from file. """ tempdir = str(tmpdir_factory.mktemp("history")) history_file = os.path.join(tempdir, "history.db") h = SqliteHistory(filename=history_file) h.append( { "inp": "echo Hello world 1\n", "rtn": 0, "ts": [1615887820.7329783, 1615887820.7513437], } ) h.append( { "inp": "echo Hello world 2\n", "rtn": 0, "ts": [1615887820.7329783, 1615887820.7513437], } ) h.flush() xession.env.update( dict( XONSH_DATA_DIR=tempdir, XONSH_INTERACTIVE=True, XONSH_HISTORY_BACKEND="sqlite", XONSH_HISTORY_FILE=history_file, # XONSH_DEBUG=1 # to show errors ) ) Shell(xonsh_execer, shell_type="none") assert len([i for i in xession.history.all_items()]) == 2
Check that shell use Dummy history in not interactive mode.
def test_shell_with_dummy_history_in_not_interactive(xession, xonsh_execer): """ Check that shell use Dummy history in not interactive mode. """ xession.env["XONSH_INTERACTIVE"] = False xession.history = None Shell(xonsh_execer, shell_type="none") assert isinstance(xession.history, DummyHistory)
Build os-dependent paths properly.
def mkpath(*paths): """Build os-dependent paths properly.""" return os.sep + os.sep.join(paths)
Tweaked for xonsh cases from CPython `test_genericpath.py`
def test_expandvars(inp, exp, xession): """Tweaked for xonsh cases from CPython `test_genericpath.py`""" xession.env.update( dict({"foo": "bar", "spam": "eggs", "a_bool": True, "an_int": 42, "none": None}) ) assert expandvars(inp) == exp
verify can invoke it, and usage knows about all the options
def test_tracer_help(capsys, xsh_with_aliases): """verify can invoke it, and usage knows about all the options""" spec = cmds_to_specs([("trace", "-h")], captured="stdout")[0] with pytest.raises(SystemExit): tracermain(["-h"], spec=spec) capout = capsys.readouterr().out pat = re.compile(r"^usage:\s*trace[^\n]*{([\w,-]+)}", re.MULTILINE) m = pat.match(capout) assert m[1] verbs = {v.strip().lower() for v in m[1].split(",")} assert verbs == {"rm", "start", "add", "on", "off", "del", "color", "stop", "ls"}
verify can invoke it, and usage knows about all the options
def test_xonfig_help(capsys, xession): """verify can invoke it, and usage knows about all the options""" with pytest.raises(SystemExit): xonfig_main(["-h"]) capout = capsys.readouterr().out pat = re.compile(r"^usage:\s*xonfig[^\n]*{([\w,-]+)}", re.MULTILINE) m = pat.match(capout) assert m[1] verbs = {v.strip().lower() for v in m[1].split(",")} assert verbs == { "info", "styles", "wizard", "web", "colors", "tutorial", }
info works, and reports no jupyter if none in environment
def test_xonfig_info(args, xession): """info works, and reports no jupyter if none in environment""" capout = xonfig_main(args) assert capout.startswith("+---") assert capout.endswith("---+\n") pat = re.compile(r".*history backend\s+\|\s+", re.MULTILINE | re.IGNORECASE) m = pat.search(capout) assert m
Same as tmpdir but also adds/removes it to the front of sys.path. Also cleans out any modules loaded as part of the test.
def tmpmod(tmpdir): """ Same as tmpdir but also adds/removes it to the front of sys.path. Also cleans out any modules loaded as part of the test. """ sys.path.insert(0, str(tmpdir)) loadedmods = set(sys.modules.keys()) try: yield tmpdir finally: del sys.path[0] newmods = set(sys.modules.keys()) - loadedmods for m in newmods: del sys.modules[m]
Tests what get's exported from a module without __all__
def test_noall(tmpmod): """ Tests what get's exported from a module without __all__ """ with tmpmod.mkdir("xontrib").join("spameggs.py").open("w") as x: x.write( """ spam = 1 eggs = 2 _foobar = 3 """ ) ctx = xontrib_context("spameggs") assert ctx == {"spam": 1, "eggs": 2}
Tests what get's exported from a module with __all__
def test_withall(tmpmod): """ Tests what get's exported from a module with __all__ """ with tmpmod.mkdir("xontrib").join("spameggs.py").open("w") as x: x.write( """ __all__ = 'spam', '_foobar' spam = 1 eggs = 2 _foobar = 3 """ ) ctx = xontrib_context("spameggs") assert ctx == {"spam": 1, "_foobar": 3}
Test that .xsh xontribs are loadable
def test_xshxontrib(tmpmod): """ Test that .xsh xontribs are loadable """ with tmpmod.mkdir("xontrib").join("script.xsh").open("w") as x: x.write( """ hello = 'world' """ ) ctx = xontrib_context("script") assert ctx == {"hello": "world"}
Test that .xsh xontribs are loadable
def test_xontrib_load(tmpmod): """ Test that .xsh xontribs are loadable """ with tmpmod.mkdir("xontrib").join("script.xsh").open("w") as x: x.write( """ hello = 'world' """ ) xontribs_load(["script"]) assert "script" in xontribs_loaded()
Test that .xsh xontribs are loadable
def test_xontrib_load_dashed(tmpmod): """ Test that .xsh xontribs are loadable """ with tmpmod.mkdir("xontrib").join("scri-pt.xsh").open("w") as x: x.write( """ hello = 'world' """ ) xontribs_load(["scri-pt"]) assert "scri-pt" in xontribs_loaded()
Return a dict with vc and a temporary dir that is a repository for testing.
def repo(request, tmpdir_factory): """Return a dict with vc and a temporary dir that is a repository for testing. """ vc = request.param temp_dir = Path(tmpdir_factory.mktemp("dir")) os.chdir(temp_dir) try: for init_command in VC_INIT[vc]: sp.call([vc] + init_command) except FileNotFoundError: pytest.skip(f"cannot find {vc} executable") if vc == "git": _init_git_repository(temp_dir) return {"vc": vc, "dir": temp_dir}
Completion for "cd", includes only valid directory names.
def xonsh_complete(command: CommandContext): """ Completion for "cd", includes only valid directory names. """ results, lprefix = complete_dir(command) if len(results) == 0: raise StopIteration return results, lprefix
Completes python's package manager pip.
def xonsh_complete(ctx: CommandContext): """Completes python's package manager pip.""" return comp_based_completer(ctx, PIP_AUTO_COMPLETE="1")
Completion for "rmdir", includes only valid directory names.
def xonsh_complete(ctx: CommandContext): """ Completion for "rmdir", includes only valid directory names. """ # if starts with the given prefix then it will get completions from man page if not ctx.prefix.startswith("-") and ctx.arg_index > 0: comps, lprefix = complete_dir(ctx) if not comps: raise StopIteration # no further file completions return comps, lprefix
Completer for ``xonsh`` command using its ``argparser``
def xonsh_complete(command: CommandContext): """Completer for ``xonsh`` command using its ``argparser``""" from xonsh.main import parser completer = ArgparseCompleter(parser, command=command) return completer.complete(), False
Dispatches the appropriate eval alias based on the number of args to the original callable alias and how many arguments to apply.
def partial_eval_alias(f, acc_args=()): """Dispatches the appropriate eval alias based on the number of args to the original callable alias and how many arguments to apply. """ # no partial needed if no extra args if not acc_args: return f # need to dispatch numargs = 0 for name, param in inspect.signature(f).parameters.items(): if ( param.kind == param.POSITIONAL_ONLY or param.kind == param.POSITIONAL_OR_KEYWORD ): numargs += 1 elif name in ALIAS_KWARG_NAMES and param.kind == param.KEYWORD_ONLY: numargs += 1 if numargs < 7: return PARTIAL_EVAL_ALIASES[numargs](f, acc_args=acc_args) else: e = "Expected proxy with 6 or fewer arguments for {}, not {}" raise XonshError(e.format(", ".join(ALIAS_KWARG_NAMES), numargs))
Sends signal to exit shell.
def xonsh_exit(args, stdin=None): """Sends signal to exit shell.""" if not clean_jobs(): # Do not exit if jobs not cleaned up return None, None XSH.exit = True print() # gimme a newline return None, None
Clears __xonsh__.ctx
def xonsh_reset(args, stdin=None): """Clears __xonsh__.ctx""" XSH.ctx.clear()
Sources a file written in a foreign shell language. Parameters ---------- shell Name or path to the foreign shell files_or_code file paths to source or code in the target language. interactive : -i, --interactive whether the sourced shell should be interactive login : -l, --login whether the sourced shell should be login envcmd : --envcmd command to print environment aliascmd : --aliascmd command to print aliases extra_args : --extra-args extra arguments needed to run the shell safe : -u, --unsafe whether the source shell should be run safely, and not raise any errors, even if they occur. prevcmd : -p, --prevcmd command(s) to run before any other commands, replaces traditional source. postcmd : --postcmd command(s) to run after all other commands funcscmd : --funcscmd code to find locations of all native functions in the shell language. sourcer : --sourcer the source command in the target shell language. If this is not set, a default value will attempt to be looked up based on the shell name. use_tmpfile : --use-tmpfile whether the commands for source shell should be written to a temporary file. seterrprevcmd : --seterrprevcmd command(s) to set exit-on-error before any other commands. seterrpostcmd : --seterrpostcmd command(s) to set exit-on-error after all other commands. overwrite_aliases : --overwrite-aliases flag for whether or not sourced aliases should replace the current xonsh aliases. suppress_skip_message : --suppress-skip-message flag for whether or not skip messages should be suppressed. show : --show show the script output. dryrun : -d, --dry-run Will not actually source the file.
def source_foreign_fn( shell: str, files_or_code: Annotated[list[str], Arg(nargs="+")], interactive=False, login=False, envcmd=None, aliascmd=None, extra_args="", safe=True, prevcmd="", postcmd="", funcscmd="", sourcer=None, use_tmpfile=False, seterrprevcmd=None, seterrpostcmd=None, overwrite_aliases=False, suppress_skip_message=False, show=False, dryrun=False, _stderr=None, ): """Sources a file written in a foreign shell language. Parameters ---------- shell Name or path to the foreign shell files_or_code file paths to source or code in the target language. interactive : -i, --interactive whether the sourced shell should be interactive login : -l, --login whether the sourced shell should be login envcmd : --envcmd command to print environment aliascmd : --aliascmd command to print aliases extra_args : --extra-args extra arguments needed to run the shell safe : -u, --unsafe whether the source shell should be run safely, and not raise any errors, even if they occur. prevcmd : -p, --prevcmd command(s) to run before any other commands, replaces traditional source. postcmd : --postcmd command(s) to run after all other commands funcscmd : --funcscmd code to find locations of all native functions in the shell language. sourcer : --sourcer the source command in the target shell language. If this is not set, a default value will attempt to be looked up based on the shell name. use_tmpfile : --use-tmpfile whether the commands for source shell should be written to a temporary file. seterrprevcmd : --seterrprevcmd command(s) to set exit-on-error before any other commands. seterrpostcmd : --seterrpostcmd command(s) to set exit-on-error after all other commands. overwrite_aliases : --overwrite-aliases flag for whether or not sourced aliases should replace the current xonsh aliases. suppress_skip_message : --suppress-skip-message flag for whether or not skip messages should be suppressed. show : --show show the script output. dryrun : -d, --dry-run Will not actually source the file. """ extra_args = tuple(extra_args.split()) env = XSH.env suppress_skip_message = ( env.get("FOREIGN_ALIASES_SUPPRESS_SKIP_MESSAGE") if not suppress_skip_message else suppress_skip_message ) files: tuple[str, ...] = () if prevcmd: pass # don't change prevcmd if given explicitly elif os.path.isfile(files_or_code[0]): if not sourcer: return (None, "xonsh: error: `sourcer` command is not mentioned.\n", 1) # we have filenames to source prevcmd = "".join([f"{sourcer} {f}\n" for f in files_or_code]) files = tuple(files_or_code) elif not prevcmd: prevcmd = " ".join(files_or_code) # code to run, no files foreign_shell_data.cache_clear() # make sure that we don't get prev src fsenv, fsaliases = foreign_shell_data( shell=shell, login=login, interactive=interactive, envcmd=envcmd, aliascmd=aliascmd, extra_args=extra_args, safe=safe, prevcmd=prevcmd, postcmd=postcmd, funcscmd=funcscmd or None, # the default is None in the called function sourcer=sourcer, use_tmpfile=use_tmpfile, seterrprevcmd=seterrprevcmd, seterrpostcmd=seterrpostcmd, show=show, dryrun=dryrun, files=files, ) if fsenv is None: if dryrun: return else: msg = f"xonsh: error: Source failed: {prevcmd!r}\n" msg += "xonsh: error: Possible reasons: File not found or syntax error\n" return (None, msg, 1) # apply results denv = env.detype() for k, v in fsenv.items(): if k == "SHLVL": # ignore $SHLVL as sourcing should not change $SHLVL continue if k in denv and v == denv[k]: continue # no change from original env[k] = v # Remove any env-vars that were unset by the script. for k in denv: if k not in fsenv: env.pop(k, None) # Update aliases baliases = XSH.aliases for k, v in fsaliases.items(): if k in baliases and v == baliases[k]: continue # no change from original elif overwrite_aliases or k not in baliases: baliases[k] = v elif suppress_skip_message: pass else: msg = ( "Skipping application of {0!r} alias from {1!r} " "since it shares a name with an existing xonsh alias. " 'Use "--overwrite-alias" option to apply it anyway. ' 'You may prevent this message with "--suppress-skip-message" or ' '"$FOREIGN_ALIASES_SUPPRESS_SKIP_MESSAGE = True".' ) print(msg.format(k, shell), file=_stderr)
Executes the contents of the provided files in the current context. If sourced file isn't found in cwd, search for file along $PATH to source instead.
def source_alias(args, stdin=None): """Executes the contents of the provided files in the current context. If sourced file isn't found in cwd, search for file along $PATH to source instead. """ env = XSH.env encoding = env.get("XONSH_ENCODING") errors = env.get("XONSH_ENCODING_ERRORS") for i, fname in enumerate(args): fpath = fname if not os.path.isfile(fpath): fpath = locate_binary(fname) if fpath is None: if env.get("XONSH_DEBUG"): print(f"source: {fname}: No such file", file=sys.stderr) if i == 0: raise RuntimeError( "must source at least one file, " + fname + " does not exist." ) break _, fext = os.path.splitext(fpath) if fext and fext != ".xsh" and fext != ".py": raise RuntimeError( "attempting to source non-xonsh file! If you are " "trying to source a file in another language, " "then please use the appropriate source command. " "For example, source-bash script.sh" ) with open(fpath, encoding=encoding, errors=errors) as fp: src = fp.read() if not src.endswith("\n"): src += "\n" ctx = XSH.ctx updates = {"__file__": fpath, "__name__": os.path.abspath(fpath)} with env.swap(**make_args_env(args[i + 1 :])), swap_values(ctx, updates): try: XSH.builtins.execx(src, "exec", ctx, filename=fpath) except Exception: print_color( "{RED}You may be attempting to source non-xonsh file! " "{RESET}If you are trying to source a file in " "another language, then please use the appropriate " "source command. For example, {GREEN}source-bash " "script.sh{RESET}", file=sys.stderr, ) raise
Source cmd.exe files Parameters ---------- files paths to source files. login : -l, --login whether the sourced shell should be login envcmd : --envcmd command to print environment aliascmd : --aliascmd command to print aliases extra_args : --extra-args extra arguments needed to run the shell safe : -s, --safe whether the source shell should be run safely, and not raise any errors, even if they occur. postcmd : --postcmd command(s) to run after all other commands funcscmd : --funcscmd code to find locations of all native functions in the shell language. seterrprevcmd : --seterrprevcmd command(s) to set exit-on-error before any other commands. overwrite_aliases : --overwrite-aliases flag for whether or not sourced aliases should replace the current xonsh aliases. suppress_skip_message : --suppress-skip-message flag for whether or not skip messages should be suppressed. show : --show show the script output. dryrun : -d, --dry-run Will not actually source the file.
def source_cmd_fn( files: Annotated[list[str], Arg(nargs="+")], login=False, aliascmd=None, extra_args="", safe=True, postcmd="", funcscmd="", seterrprevcmd=None, overwrite_aliases=False, suppress_skip_message=False, show=False, dryrun=False, _stderr=None, ): """ Source cmd.exe files Parameters ---------- files paths to source files. login : -l, --login whether the sourced shell should be login envcmd : --envcmd command to print environment aliascmd : --aliascmd command to print aliases extra_args : --extra-args extra arguments needed to run the shell safe : -s, --safe whether the source shell should be run safely, and not raise any errors, even if they occur. postcmd : --postcmd command(s) to run after all other commands funcscmd : --funcscmd code to find locations of all native functions in the shell language. seterrprevcmd : --seterrprevcmd command(s) to set exit-on-error before any other commands. overwrite_aliases : --overwrite-aliases flag for whether or not sourced aliases should replace the current xonsh aliases. suppress_skip_message : --suppress-skip-message flag for whether or not skip messages should be suppressed. show : --show show the script output. dryrun : -d, --dry-run Will not actually source the file. """ args = list(files) fpath = locate_binary(args[0]) args[0] = fpath if fpath else args[0] if not os.path.isfile(args[0]): return (None, f"xonsh: error: File not found: {args[0]}\n", 1) prevcmd = "call " prevcmd += " ".join([argvquote(arg, force=True) for arg in args]) prevcmd = escape_windows_cmd_string(prevcmd) with XSH.env.swap(PROMPT="$P$G"): return source_foreign_fn( shell="cmd", files_or_code=args, interactive=True, sourcer="call", envcmd="set", seterrpostcmd="if errorlevel 1 exit 1", use_tmpfile=True, prevcmd=prevcmd, # from this function login=login, aliascmd=aliascmd, extra_args=extra_args, safe=safe, postcmd=postcmd, funcscmd=funcscmd, seterrprevcmd=seterrprevcmd, overwrite_aliases=overwrite_aliases, suppress_skip_message=suppress_skip_message, show=show, dryrun=dryrun, )
exec (also aliased as xexec) uses the os.execvpe() function to replace the xonsh process with the specified program. This provides the functionality of the bash 'exec' builtin:: >>> exec bash -l -i bash $ Parameters ---------- command program to launch along its arguments login : -l, --login the shell places a dash at the beginning of the zeroth argument passed to command to simulate login shell. clean : -c, --clean causes command to be executed with an empty environment. name : -a, --name the shell passes name as the zeroth argument to the executed command. Notes ----- This command **is not** the same as the Python builtin function exec(). That function is for running Python code. This command, which shares the same name as the sh-lang statement, is for launching a command directly in the same process. In the event of a name conflict, please use the xexec command directly or dive into subprocess mode explicitly with ![exec command]. For more details, please see http://xon.sh/faq.html#exec.
def xexec_fn( command: Annotated[list[str], Arg(nargs=argparse.REMAINDER)], login=False, clean=False, name="", _stdin=None, ): """exec (also aliased as xexec) uses the os.execvpe() function to replace the xonsh process with the specified program. This provides the functionality of the bash 'exec' builtin:: >>> exec bash -l -i bash $ Parameters ---------- command program to launch along its arguments login : -l, --login the shell places a dash at the beginning of the zeroth argument passed to command to simulate login shell. clean : -c, --clean causes command to be executed with an empty environment. name : -a, --name the shell passes name as the zeroth argument to the executed command. Notes ----- This command **is not** the same as the Python builtin function exec(). That function is for running Python code. This command, which shares the same name as the sh-lang statement, is for launching a command directly in the same process. In the event of a name conflict, please use the xexec command directly or dive into subprocess mode explicitly with ![exec command]. For more details, please see http://xon.sh/faq.html#exec. """ if len(command) == 0: return (None, "xonsh: exec: no command specified\n", 1) cmd = command[0] if name: command[0] = name if login: command[0] = f"-{command[0]}" denv = {} if not clean: denv = XSH.env.detype() # decrement $SHLVL to mirror bash's behaviour if "SHLVL" in denv: old_shlvl = to_shlvl(denv["SHLVL"]) denv["SHLVL"] = str(adjust_shlvl(old_shlvl, -1)) try: os.execvpe(cmd, command, denv) except FileNotFoundError as e: return ( None, f"xonsh: exec: file not found: {e.args[1]}: {command[0]}" "\n", 1, )
Runs the xonsh configuration utility.
def xonfig(): """Runs the xonsh configuration utility.""" from xonsh.xonfig import xonfig_main # lazy import return xonfig_main
Runs the xonsh tracer utility.
def trace(args, stdin=None, stdout=None, stderr=None, spec=None): """Runs the xonsh tracer utility.""" from xonsh.tracer import tracermain # lazy import try: return tracermain(args, stdin=stdin, stdout=stdout, stderr=stderr, spec=spec) except SystemExit: pass
usage: showcmd [-h|--help|cmd args] Displays the command and arguments as a list of strings that xonsh would run in subprocess mode. This is useful for determining how xonsh evaluates your commands and arguments prior to running these commands. optional arguments: -h, --help show this help message and exit Examples -------- >>> showcmd echo $USER "can't" hear "the sea" ['echo', 'I', "can't", 'hear', 'the sea']
def showcmd(args, stdin=None): """usage: showcmd [-h|--help|cmd args] Displays the command and arguments as a list of strings that xonsh would run in subprocess mode. This is useful for determining how xonsh evaluates your commands and arguments prior to running these commands. optional arguments: -h, --help show this help message and exit Examples -------- >>> showcmd echo $USER "can't" hear "the sea" ['echo', 'I', "can't", 'hear', 'the sea'] """ if len(args) == 0 or (len(args) == 1 and args[0] in {"-h", "--help"}): print(showcmd.__doc__.rstrip().replace("\n ", "\n")) else: sys.displayhook(args)
Determines the correct invocation to get xonsh's pip
def detect_xpip_alias(): """ Determines the correct invocation to get xonsh's pip """ if not getattr(sys, "executable", None): return lambda args, stdin=None: ( "", "Sorry, unable to run pip on your system (missing sys.executable)", 1, ) basecmd = [sys.executable, "-m", "pip"] try: if ON_WINDOWS: # XXX: Does windows have an installation mode that requires UAC? return basecmd elif IN_APPIMAGE: # In AppImage `sys.executable` is equal to path to xonsh.AppImage file and the real python executable is in $_ return [ XSH.env.get("_", "APPIMAGE_PYTHON_EXECUTABLE_NOT_FOUND"), "-m", "pip", ] elif not os.access(os.path.dirname(sys.executable), os.W_OK): return ( sys.executable + " -m pip @(['install', '--user'] + $args[1:] if $args and $args[0] == 'install' else $args)" ) else: return basecmd except Exception: # Something freaky happened, return something that'll probably work return basecmd
Creates a new default aliases dictionary.
def make_default_aliases(): """Creates a new default aliases dictionary.""" default_aliases = { "cd": cd, "pushd": pushd, "popd": popd, "dirs": dirs, "jobs": jobs, "fg": fg, "bg": bg, "disown": disown, "EOF": xonsh_exit, "exit": xonsh_exit, "quit": xonsh_exit, "exec": xexec, "xexec": xexec, "source": source_alias, "source-zsh": SourceForeignAlias( func=functools.partial(source_foreign_fn, "zsh", sourcer="source"), has_args=True, prog="source-zsh", ), "source-bash": SourceForeignAlias( func=functools.partial(source_foreign_fn, "bash", sourcer="source"), has_args=True, prog="source-bash", ), "source-cmd": source_cmd, "source-foreign": source_foreign, "history": xhm.history_main, "trace": trace, "timeit": timeit_alias, "xonfig": xonfig, "scp-resume": ["rsync", "--partial", "-h", "--progress", "--rsh=ssh"], "showcmd": showcmd, "ipynb": ["jupyter", "notebook", "--no-browser"], "which": xxw.which, "xontrib": xontribs_main, "completer": xca.completer_alias, "xpip": detect_xpip_alias(), "xonsh-reset": xonsh_reset, } if ON_WINDOWS: # Borrow builtin commands from cmd.exe. windows_cmd_aliases = { "cls", "copy", "del", "dir", "echo", "erase", "md", "mkdir", "mklink", "move", "rd", "ren", "rename", "rmdir", "time", "type", "vol", } for alias in windows_cmd_aliases: default_aliases[alias] = [os.getenv("COMSPEC"), "/c", alias] default_aliases["call"] = ["source-cmd"] default_aliases["source-bat"] = ["source-cmd"] default_aliases["clear"] = "cls" if ON_ANACONDA: # Add aliases specific to the Anaconda python distribution. default_aliases["activate"] = ["source-cmd", "activate.bat"] default_aliases["deactivate"] = ["source-cmd", "deactivate.bat"] if shutil.which("sudo", path=XSH.env.get_detyped("PATH")): # XSH.commands_cache is not available during setup import xonsh.winutils as winutils def sudo(args): if len(args) < 1: print( "You need to provide an executable to run as " "Administrator." ) return cmd = args[0] if locate_binary(cmd): return winutils.sudo(cmd, args[1:]) elif cmd.lower() in windows_cmd_aliases: args = ["/D", "/C", "CD", _get_cwd(), "&&"] + args return winutils.sudo("cmd", args) else: msg = 'Cannot find the path for executable "{0}".' print(msg.format(cmd)) default_aliases["sudo"] = sudo elif ON_DARWIN: default_aliases["ls"] = ["ls", "-G"] elif ON_FREEBSD or ON_DRAGONFLY: default_aliases["grep"] = ["grep", "--color=auto"] default_aliases["egrep"] = ["egrep", "--color=auto"] default_aliases["fgrep"] = ["fgrep", "--color=auto"] default_aliases["ls"] = ["ls", "-G"] elif ON_NETBSD: default_aliases["grep"] = ["grep", "--color=auto"] default_aliases["egrep"] = ["egrep", "--color=auto"] default_aliases["fgrep"] = ["fgrep", "--color=auto"] elif ON_OPENBSD: pass else: default_aliases["grep"] = ["grep", "--color=auto"] default_aliases["egrep"] = ["egrep", "--color=auto"] default_aliases["fgrep"] = ["fgrep", "--color=auto"] default_aliases["ls"] = ["ls", "--color=auto", "-v"] return default_aliases
Converts a color name to the inner part of an ANSI escape code
def ansi_color_name_to_escape_code(name, style="default", cmap=None): """Converts a color name to the inner part of an ANSI escape code""" cmap = _ensure_color_map(style=style, cmap=cmap) if name in cmap: return cmap[name] m = RE_XONSH_COLOR.match(name) if m is None: raise ValueError(f"{name!r} is not a color!") parts = m.groupdict() # convert regex match into actual ANSI colors if parts["reset"] is not None: if parts["reset"] == "NO_COLOR": warn_deprecated_no_color() res = "0" elif parts["bghex"] is not None: res = "48;5;" + rgb_to_256(parts["bghex"][3:])[0] elif parts["background"] is not None: color = parts["color"] if "#" in color: res = "48;5;" + rgb_to_256(color[1:])[0] else: fgcolor = cmap[color] if fgcolor.isdecimal(): res = str(int(fgcolor) + 10) elif fgcolor.startswith("38;"): res = "4" + fgcolor[1:] elif fgcolor == "DEFAULT": res = "39" else: msg = ( "when converting {!r}, did not recognize {!r} within " "the following color map as a valid color:\n\n{!r}" ) raise ValueError(msg.format(name, fgcolor, cmap)) else: # have regular, non-background color mods = parts["modifiers"] if mods is None: mods = [] else: mods = mods.strip("_").split("_") mods = [ANSI_ESCAPE_MODIFIERS[mod] for mod in mods] color = parts["color"] if "#" in color: mods.append("38;5;" + rgb_to_256(color[1:])[0]) elif color == "DEFAULT": res = "39" else: mods.append(cmap[color]) res = ";".join(mods) cmap[name] = res return res
Formats a template string but only with respect to the colors. Another template string is returned, with the color values filled in. Parameters ---------- template : str The template string, potentially with color names. style : str, optional Style name to look up color map from. cmap : dict, optional A color map to use, this will prevent the color map from being looked up via the style name. hide : bool, optional Whether to wrap the color codes in the \001 and \002 escape codes, so that the color codes are not counted against line length. Returns ------- A template string with the color values filled in.
def ansi_partial_color_format(template, style="default", cmap=None, hide=False): """Formats a template string but only with respect to the colors. Another template string is returned, with the color values filled in. Parameters ---------- template : str The template string, potentially with color names. style : str, optional Style name to look up color map from. cmap : dict, optional A color map to use, this will prevent the color map from being looked up via the style name. hide : bool, optional Whether to wrap the color codes in the \\001 and \\002 escape codes, so that the color codes are not counted against line length. Returns ------- A template string with the color values filled in. """ try: return _ansi_partial_color_format_main( template, style=style, cmap=cmap, hide=hide ) except Exception: return template
Returns an iterable of all ANSI color style names.
def ansi_color_style_names(): """Returns an iterable of all ANSI color style names.""" return ANSI_STYLES.keys()