Beispiel #1
0
def premain(argv=None):
    """Setup for main xonsh entry point. Returns parsed arguments."""
    if argv is None:
        argv = sys.argv[1:]
    setup_timings()
    setproctitle = get_setproctitle()
    if setproctitle is not None:
        setproctitle(" ".join(["xonsh"] + argv))
    builtins.__xonsh__ = XonshSession()
    args = parser.parse_args(argv)
    if args.help:
        parser.print_help()
        parser.exit()
    if args.version:
        version = "/".join(("xonsh", __version__))
        print(version)
        parser.exit()
    shell_kwargs = {
        "shell_type": args.shell_type,
        "completer": False,
        "login": False,
        "scriptcache": args.scriptcache,
        "cacheall": args.cacheall,
        "ctx": builtins.__xonsh__.ctx,
    }
    if args.login:
        shell_kwargs["login"] = True
    if args.norc:
        shell_kwargs["rc"] = ()
    elif args.rc:
        shell_kwargs["rc"] = args.rc
    setattr(sys, "displayhook", _pprint_displayhook)
    if args.command is not None:
        args.mode = XonshMode.single_command
        shell_kwargs["shell_type"] = "none"
    elif args.file is not None:
        args.mode = XonshMode.script_from_file
        shell_kwargs["shell_type"] = "none"
    elif not sys.stdin.isatty() and not args.force_interactive:
        args.mode = XonshMode.script_from_stdin
        shell_kwargs["shell_type"] = "none"
    else:
        args.mode = XonshMode.interactive
        shell_kwargs["completer"] = True
        shell_kwargs["login"] = True
    env = start_services(shell_kwargs, args)
    env["XONSH_LOGIN"] = shell_kwargs["login"]
    if args.defines is not None:
        env.update([x.split("=", 1) for x in args.defines])
    env["XONSH_INTERACTIVE"] = args.force_interactive or (
        args.mode == XonshMode.interactive
    )
    if ON_WINDOWS:
        setup_win_unicode_console(env.get("WIN_UNICODE_CONSOLE", True))
    return args
Beispiel #2
0
def xonsh_builtins(monkeypatch, xonsh_events):
    """Mock out most of the builtins xonsh attributes."""
    old_builtins = set(dir(builtins))
    execer = getattr(getattr(builtins, "__xonsh__", None), "execer", None)
    session = XonshSession(execer=execer, ctx={})
    ensure_attached_session(monkeypatch, session)
    builtins.__xonsh__.env = DummyEnv()
    if ON_WINDOWS:
        builtins.__xonsh__.env["PATHEXT"] = [".EXE", ".BAT", ".CMD"]
    builtins.__xonsh__.shell = DummyShell()
    builtins.__xonsh__.help = lambda x: x
    builtins.__xonsh__.glob = glob.glob
    builtins.__xonsh__.exit = False
    builtins.__xonsh__.superhelp = lambda x: x
    builtins.__xonsh__.pathsearch = pathsearch
    builtins.__xonsh__.globsearch = globsearch
    builtins.__xonsh__.regexsearch = regexsearch
    builtins.__xonsh__.regexpath = lambda x: []
    builtins.__xonsh__.expand_path = lambda x: x
    builtins.__xonsh__.subproc_captured = sp
    builtins.__xonsh__.subproc_uncaptured = sp
    builtins.__xonsh__.stdout_uncaptured = None
    builtins.__xonsh__.stderr_uncaptured = None
    builtins.__xonsh__.ensure_list_of_strs = ensure_list_of_strs
    builtins.__xonsh__.commands_cache = DummyCommandsCache()
    builtins.__xonsh__.all_jobs = {}
    builtins.__xonsh__.list_of_strs_or_callables = list_of_strs_or_callables
    builtins.__xonsh__.list_of_list_of_strs_outer_product = (
        list_of_list_of_strs_outer_product
    )
    builtins.__xonsh__.history = DummyHistory()
    builtins.__xonsh__.subproc_captured_stdout = sp
    builtins.__xonsh__.subproc_captured_inject = sp
    builtins.__xonsh__.subproc_captured_object = sp
    builtins.__xonsh__.subproc_captured_hiddenobject = sp
    builtins.__xonsh__.enter_macro = enter_macro
    builtins.__xonsh__.completers = None
    builtins.__xonsh__.call_macro = call_macro
    builtins.__xonsh__.enter_macro = enter_macro
    builtins.__xonsh__.path_literal = path_literal
    builtins.__xonsh__.builtins = _BuiltIns(execer=execer)
    builtins.evalx = eval
    builtins.execx = None
    builtins.compilex = None
    builtins.aliases = {}
    # 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.
    builtins.events = xonsh_events
    yield builtins
    monkeypatch.delattr(builtins, "__xonsh__", raising=False)
    for attr in set(dir(builtins)) - old_builtins:
        if hasattr(builtins, attr):
            delattr(builtins, attr)
    tasks.clear()  # must to this to enable resetting all_jobs
Beispiel #3
0
def xonsh_execer(monkeypatch):
    """Initiate the Execer with a mocked nop `load_builtins`"""
    monkeypatch.setattr(
        "xonsh.built_ins.load_builtins.__code__",
        (lambda *args, **kwargs: None).__code__,
    )
    if not hasattr(builtins, "__xonsh__"):
        ensure_attached_session(XonshSession())
    execer = Execer(unload=False)
    builtins.__xonsh__.execer = execer
    return execer
