Example #1
0
def main(argv):
    global ROOT
    parser = argparse.ArgumentParser(
        description='An automatic programming contest judge.')
    parser.add_argument('contest', help='the contest directory')
    parser.add_argument('-d',
                        "--directory",
                        default=None,
                        help="The root directory")
    opts = parser.parse_args(argv)

    sh_parser = Parser(lexer_table='lexer_table',
                       yacc_table='parser_table',
                       outputdir=os.path.join(BASE_DIR, "xonsh", "xonsh"))
    if opts.directory:
        ROOT = opts.directory
    else:
        ROOT = tempfile.mkdtemp(prefix="epsilon")
    os.chdir(ROOT)
    os.environ["USER"] = "******"

    shell.load_contest(opts.contest)

    cmd = Shell()
    cmd.execer.parser = sh_parser
    setup_shortcuts()
    setup_aliases()
    setup_env()
    cmd.cmdloop()
Example #2
0
File: main.py Project: Cynary/xonsh
def main(argv=None):
    """Main entry point for xonsh cli."""
    args = parser.parse_args()
    shell = Shell() if not args.norc else Shell(ctx={})
    from xonsh import imphooks
    env = builtins.__xonsh_env__
    if args.defines is not None:
        env.update([x.split('=', 1) for x in args.defines])
    env['XONSH_INTERACTIVE'] = False
    if args.command is not None:
        # run a single command and exit
        shell.default(args.command)
    elif args.file is not None:
        # run a script contained in a file
        if os.path.isfile(args.file):
            with open(args.file) as f:
                code = f.read()
            code = code if code.endswith('\n') else code + '\n'
            env['ARGS'] = [args.file] + args.args
            code = shell.execer.compile(code, mode='exec', glbs=shell.ctx)
            shell.execer.exec(code, mode='exec', glbs=shell.ctx)
        else:
            print('xonsh: {0}: No such file or directory.'.format(args.file))
    elif not sys.stdin.isatty():
        # run a script given on stdin
        code = sys.stdin.read()
        code = code if code.endswith('\n') else code + '\n'
        code = shell.execer.compile(code, mode='exec', glbs=shell.ctx)
        shell.execer.exec(code, mode='exec', glbs=shell.ctx)
    else:
        # otherwise, enter the shell
        env['XONSH_INTERACTIVE'] = True
        ignore_sigtstp()
        shell.cmdloop()
Example #3
0
def ctx():
    """Create a global Shell instance to use in all the test."""
    ctx = {'PATH': []}
    execer = Execer(xonsh_ctx=ctx)
    builtins.__xonsh_shell__ = Shell(execer=execer, ctx=ctx)
    yield
    del builtins.__xonsh_shell__
Example #4
0
def ctx():
    """Create a global Shell instance to use in all the test."""
    ctx = {"PATH": []}
    execer = Execer(xonsh_ctx=ctx)
    builtins.__xonsh__.shell = Shell(execer=execer, ctx=ctx, shell_type="none")
    yield
    builtins.__xonsh__.shell = None
Example #5
0
def premain(argv=None):
    """Setup for main xonsh entry point, returns parsed arguments."""
    args, other = parser.parse_known_args(argv)
    if args.file is not None:
        real_argv = (argv or sys.argv)
        i = real_argv.index(args.file)
        args.args = real_argv[i+1:]
        undo_args(args)
    if args.help:
        parser.print_help()
        exit()
    if args.version:
        version = '/'.join(('xonsh', __version__)),
        print(version)
        exit()
    shell_kwargs = {'shell_type': args.shell_type}
    if args.norc:
        shell_kwargs['ctx'] = {}
    if args.config_path:
        shell_kwargs['ctx']= {'XONSHCONFIG': args.config_path}
    setattr(sys, 'displayhook', _pprint_displayhook)
    shell = builtins.__xonsh_shell__ = Shell(**shell_kwargs)
    from xonsh import imphooks
    env = builtins.__xonsh_env__
    if args.defines is not None:
        env.update([x.split('=', 1) for x in args.defines])
    if args.login:
        env['XONSH_LOGIN'] = True
    env['XONSH_INTERACTIVE'] = False
    return args
