Exemplo n.º 1
0
def load_command_cache(xession):
    gc.collect()
    XSH.unload()
    XSH.load()
    if ON_WINDOWS:
        for key in ("cd", "bash"):
            xession.aliases[key] = lambda *args, **kwargs: None
Exemplo n.º 2
0
def xonsh_execer(monkeypatch):
    """Initiate the Execer with a mocked nop `load_builtins`"""
    execer = Execer()
    XSH.load(execer=execer)
    # TODO this monkeypatch *shouldn't* be useful now.
    monkeypatch.setattr(XSH, "execer", execer)
    yield execer
Exemplo n.º 3
0
def install_import_hooks(execer=ARG_NOT_PRESENT):
    """
    Install Xonsh import hooks in ``sys.meta_path`` in order for ``.xsh`` files
    to be importable and import events to be fired.

    Can safely be called many times, will be no-op if xonsh import hooks are
    already present.
    """
    if execer is ARG_NOT_PRESENT:
        print_warning("No execer was passed to install_import_hooks. "
                      "This will become an error in future.")
        execer = XSH.execer
        if execer is None:
            execer = Execer()
            XSH.load(execer=execer)

    found_imp = found_event = False
    for hook in sys.meta_path:
        if isinstance(hook, XonshImportHook):
            found_imp = True
        elif isinstance(hook, XonshImportEventHook):
            found_event = True
    if not found_imp:
        sys.meta_path.append(XonshImportHook(execer))
    if not found_event:
        sys.meta_path.insert(0, XonshImportEventHook())
Exemplo n.º 4
0
def start_services(shell_kwargs, args, pre_env=None):
    """Starts up the essential services in the proper order.
    This returns the environment instance as a convenience.
    """
    if pre_env is None:
        pre_env = {}
    # create execer, which loads builtins
    ctx = shell_kwargs.get("ctx", {})
    debug = to_bool_or_int(os.getenv("XONSH_DEBUG", "0"))
    events.on_timingprobe.fire(name="pre_execer_init")
    execer = Execer(
        filename="<stdin>",
        debug_level=debug,
        scriptcache=shell_kwargs.get("scriptcache", True),
        cacheall=shell_kwargs.get("cacheall", False),
    )
    XSH.load(ctx=ctx, execer=execer)
    events.on_timingprobe.fire(name="post_execer_init")

    install_import_hooks(execer)

    env = XSH.env
    for k, v in pre_env.items():
        env[k] = v

    _autoload_xontribs(env)
    _load_rc_files(shell_kwargs, args, env, execer, ctx)
    # create shell
    XSH.shell = Shell(execer=execer, **shell_kwargs)
    ctx["__name__"] = "__main__"
    return env
Exemplo n.º 5
0
def start_services(shell_kwargs, args, pre_env=None):
    """Starts up the essential services in the proper order.
    This returns the environment instance as a convenience.
    """
    if pre_env is None:
        pre_env = {}
    # create execer, which loads builtins
    ctx = shell_kwargs.get("ctx", {})
    debug = to_bool_or_int(os.getenv("XONSH_DEBUG", "0"))
    events.on_timingprobe.fire(name="pre_execer_init")
    execer = Execer(
        debug_level=debug,
        scriptcache=shell_kwargs.get("scriptcache", True),
        cacheall=shell_kwargs.get("cacheall", False),
    )
    XSH.load(ctx=ctx, execer=execer)
    events.on_timingprobe.fire(name="post_execer_init")

    install_import_hooks(execer)

    # load rc files
    login = shell_kwargs.get("login", True)
    rc_cli = shell_kwargs.get("rc")
    env = XSH.env
    for k, v in pre_env.items():
        env[k] = v

    # determine which RC files to load, including whether any RC directories
    # should be scanned for such files
    if shell_kwargs.get("norc") or (args.mode != XonshMode.interactive
                                    and not args.force_interactive
                                    and not args.login):
        # if --no-rc was passed, or we're not in an interactive shell and
        # interactive mode was not forced, then disable loading RC files and dirs
        rc = ()
        rcd = ()
    elif rc_cli:
        # if an explicit --rc was passed, then we should load only that RC
        # file, and nothing else (ignore both XONSHRC and XONSHRC_DIR)
        rc = [r for r in rc_cli if os.path.isfile(r)]
        rcd = [r for r in rc_cli if os.path.isdir(r)]
    else:
        # otherwise, get the RC files from XONSHRC, and RC dirs from XONSHRC_DIR
        rc = env.get("XONSHRC")
        rcd = env.get("XONSHRC_DIR")

    events.on_pre_rc.fire()
    XSH.rc_files = xonshrc_context(rcfiles=rc,
                                   rcdirs=rcd,
                                   execer=execer,
                                   ctx=ctx,
                                   env=env,
                                   login=login)
    events.on_post_rc.fire()
    # create shell
    XSH.shell = Shell(execer=execer, **shell_kwargs)
    ctx["__name__"] = "__main__"
    return env
Exemplo n.º 6
0
def xsh():
    from xonsh.built_ins import XSH

    XSH.load()
    from xontrib.powerline3 import main

    main()
    yield XSH
    XSH.unload()