Beispiel #4
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)
        builtins.__xonsh__ = XonshSession(ctx=ctx, execer=execer)
        load_builtins(ctx=ctx, execer=execer)
        builtins.__xonsh__.shell = Shell(execer,
                                         ctx=ctx,
                                         shell_type=shell_type)
    builtins.__xonsh__.env.update(env)
    install_import_hooks()
    builtins.aliases.update(aliases)
    if xontribs:
        xontribs_load(xontribs)
    tp = builtins.__xonsh__.commands_cache.threadable_predictors
    tp.update(threadable_predictors)
Beispiel #5
0
def premain(argv=None):
    """Setup for main xonsh entry point. Returns parsed arguments."""
    if argv is None:
        argv = sys.argv[1:]
    builtins.__xonsh__ = XonshSession()
    setup_timings(argv)
    setproctitle = get_setproctitle()
    if setproctitle is not None:
        setproctitle(" ".join(["xonsh"] + argv))
    args = parser.parse_args(argv)
    if args.help:
        parser.print_help()
        parser.exit()
    shell_kwargs = {
        "shell_type": args.shell_type,
        "completer": False,
        "login": False,
        "scriptcache": args.scriptcache,
        "cacheall": args.cacheall,
        "ctx": builtins.__xonsh__.ctx,
    }
    if args.login or sys.argv[0].startswith("-"):
        args.login = True
        shell_kwargs["login"] = True
    if args.norc:
        shell_kwargs["rc"] = ()
    elif args.rc:
        shell_kwargs["rc"] = args.rc
    setattr(sys, "displayhook", _pprint_displayhook)
    if args.command is not None:
        args.mode = XonshMode.single_command
        shell_kwargs["shell_type"] = "none"
    elif args.file is not None:
        args.mode = XonshMode.script_from_file
        shell_kwargs["shell_type"] = "none"
    elif not sys.stdin.isatty() and not args.force_interactive:
        args.mode = XonshMode.script_from_stdin
        shell_kwargs["shell_type"] = "none"
    else:
        args.mode = XonshMode.interactive
        shell_kwargs["completer"] = True
        shell_kwargs["login"] = True

    pre_env = {
        "XONSH_LOGIN":
        shell_kwargs["login"],
        "XONSH_INTERACTIVE":
        args.force_interactive or (args.mode == XonshMode.interactive),
    }
    env = start_services(shell_kwargs, args, pre_env=pre_env)
    if args.defines is not None:
        env.update([x.split("=", 1) for x in args.defines])
    return args
Beispiel #6
0
def xonsh_execer(monkeypatch):
    """Initiate the Execer with a mocked nop `load_builtins`"""
    monkeypatch.setattr(
        "xonsh.built_ins.load_builtins.__code__",
        (lambda *args, **kwargs: None).__code__,
    )
    added_session = False
    if not hasattr(builtins, "__xonsh__"):
        added_session = True
        ensure_attached_session(monkeypatch, XonshSession())
    execer = Execer(unload=False)
    builtins.__xonsh__.execer = execer
    yield execer
    if added_session:
        monkeypatch.delattr(builtins, "__xonsh__", raising=False)
Beispiel #7
0
def ctx():
    """Context in which the ptk multiline functionality will be tested."""
    builtins.__xonsh__ = XonshSession()
    builtins.__xonsh__.env = DummyEnv()
    builtins.__xonsh__.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,
    )
    del builtins.__xonsh__.env
    del builtins.__xonsh__
Beispiel #8
0
    def create(cls) -> "Shell":
        import signal
        from xonsh.built_ins import load_builtins
        from xonsh.built_ins import XonshSession
        from xonsh.imphooks import install_import_hooks
        from xonsh.main import _pprint_displayhook
        from xonsh.xontribs import xontribs_load
        import xonsh.history.main as xhm

        ctx: Dict[str, Any] = {}

        execer = Execer(xonsh_ctx=ctx)

        builtins.__xonsh__ = XonshSession(ctx=ctx,
                                          execer=execer)  # type: ignore
        load_builtins(ctx=ctx, execer=execer)
        env = builtins.__xonsh__.env  # type: ignore
        env.update({"XONSH_INTERACTIVE": True, "SHELL_TYPE": "prompt_toolkit"})
        builtins.__xonsh__.history = xhm.construct_history(  # type: ignore
            env=env.detype(),
            ts=[time.time(), None],
            locked=True)

        builtins.__xonsh__.history.gc.wait_for_shell = False  # type: ignore

        setattr(sys, "displayhook", _pprint_displayhook)

        install_import_hooks()
        builtins.aliases.update({"ll": "ls -alF"})  # type: ignore
        xontribs_load([""])

        def func_sig_ttin_ttou(n: Any, f: Any) -> None:
            pass

        signal.signal(signal.SIGTTIN, func_sig_ttin_ttou)
        signal.signal(signal.SIGTTOU, func_sig_ttin_ttou)

        shell = cls(execer)
        builtins.__xonsh__.shell = shell  # type: ignore
        builtins.__xonsh__.shell.shell = shell  # type: ignore

        return shell