Example #6
0
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
Example #7
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
Example #8
0
def start_services(shell_kwargs, args):
    """Starts up the essential services in the proper order.
    This returns the environment instance as a convenience.
    """
    install_import_hooks()
    # 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(xonsh_ctx=ctx,
                    debug_level=debug,
                    scriptcache=shell_kwargs.get('scriptcache', True),
                    cacheall=shell_kwargs.get('cacheall', False))
    events.on_timingprobe.fire(name='post_execer_init')
    # load rc files
    login = shell_kwargs.get('login', True)
    env = builtins.__xonsh_env__
    rc = shell_kwargs.get('rc', None)
    rc = env.get('XONSHRC') if rc is None else rc
    if args.mode != XonshMode.interactive and not args.force_interactive:
        #  Don't load xonshrc if not interactive shell
        rc = None
    events.on_pre_rc.fire()
    xonshrc_context(rcfiles=rc, execer=execer, ctx=ctx, env=env, login=login)
    events.on_post_rc.fire()
    # create shell
    builtins.__xonsh_shell__ = Shell(execer=execer, **shell_kwargs)
    ctx['__name__'] = '__main__'
    return env
Example #9
0
def setup(ctx=None, shell_type='none', env=(('RAISE_SUBPROC_ERROR', True), )):
    """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.

    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.
    """
    ctx = {} if ctx is None else ctx
    # setup xonsh ctx and execer
    builtins.__xonsh_ctx__ = ctx
    builtins.__xonsh_execer__ = Execer(xonsh_ctx=ctx)
    builtins.__xonsh_shell__ = Shell(builtins.__xonsh_execer__,
                                     ctx=ctx,
                                     shell_type='none')
    builtins.__xonsh_env__.update(env)
    install_import_hooks()
Example #10
0
def start_services(shell_kwargs, args):
    """Starts up the essential services in the proper order.
    This returns the environment instance as a convenience.
    """
    install_import_hooks()
    # 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(
        xonsh_ctx=ctx,
        debug_level=debug,
        scriptcache=shell_kwargs.get("scriptcache", True),
        cacheall=shell_kwargs.get("cacheall", False),
    )
    events.on_timingprobe.fire(name="post_execer_init")
    # load rc files
    login = shell_kwargs.get("login", True)
    env = builtins.__xonsh__.env
    rc = shell_kwargs.get("rc", None)
    rc = env.get("XONSHRC") if rc is None else rc
    if args.mode != XonshMode.interactive and not args.force_interactive:
        #  Don't load xonshrc if not interactive shell
        rc = None
    events.on_pre_rc.fire()
    xonshrc_context(rcfiles=rc, execer=execer, ctx=ctx, env=env, login=login)
    events.on_post_rc.fire()
    # create shell
    builtins.__xonsh__.shell = Shell(execer=execer, **shell_kwargs)
    ctx["__name__"] = "__main__"
    return env
Example #11
0
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)
Example #12
0
def test_shell_with_dummy_history_in_not_interactive(xonsh_builtins, xonsh_execer):
    """
    Check that shell use Dummy history in not interactive mode.
    """
    xonsh_builtins.__xonsh__.env = Env(XONSH_INTERACTIVE=False)
    xonsh_builtins.__xonsh__.history = None
    Shell(xonsh_execer, shell_type='none')
    assert isinstance(xonsh_builtins.__xonsh__.history, DummyHistory)
