Пример #1
0
def test_ensure_int_or_slice():
    cases = [
        (42, 42),
        (None, slice(None, None, None)),
        ('42', 42),
        ('-42', -42),
        ('1:2:3', slice(1, 2, 3)),
        ('1::3', slice(1, None, 3)),
        ('1:', slice(1, None, None)),
        ('[1:2:3]', slice(1, 2, 3)),
        ('(1:2:3)', slice(1, 2, 3)),
        ]
    for inp, exp in cases:
        obs = ensure_int_or_slice(inp)
        yield assert_equal, exp, obs
Пример #2
0
def _hist_main(hist, args):
    """This implements the history CLI."""
    if not args or args[0] in ['-r'] or ensure_int_or_slice(args[0]):
        args.insert(0, 'show')
    elif args[0] not in list(_HIST_MAIN_ACTIONS) + ['-h', '--help']:
        print("{} is not a valid input.".format(args[0]), file=sys.stderr)
        return
    if (args[0] in ['show', 'xonsh', 'zsh', 'bash', 'session', 'all']
            and len(args) > 1 and args[-1].startswith('-')
            and args[-1][1].isdigit()):
        args.insert(-1, '--')  # ensure parsing stops before a negative int
    ns = _hist_create_parser().parse_args(args)
    if ns.action is None:  # apply default action
        ns = _hist_create_parser().parse_args(['show'] + args)
    _HIST_MAIN_ACTIONS[ns.action](ns, hist)
Пример #3
0
def test_ensure_int_or_slice():
    cases = [
        (42, 42),
        (None, slice(None, None, None)),
        ('42', 42),
        ('-42', -42),
        ('1:2:3', slice(1, 2, 3)),
        ('1::3', slice(1, None, 3)),
        ('1:', slice(1, None, None)),
        ('[1:2:3]', slice(1, 2, 3)),
        ('(1:2:3)', slice(1, 2, 3)),
    ]
    for inp, exp in cases:
        obs = ensure_int_or_slice(inp)
        yield assert_equal, exp, obs
Пример #4
0
def _hist_main(hist, args):
    """This implements the history CLI."""
    if not args or args[0] in ['-r'] or ensure_int_or_slice(args[0]):
        args.insert(0, 'show')
    elif args[0] not in list(_HIST_MAIN_ACTIONS) + ['-h', '--help']:
        print("{} is not a valid input.".format(args[0]),
              file=sys.stderr)
        return
    if (args[0] in ['show', 'xonsh', 'zsh', 'bash', 'session', 'all'] and
        len(args) > 1 and args[-1].startswith('-') and
            args[-1][1].isdigit()):
        args.insert(-1, '--')  # ensure parsing stops before a negative int
    ns = _hist_create_parser().parse_args(args)
    if ns.action is None:  # apply default action
        ns = _hist_create_parser().parse_args(['show'] + args)
    _HIST_MAIN_ACTIONS[ns.action](ns, hist)
Пример #5
0
def test_ensure_int_or_slice():
    cases = [
        (42, 42),
        (None, slice(None, None, None)),
        ('42', 42),
        ('-42', -42),
        ('1:2:3', slice(1, 2, 3)),
        ('1::3', slice(1, None, 3)),
        (':', slice(None, None, None)),
        ('1:', slice(1, None, None)),
        ('[1:2:3]', slice(1, 2, 3)),
        ('(1:2:3)', slice(1, 2, 3)),
        ('r', False),
        ('r:11', False),
        ]
    for inp, exp in cases:
        obs = ensure_int_or_slice(inp)
        assert exp == obs
Пример #6
0
def _show(ns, hist):
    idx = ensure_int_or_slice(ns.n)
    if len(hist) == 0:
        return
    inps = hist.inps[idx]
    if isinstance(idx, int):
        inps = [inps]
        indices = [idx if idx >= 0 else len(hist) + idx]
    else:
        indices = list(range(*idx.indices(len(hist))))
    ndigits = len(str(indices[-1]))
    indent = ' ' * (ndigits + 3)
    if ns.reverse:
        indices = reversed(indices)
        inps = reversed(inps)
    for i, inp in zip(indices, inps):
        lines = inp.splitlines()
        lines[0] = ' {0:>{1}}  {2}'.format(i, ndigits, lines[0])
        lines[1:] = [indent + x for x in lines[1:]]
        print('\n'.join(lines))