Exemplo n.º 7
0
def xonsh_builtins(monkeypatch, xonsh_events, session_vars):
    """Mock out most of the builtins xonsh attributes."""
    old_builtins = dict(vars(builtins).items())  # type: ignore

    XSH.load(ctx={}, **session_vars)

    def locate_binary(self, name):
        return os.path.join(os.path.dirname(__file__), "bin", name)

    for attr, val in [
        ("env", DummyEnv()),
        ("shell", DummyShell()),
        ("help", lambda x: x),
        ("aliases", Aliases()),
        ("exit", False),
        ("history", DummyHistory()),
            # ("subproc_captured", sp),
        ("subproc_uncaptured", sp),
        ("subproc_captured_stdout", sp),
        ("subproc_captured_inject", sp),
        ("subproc_captured_object", sp),
        ("subproc_captured_hiddenobject", sp),
    ]:
        monkeypatch.setattr(XSH, attr, val)

    if ON_WINDOWS:
        XSH.env["PATHEXT"] = [".EXE", ".BAT", ".CMD"]

    cc = XSH.commands_cache
    monkeypatch.setattr(cc, "locate_binary",
                        types.MethodType(locate_binary, cc))
    monkeypatch.setattr(cc, "_cmds_cache", {})

    for attr, val in [
        ("evalx", eval),
        ("execx", None),
        ("compilex", None),
            # Unlike all the other stuff, this has to refer to the "real" one because all modules that would
            # be firing events on the global instance.
        ("events", xonsh_events),
    ]:
        # attributes to builtins are dynamicProxy and should pickup the following
        monkeypatch.setattr(XSH.builtins, attr, val)

    # todo: remove using builtins for tests at all
    yield builtins
    XSH.unload()
    for attr in set(dir(builtins)) - set(old_builtins):
        if hasattr(builtins, attr):
            delattr(builtins, attr)
    for attr, old_value in old_builtins.items():
        setattr(builtins, attr, old_value)

    tasks.clear()  # must to this to enable resetting all_jobs
Exemplo n.º 8
0
def session_vars():
    """keep costly vars per session"""
    from xonsh.environ import Env, default_env
    from xonsh.commands_cache import CommandsCache

    execer = Execer()
    XSH.load(execer=execer)
    return {
        "execer": execer,
        "env": Env(default_env()),
        "commands_cache": CommandsCache(),
    }
Exemplo n.º 9
0
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,
        commands_cache=commands_cache.CommandsCache(),
        env=os_env,
    )
    yield XSH
    XSH.unload()
    tasks.clear()  # must to this to enable resetting all_jobs
Exemplo n.º 10
0
def setup(
    ctx=None,
    shell_type="none",
    env=(("RAISE_SUBPROC_ERROR", True),),
    aliases=(),
    xontribs=(),
    threadable_predictors=(),
):
    """Starts up a new xonsh shell. Calling this in function in another
    packages ``__init__.py`` will allow xonsh to be fully used in the
    package in headless or headed mode. This function is primarily indended to
    make starting up xonsh for 3rd party packages easier.

    Here is example of using this at the top of an ``__init__.py``::

        from xonsh.main import setup
        setup()
        del setup

    Parameters
    ----------
    ctx : dict-like or None, optional
        The xonsh context to start with. If None, an empty dictionary
        is provided.
    shell_type : str, optional
        The type of shell to start. By default this is 'none', indicating
        we should start in headless mode.
    env : dict-like, optional
        Environment to update the current environment with after the shell
        has been initialized.
    aliases : dict-like, optional
        Aliases to add after the shell has been initialized.
    xontribs : iterable of str, optional
        Xontrib names to load.
    threadable_predictors : dict-like, optional
        Threadable predictors to start up with. These overide the defaults.
    """
    ctx = {} if ctx is None else ctx
    # setup xonsh ctx and execer
    if not hasattr(builtins, "__xonsh__"):
        execer = Execer(xonsh_ctx=ctx)
        XSH.load(
            ctx=ctx, execer=execer, shell=Shell(execer, ctx=ctx, shell_type=shell_type)
        )
    XSH.env.update(env)
    install_import_hooks()
    XSH.aliases.update(aliases)
    if xontribs:
        xontribs_load(xontribs)
    tp = XSH.commands_cache.threadable_predictors
    tp.update(threadable_predictors)
Exemplo n.º 11
0
 def __init__(
     self,
     filename="<xonsh-code>",
     debug_level=0,
     parser_args=None,
     unload=True,
     xonsh_ctx=None,
     scriptcache=True,
     cacheall=False,
 ):
     """Parameters
     ----------
     filename : str, optional
         File we are to execute.
     debug_level : int, optional
         Debugging level to use in lexing and parsing.
     parser_args : dict, optional
         Arguments to pass down to the parser.
     unload : bool, optional
         Whether or not to unload xonsh builtins upon deletion.
     xonsh_ctx : dict or None, optional
         Xonsh xontext to load as xonsh.built_ins.XSH.ctx
     scriptcache : bool, optional
         Whether or not to use a precompiled bytecode cache when execing
         code, default: True.
     cacheall : bool, optional
         Whether or not to cache all xonsh code, and not just files. If this
         is set to true, it will cache command line input too, default: False.
     """
     parser_args = parser_args or {}
     self.parser = Parser(**parser_args)
     self.filename = filename
     self._default_filename = filename
     self.debug_level = debug_level
     self.unload = unload
     self.scriptcache = scriptcache
     self.cacheall = cacheall
     self.ctxtransformer = CtxAwareTransformer(self.parser)
     XSH.load(execer=self, ctx=xonsh_ctx)