Example #13
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
Example #14
0
def premain(argv=None):
    """Setup for main xonsh entry point, returns parsed arguments."""
    if setproctitle is not None:
        setproctitle(' '.join(['xonsh'] + sys.argv[1:]))
    builtins.__xonsh_ctx__ = {}
    args, other = parser.parse_known_args(argv)
    if args.file is not None:
        real_argv = (argv or sys.argv)
        i = real_argv.index(args.file)
        args.args = real_argv[i + 1:]
        undo_args(args)
    if args.help:
        parser.print_help()
        exit()
    if args.version:
        version = '/'.join(('xonsh', __version__)),
        print(version)
        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.config_path is None:
        shell_kwargs['config'] = args.config_path
    if args.norc:
        shell_kwargs['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
    from xonsh import imphooks
    shell = builtins.__xonsh_shell__ = Shell(**shell_kwargs)
    env = builtins.__xonsh_env__
    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'] = False
    if ON_WINDOWS:
        setup_win_unicode_console(env.get('WIN_UNICODE_CONSOLE', True))
    return args
Example #15
0
def test_prompt_toolkit_version_checks(
    ptk_ver,
    ini_shell_type,
    exp_shell_type,
    warn_snip,
    using_vended_ptk,
    monkeypatch,
    xonsh_builtins,
):

    mocked_warn = ""

    def mock_warning(msg):
        nonlocal mocked_warn
        mocked_warn = msg
        return

    def mock_ptk_above_min_supported():
        nonlocal ptk_ver
        return ptk_ver and (ptk_ver[:3] >= minimum_required_ptk_version)

    def mock_has_prompt_toolkit():
        nonlocal ptk_ver
        return ptk_ver is not None

    monkeypatch.setattr(
        "xonsh.shell.warnings.warn", mock_warning
    )  # hardwon: patch the caller!
    monkeypatch.setattr(
        "xonsh.shell.ptk_above_min_supported", mock_ptk_above_min_supported
    )  # have to patch both callers
    monkeypatch.setattr(
        "xonsh.platform.ptk_above_min_supported", mock_ptk_above_min_supported
    )
    monkeypatch.setattr("xonsh.platform.has_prompt_toolkit", mock_has_prompt_toolkit)

    old_syspath = sys.path.copy()

    act_shell_type = Shell.choose_shell_type(ini_shell_type, {})

    if using_vended_ptk:
        # ensure PTK has been unloaded and the vended version added to sys.path
        assert len(old_syspath) < len(sys.path)
    else:
        assert len(old_syspath) == len(sys.path)

    sys.path = old_syspath

    assert act_shell_type == exp_shell_type

    if warn_snip:
        assert warn_snip in mocked_warn

    pass
Example #16
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)
Example #17
0
def main(argv=None):
    """Main entry point for xonsh cli."""
    args = parser.parse_args()
    shell_kwargs = {"shell_type": args.shell_type}
    if args.norc:
        shell_kwargs["ctx"] = {}
    setattr(sys, "displayhook", _pprint_displayhook)
    shell = Shell(**shell_kwargs)
    from xonsh import imphooks

    env = builtins.__xonsh_env__
    if args.defines is not None:
        env.update([x.split("=", 1) for x in args.defines])
    env["XONSH_INTERACTIVE"] = False
    if args.command is not None:
        # run a single command and exit
        shell.default(args.command)
    elif args.file is not None:
        # run a script contained in a file
        if os.path.isfile(args.file):
            with open(args.file) as f:
                code = f.read()
            code = code if code.endswith("\n") else code + "\n"
            env["ARGS"] = [args.file] + args.args
            code = shell.execer.compile(code, mode="exec", glbs=shell.ctx)
            shell.execer.exec(code, mode="exec", glbs=shell.ctx)
        else:
            print("xonsh: {0}: No such file or directory.".format(args.file))
    elif not sys.stdin.isatty():
        # run a script given on stdin
        code = sys.stdin.read()
        code = code if code.endswith("\n") else code + "\n"
        code = shell.execer.compile(code, mode="exec", glbs=shell.ctx)
        shell.execer.exec(code, mode="exec", glbs=shell.ctx)
    else:
        # otherwise, enter the shell
        env["XONSH_INTERACTIVE"] = True
        ignore_sigtstp()
        shell.cmdloop()