Пример #7
0
def _show(ns, hist):
    idx = ensure_int_or_slice(ns.n)
    if len(hist) == 0:
        return
    inps = hist.inps[idx]
    if isinstance(idx, int):
        inps = [inps]
        indices = [idx if idx >= 0 else len(hist) + idx]
    else:
        indices = list(range(*idx.indices(len(hist))))
    ndigits = len(str(indices[-1]))
    indent = " " * (ndigits + 3)
    if ns.reverse:
        indices = reversed(indices)
        inps = reversed(inps)
    for i, inp in zip(indices, inps):
        lines = inp.splitlines()
        lines[0] = " {0:>{1}}  {2}".format(i, ndigits, lines[0])
        lines[1:] = [indent + x for x in lines[1:]]
        print("\n".join(lines))
Пример #8
0
def _show(ns, hist):
    """Show the requested portion of the shell history."""
    idx = ensure_int_or_slice(ns.n)
    if len(hist) == 0:
        return
    inps = hist.inps[idx]
    if isinstance(idx, int):
        inps = [inps]
        indices = [idx if idx >= 0 else len(hist) + idx]
    else:
        indices = list(range(*idx.indices(len(hist))))
    ndigits = len(str(indices[-1]))
    indent = ' '*(ndigits + 3)
    if ns.reverse:
        indices = reversed(indices)
        inps = reversed(inps)
    for i, inp in zip(indices, inps):
        lines = inp.splitlines()
        lines[0] = ' {0:>{1}}  {2}'.format(i, ndigits, lines[0])
        lines[1:] = [indent + x for x in lines[1:]]
        print('\n'.join(lines))
Пример #9
0
def _show(ns=None, hist=None, start_index=None, end_index=None,
          start_time=None, end_time=None, location=None):
    """
    Show the requested portion of shell history.
    Accepts multiple history sources (xonsh, bash, zsh)

    May be invoked as an alias with `history all/bash/zsh` which will
    provide history as stdout or with `__xonsh_history__.show()`
    which will return the history as a list with each item
    in the tuple form (name, start_time, index).

    If invoked via __xonsh_history__.show() then the ns parameter
    can be supplied as a str with the follow options:
        `session` - returns xonsh history from current session
        `all`     - returns xonsh history from all sessions
        `zsh`     - returns all zsh history
        `bash`    - returns all bash history
    """
    # Check if ns is a string, meaning it was invoked from
    # __xonsh_history__
    alias = True
    valid_formats = {'session': functools.partial(_curr_session_parser, hist),
                     'show': functools.partial(_curr_session_parser, hist),
                     'all': _all_xonsh_parser,
                     'xonsh': _all_xonsh_parser,
                     'zsh': functools.partial(_zsh_hist_parser, location),
                     'bash': functools.partial(_bash_hist_parser, location)}
    if isinstance(ns, str) and ns in valid_formats.keys():
        ns = _hist_create_parser().parse_args([ns])
        alias = False
    if not ns:
        ns = _hist_create_parser().parse_args(['all'])
        alias = False
    try:
        commands = valid_formats[ns.action]()
    except KeyError:
        print("{} is not a valid history format".format(ns.action))
        return None
    if not commands:
        return None
    if start_time:
        if isinstance(start_time, datetime.datetime):
            start_time = start_time.timestamp()
        if isinstance(start_time, float):
            commands = [c for c in commands if c[1] >= start_time]
        else:
            print("Invalid start time, must be float or datetime.")
    if end_time:
        if isinstance(end_time, datetime.datetime):
            end_time = end_time.timestamp()
        if isinstance(end_time, float):
            commands = [c for c in commands if c[1] <= end_time]
        else:
            print("Invalid end time, must be float or datetime.")
    idx = None
    if ns:
        idx = ensure_int_or_slice(ns.n)
        if idx is False:
            print("{} is not a valid input.".format(ns.n),
                  file=sys.stderr)
            return
        elif isinstance(idx, int):
            try:
                commands = [commands[idx]]
            except IndexError:
                err = "Index likely not in range. Only {} commands."
                print(err.format(len(commands)))
                return
    else:
        idx = slice(start_index, end_index)

    if (isinstance(idx, slice) and
            start_time is None and end_time is None):
        commands = commands[idx]

    if ns and ns.reverse:
        commands = list(reversed(commands))

    if commands:
        digits = len(str(max([i for c, t, i in commands])))
        if alias:
            for c, t, i in commands:
                for line_ind, line in enumerate(c.split('\n')):
                    if line_ind == 0:
                        print('{:>{width}}: {}'.format(i, line,
                                                       width=digits + 1))
                    else:
                        print(' {:>>{width}} {}'.format('', line,
                                                        width=digits + 1))
        else:
            return commands
Пример #10
0
def _show(ns=None,
          hist=None,
          start_index=None,
          end_index=None,
          start_time=None,
          end_time=None,
          location=None):
    """
    Show the requested portion of shell history.
    Accepts multiple history sources (xonsh, bash, zsh)

    May be invoked as an alias with `history all/bash/zsh` which will
    provide history as stdout or with `__xonsh_history__.show()`
    which will return the history as a list with each item
    in the tuple form (name, start_time, index).

    If invoked via __xonsh_history__.show() then the ns parameter
    can be supplied as a str with the follow options:
        `session` - returns xonsh history from current session
        `all`     - returns xonsh history from all sessions
        `zsh`     - returns all zsh history
        `bash`    - returns all bash history
    """
    # Check if ns is a string, meaning it was invoked from
    # __xonsh_history__
    alias = True
    valid_formats = {
        'session': functools.partial(_curr_session_parser, hist),
        'show': functools.partial(_curr_session_parser, hist),
        'all': _all_xonsh_parser,
        'xonsh': _all_xonsh_parser,
        'zsh': functools.partial(_zsh_hist_parser, location),
        'bash': functools.partial(_bash_hist_parser, location)
    }
    if isinstance(ns, str) and ns in valid_formats.keys():
        ns = _hist_create_parser().parse_args([ns])
        alias = False
    if not ns:
        ns = _hist_create_parser().parse_args(['all'])
        alias = False
    try:
        commands = valid_formats[ns.action]()
    except KeyError:
        print("{} is not a valid history format".format(ns.action))
        return None
    if not commands:
        return None
    if start_time:
        if isinstance(start_time, datetime.datetime):
            start_time = start_time.timestamp()
        if isinstance(start_time, float):
            commands = [c for c in commands if c[1] >= start_time]
        else:
            print("Invalid start time, must be float or datetime.")
    if end_time:
        if isinstance(end_time, datetime.datetime):
            end_time = end_time.timestamp()
        if isinstance(end_time, float):
            commands = [c for c in commands if c[1] <= end_time]
        else:
            print("Invalid end time, must be float or datetime.")
    idx = None
    if ns:
        idx = ensure_int_or_slice(ns.n)
        if idx is False:
            print("{} is not a valid input.".format(ns.n), file=sys.stderr)
            return
        elif isinstance(idx, int):
            try:
                commands = [commands[idx]]
            except IndexError:
                err = "Index likely not in range. Only {} commands."
                print(err.format(len(commands)))
                return
    else:
        idx = slice(start_index, end_index)

    if (isinstance(idx, slice) and start_time is None and end_time is None):
        commands = commands[idx]

    if ns and ns.reverse:
        commands = list(reversed(commands))

    if commands:
        digits = len(str(max([i for c, t, i in commands])))
        if alias:
            for c, t, i in commands:
                for line_ind, line in enumerate(c.split('\n')):
                    if line_ind == 0:
                        print('{:>{width}}: {}'.format(i,
                                                       line,
                                                       width=digits + 1))
                    else:
                        print(' {:>>{width}} {}'.format('',
                                                        line,
                                                        width=digits + 1))
        else:
            return commands
Пример #11
0
def test_ensure_int_or_slice(inp, exp):
    obs = ensure_int_or_slice(inp)
    assert exp == obs
Пример #12
0
def test_ensure_int_or_slice(inp, exp):
    obs = ensure_int_or_slice(inp)
    assert exp == obs