Example #18
0
def premain(argv=None):
    """Setup for main xonsh entry point, returns parsed arguments."""
    args = parser.parse_args(argv)
    shell_kwargs = {'shell_type': args.shell_type}
    if args.norc:
        shell_kwargs['ctx'] = {}
    setattr(sys, 'displayhook', _pprint_displayhook)
    shell = builtins.__xonsh_shell__ = Shell(**shell_kwargs)
    from xonsh import imphooks
    env = builtins.__xonsh_env__
    if args.defines is not None:
        env.update([x.split('=', 1) for x in args.defines])
    env['XONSH_INTERACTIVE'] = False
    return args
Example #19
0
def main(argv=None):
    """Main entry point for xonsh cli."""
    args = parser.parse_args()
    shell_kwargs = {'shell_type': args.shell_type}
    if args.norc:
        shell_kwargs['ctx'] = {}
    setattr(sys, 'displayhook', _pprint_displayhook)
    shell = builtins.__xonsh_shell__ = Shell(**shell_kwargs)
    from xonsh import imphooks
    env = builtins.__xonsh_env__
    if args.defines is not None:
        env.update([x.split('=', 1) for x in args.defines])
    env['XONSH_INTERACTIVE'] = False
    click.echo('Version: ' + gitsome_version)
    if args.command is not None:
        # run a single command and exit
        shell.default(args.command)
    elif args.file is not None:
        # run a script contained in a file
        if os.path.isfile(args.file):
            with open(args.file) as f:
                code = f.read()
            code = code if code.endswith('\n') else code + '\n'
            env['ARGS'] = [args.file] + args.args
            code = shell.execer.compile(code, mode='exec', glbs=shell.ctx)
            shell.execer.exec(code, mode='exec', glbs=shell.ctx)
        else:
            print('xonsh: {0}: No such file or directory.'.format(args.file))
    elif not sys.stdin.isatty():
        # run a script given on stdin
        code = sys.stdin.read()
        code = code if code.endswith('\n') else code + '\n'
        code = shell.execer.compile(code, mode='exec', glbs=shell.ctx)
        shell.execer.exec(code, mode='exec', glbs=shell.ctx)
    else:
        # otherwise, enter the shell
        env['XONSH_INTERACTIVE'] = True
        ignore_sigtstp()
        shell.cmdloop()
    del builtins.__xonsh_shell__
Example #20
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.

    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
    builtins.__xonsh_ctx__ = ctx
    builtins.__xonsh_execer__ = Execer(xonsh_ctx=ctx)
    builtins.__xonsh_shell__ = Shell(builtins.__xonsh_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)
Example #21
0
def test_prompt_toolkit_version_checks(ptk_ver, ini_shell_type, exp_shell_type,
                                       warn_snip, monkeypatch, xonsh_builtins):

    mocked_warn = ""

    def mock_warning(msg):
        nonlocal mocked_warn
        mocked_warn = msg
        return

    def mock_ptk_above_min_supported():
        nonlocal ptk_ver
        return ptk_ver and (ptk_ver[:2] >= minimum_required_ptk_version)

    def mock_has_prompt_toolkit():
        nonlocal ptk_ver
        return ptk_ver is not None

    monkeypatch.setattr("xonsh.shell.warnings.warn",
                        mock_warning)  # hardwon: patch the caller!
    monkeypatch.setattr(
        "xonsh.shell.ptk_above_min_supported",
        mock_ptk_above_min_supported)  # have to patch both callers
    monkeypatch.setattr("xonsh.platform.ptk_above_min_supported",
                        mock_ptk_above_min_supported)
    monkeypatch.setattr("xonsh.shell.has_prompt_toolkit",
                        mock_has_prompt_toolkit)
    monkeypatch.setattr("xonsh.platform.has_prompt_toolkit",
                        mock_has_prompt_toolkit)

    act_shell_type = Shell.choose_shell_type(ini_shell_type, {})

    assert act_shell_type == exp_shell_type

    if warn_snip:
        assert warn_snip in mocked_warn

    pass
Example #22
0
def test_shell_with_sqlite_history(xonsh_builtins, 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()

    xonsh_builtins.__xonsh__.env = Env(
        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 xonsh_builtins.__xonsh__.history.all_items()]) == 2
Example #23
0
def xonsh(request):
    sess = builtins.__xonsh__
    if sess.shell is None:
        from xonsh.shell import Shell
        sess.shell = Shell(sess.execer, ctx=sess.ctx, shell_type="none")
    return sess
Example #24
0
import builtins

# setup xonsh ctx and execer
builtins.__xonsh_ctx__ = {}
from xonsh.execer import Execer
builtins.__xonsh_execer__ = Execer(xonsh_ctx=builtins.__xonsh_ctx__)
from xonsh.shell import Shell
builtins.__xonsh_shell__ = Shell(builtins.__xonsh_execer__,
                                 ctx=builtins.__xonsh_ctx__,
                                 shell_type='none')

builtins.__xonsh_env__['RAISE_SUBPROC_ERROR'] = True

# setup import hooks
import xonsh.imphooks
xonsh.imphooks.install_import_hooks()

__version__ = '0.2.5'

del xonsh, builtins, Execer, Shell
Example #25
0
"""Tests the xonsh replay functionality."""
from __future__ import unicode_literals, print_function
import os
import builtins
from contextlib import contextmanager

import nose
from nose.tools import assert_equal, assert_true

from xonsh.tools import swap
from xonsh.shell import Shell
from xonsh.replay import Replayer

from tools import ON_MAC, skip_if

SHELL = Shell()
HISTDIR = os.path.join(os.path.dirname(__file__), 'histories')

def run_replay(re_file):
    with swap(builtins, '__xonsh_shell__', SHELL):
        r = Replayer(re_file)
        hist = r.replay()
    return hist


def cleanup_replay(hist):
    fname = hist.filename
    del hist
    if os.path.isfile(fname):
        os.remove(fname)
Example #26
0
# -*- coding: utf-8 -*-
"""Tests the xonsh replay functionality."""
from __future__ import unicode_literals, print_function
import os
import builtins
from contextlib import contextmanager

import pytest

from xonsh.tools import swap
from xonsh.shell import Shell
from xonsh.replay import Replayer

from tools import skip_if_on_darwin

SHELL = Shell({'PATH': []})
HISTDIR = os.path.join(os.path.dirname(__file__), 'histories')


def run_replay(re_file):
    with swap(builtins, '__xonsh_shell__', SHELL):
        with swap(builtins, '__xonsh_exit__', False):
            r = Replayer(re_file)
            hist = r.replay()
    return hist


def cleanup_replay(hist):
    fname = hist.filename
    del hist
    if os.path.isfile(fname):
Example #27
0
def premain(argv=None):
    """Setup for main xonsh entry point, returns parsed arguments."""
    if setproctitle is not None:
        setproctitle(' '.join(['xonsh'] + sys.argv[1:]))
    builtins.__xonsh_ctx__ = {}
    args, other = parser.parse_known_args(argv)
    if args.file is not None:
        arguments = (argv or sys.argv)
        file_index = arguments.index(args.file)
        # A script-file was passed and is to be executed. The argument parser
        # might have parsed switches intended for the script, so reset the
        # parsed switches to their default values
        old_args = args
        args = parser.parse_known_args('')[0]
        args.file = old_args.file
        # Save the arguments that are intended for the script-file. Switches
        # and positional arguments passed before the path to the script-file are
        # ignored.
        args.args = arguments[file_index+1:]
    if args.help:
        parser.print_help()
        exit()
    if args.version:
        version = '/'.join(('xonsh', __version__)),
        print(version)
        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.config_path is None:
        shell_kwargs['config'] = args.config_path
    if args.norc:
        shell_kwargs['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
    from xonsh import imphooks
    shell = builtins.__xonsh_shell__ = Shell(**shell_kwargs)
    env = builtins.__xonsh_env__
    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'] = False
    if ON_WINDOWS:
        setup_win_unicode_console(env.get('WIN_UNICODE_CONSOLE', True))
    return args
Example #28
0
def ctx():
    """Create a global Shell instance to use in all the test."""
    builtins.__xonsh_shell__ = Shell({'PATH': []})
    yield
    del builtins.__xonsh_shell__