Exemple #1
0
def ensure_shell(shell):
    """Ensures that a mapping follows the shell specification."""
    if not isinstance(shell, MutableMapping):
        shell = dict(shell)
    shell_keys = set(shell.keys())
    if not (shell_keys <= VALID_SHELL_PARAMS):
        msg = 'unknown shell keys: {0}'
        raise KeyError(msg.format(shell_keys - VALID_SHELL_PARAMS))
    shell['shell'] = ensure_string(shell['shell'])
    if 'interactive' in shell_keys:
        shell['interactive'] = to_bool(shell['interactive'])
    if 'login' in shell_keys:
        shell['login'] = to_bool(shell['login'])
    if 'envcmd' in shell_keys:
        shell['envcmd'] = eunsure_string(shell['envcmd'])
    if 'aliascmd' in shell_keys:
        shell['aliascmd'] = eunsure_string(shell['aliascmd'])
    if 'extra_args' in shell_keys and not isinstance(shell['extra_args'], tuple):
        shell['extra_args'] = tuple(map(ensure_string, shell['extra_args']))
    if 'currenv' in shell_keys and not isinstance(shell['currenv'], tuple):
        ce = shell['currenv']
        if isinstance(ce, Mapping):
            ce = tuple([(ensure_string(k), v) for k, v in ce.items()])
        elif isinstance(ce, Sequence):
            ce = tuple([(ensure_string(k), v) for k, v in ce])
        else:
            raise RuntimeError('unrecognized type for currenv')
        shell['currenv'] = ce
    if 'safe' in shell_keys:
        shell['safe'] = to_bool(shell['safe'])
    return shell
Exemple #2
0
def ensure_shell(shell):
    """Ensures that a mapping follows the shell specification."""
    if not isinstance(shell, MutableMapping):
        shell = dict(shell)
    shell_keys = set(shell.keys())
    if not (shell_keys <= VALID_SHELL_PARAMS):
        msg = 'unknown shell keys: {0}'
        raise KeyError(msg.format(shell_keys - VALID_SHELL_PARAMS))
    shell['shell'] = ensure_string(shell['shell'])
    if 'interactive' in shell_keys:
        shell['interactive'] = to_bool(shell['interactive'])
    if 'login' in shell_keys:
        shell['login'] = to_bool(shell['login'])
    if 'envcmd' in shell_keys:
        shell['envcmd'] = eunsure_string(shell['envcmd'])
    if 'aliascmd' in shell_keys:
        shell['aliascmd'] = eunsure_string(shell['aliascmd'])
    if 'extra_args' in shell_keys and not isinstance(shell['extra_args'],
                                                     tuple):
        shell['extra_args'] = tuple(map(ensure_string, shell['extra_args']))
    if 'currenv' in shell_keys and not isinstance(shell['currenv'], tuple):
        ce = shell['currenv']
        if isinstance(ce, Mapping):
            ce = tuple([(ensure_string(k), v) for k, v in ce.items()])
        elif isinstance(ce, Sequence):
            ce = tuple([(ensure_string(k), v) for k, v in ce])
        else:
            raise RuntimeError('unrecognized type for currenv')
        shell['currenv'] = ce
    if 'safe' in shell_keys:
        shell['safe'] = to_bool(shell['safe'])
    return shell
Exemple #3
0
def ensure_shell(shell):
    """Ensures that a mapping follows the shell specification."""
    if not isinstance(shell, cabc.MutableMapping):
        shell = dict(shell)
    shell_keys = set(shell.keys())
    if not (shell_keys <= VALID_SHELL_PARAMS):
        msg = "unknown shell keys: {0}"
        raise KeyError(msg.format(shell_keys - VALID_SHELL_PARAMS))
    shell["shell"] = ensure_string(shell["shell"]).lower()
    if "interactive" in shell_keys:
        shell["interactive"] = to_bool(shell["interactive"])
    if "login" in shell_keys:
        shell["login"] = to_bool(shell["login"])
    if "envcmd" in shell_keys:
        shell["envcmd"] = (
            None if shell["envcmd"] is None else ensure_string(shell["envcmd"])
        )
    if "aliascmd" in shell_keys:
        shell["aliascmd"] = (
            None if shell["aliascmd"] is None else ensure_string(shell["aliascmd"])
        )
    if "extra_args" in shell_keys and not isinstance(shell["extra_args"], tuple):
        shell["extra_args"] = tuple(map(ensure_string, shell["extra_args"]))
    if "currenv" in shell_keys and not isinstance(shell["currenv"], tuple):
        ce = shell["currenv"]
        if isinstance(ce, cabc.Mapping):
            ce = tuple([(ensure_string(k), v) for k, v in ce.items()])
        elif isinstance(ce, cabc.Sequence):
            ce = tuple([(ensure_string(k), v) for k, v in ce])
        else:
            raise RuntimeError("unrecognized type for currenv")
        shell["currenv"] = ce
    if "safe" in shell_keys:
        shell["safe"] = to_bool(shell["safe"])
    if "prevcmd" in shell_keys:
        shell["prevcmd"] = ensure_string(shell["prevcmd"])
    if "postcmd" in shell_keys:
        shell["postcmd"] = ensure_string(shell["postcmd"])
    if "funcscmd" in shell_keys:
        shell["funcscmd"] = (
            None if shell["funcscmd"] is None else ensure_string(shell["funcscmd"])
        )
    if "sourcer" in shell_keys:
        shell["sourcer"] = (
            None if shell["sourcer"] is None else ensure_string(shell["sourcer"])
        )
    if "seterrprevcmd" in shell_keys:
        shell["seterrprevcmd"] = (
            None
            if shell["seterrprevcmd"] is None
            else ensure_string(shell["seterrprevcmd"])
        )
    if "seterrpostcmd" in shell_keys:
        shell["seterrpostcmd"] = (
            None
            if shell["seterrpostcmd"] is None
            else ensure_string(shell["seterrpostcmd"])
        )
    return shell
Exemple #4
0
def ensure_shell(shell):
    """Ensures that a mapping follows the shell specification."""
    if not isinstance(shell, cabc.MutableMapping):
        shell = dict(shell)
    shell_keys = set(shell.keys())
    if not (shell_keys <= VALID_SHELL_PARAMS):
        msg = "unknown shell keys: {0}"
        raise KeyError(msg.format(shell_keys - VALID_SHELL_PARAMS))
    shell["shell"] = ensure_string(shell["shell"]).lower()
    if "interactive" in shell_keys:
        shell["interactive"] = to_bool(shell["interactive"])
    if "login" in shell_keys:
        shell["login"] = to_bool(shell["login"])
    if "envcmd" in shell_keys:
        shell["envcmd"] = (
            None if shell["envcmd"] is None else ensure_string(shell["envcmd"])
        )
    if "aliascmd" in shell_keys:
        shell["aliascmd"] = (
            None if shell["aliascmd"] is None else ensure_string(shell["aliascmd"])
        )
    if "extra_args" in shell_keys and not isinstance(shell["extra_args"], tuple):
        shell["extra_args"] = tuple(map(ensure_string, shell["extra_args"]))
    if "currenv" in shell_keys and not isinstance(shell["currenv"], tuple):
        ce = shell["currenv"]
        if isinstance(ce, cabc.Mapping):
            ce = tuple([(ensure_string(k), v) for k, v in ce.items()])
        elif isinstance(ce, cabc.Sequence):
            ce = tuple([(ensure_string(k), v) for k, v in ce])
        else:
            raise RuntimeError("unrecognized type for currenv")
        shell["currenv"] = ce
    if "safe" in shell_keys:
        shell["safe"] = to_bool(shell["safe"])
    if "prevcmd" in shell_keys:
        shell["prevcmd"] = ensure_string(shell["prevcmd"])
    if "postcmd" in shell_keys:
        shell["postcmd"] = ensure_string(shell["postcmd"])
    if "funcscmd" in shell_keys:
        shell["funcscmd"] = (
            None if shell["funcscmd"] is None else ensure_string(shell["funcscmd"])
        )
    if "sourcer" in shell_keys:
        shell["sourcer"] = (
            None if shell["sourcer"] is None else ensure_string(shell["sourcer"])
        )
    if "seterrprevcmd" in shell_keys:
        shell["seterrprevcmd"] = (
            None
            if shell["seterrprevcmd"] is None
            else ensure_string(shell["seterrprevcmd"])
        )
    if "seterrpostcmd" in shell_keys:
        shell["seterrpostcmd"] = (
            None
            if shell["seterrpostcmd"] is None
            else ensure_string(shell["seterrpostcmd"])
        )
    return shell
Exemple #5
0
 def _querycompletions(self, completions, loc):
     """Returns whether or not we should show completions"""
     if os.path.commonprefix([c[loc:] for c in completions]):
         return True
     elif len(completions) <= builtins.__xonsh_env__.get('COMPLETION_QUERY_LIMIT'):
         return True
     msg = '\nDisplay all {} possibilities? '.format(len(completions))
     msg += '({GREEN}y{NO_COLOR} or {RED}n{NO_COLOR})'
     self.print_color(msg, end='', flush=True, file=sys.stderr)
     yn = 'x'
     while yn not in 'yn':
         yn = sys.stdin.read(1)
     show_completions = to_bool(yn)
     print()
     if not show_completions:
         rl_on_new_line()
         return False
     w, h = shutil.get_terminal_size()
     lines = columnize(completions, width=w)
     more_msg = self.format_color('{YELLOW}==={NO_COLOR} more or '
                                  '{PURPLE}({NO_COLOR}q{PURPLE}){NO_COLOR}uit '
                                  '{YELLOW}==={NO_COLOR}')
     while len(lines) > h - 1:
         print(''.join(lines[:h-1]), end='', flush=True, file=sys.stderr)
         lines = lines[h-1:]
         print(more_msg, end='', flush=True, file=sys.stderr)
         q = sys.stdin.read(1).lower()
         print(flush=True, file=sys.stderr)
         if q == 'q':
             rl_on_new_line()
             return False
     print(''.join(lines), end='', flush=True, file=sys.stderr)
     rl_on_new_line()
     return False
Exemple #6
0
 def _querycompletions(self, completions, loc):
     """Returns whether or not we should show completions"""
     if os.path.commonprefix([c[loc:] for c in completions]):
         return True
     elif len(completions) <= builtins.__xonsh_env__.get('COMPLETION_QUERY_LIMIT'):
         return True
     msg = '\nDisplay all {} possibilities? '.format(len(completions))
     msg += '({GREEN}y{NO_COLOR} or {RED}n{NO_COLOR})'
     self.print_color(msg, end='', flush=True, file=sys.stderr)
     yn = 'x'
     while yn not in 'yn':
         yn = sys.stdin.read(1)
     show_completions = to_bool(yn)
     print()
     if not show_completions:
         rl_on_new_line()
         return False
     w, h = shutil.get_terminal_size()
     lines = columnize(completions, width=w)
     more_msg = self.format_color('{YELLOW}==={NO_COLOR} more or '
                                  '{PURPLE}({NO_COLOR}q{PURPLE}){NO_COLOR}uit '
                                  '{YELLOW}==={NO_COLOR}')
     while len(lines) > h - 1:
         print(''.join(lines[:h-1]), end='', flush=True, file=sys.stderr)
         lines = lines[h-1:]
         print(more_msg, end='', flush=True, file=sys.stderr)
         q = sys.stdin.read(1).lower()
         print(flush=True, file=sys.stderr)
         if q == 'q':
             rl_on_new_line()
             return False
     print(''.join(lines), end='', flush=True, file=sys.stderr)
     rl_on_new_line()
     return False
Exemple #7
0
def make_xontrib(xon_item: tp.Tuple[str, Xontrib]):
    """Makes a message and StoreNonEmpty node for a xontrib."""
    name, xontrib = xon_item
    name = name or "<unknown-xontrib-name>"
    msg = "\n{BOLD_CYAN}" + name + "{RESET}\n"
    if xontrib.url:
        msg += "{RED}url:{RESET} " + xontrib.url + "\n"
    if xontrib.package:
        pkg = xontrib.package
        msg += "{RED}package:{RESET} " + pkg.name + "\n"
        if pkg.url:
            if xontrib.url and pkg.url != xontrib.url:
                msg += "{RED}package-url:{RESET} " + pkg.url + "\n"
        if pkg.license:
            msg += "{RED}license:{RESET} " + pkg.license + "\n"
    msg += "{PURPLE}installed?{RESET} "
    msg += ("no" if find_xontrib(name) is None else "yes") + "\n"
    msg += _wrap_paragraphs(xontrib.description, width=69)
    if msg.endswith("\n"):
        msg = msg[:-1]
    mnode = wiz.Message(message=msg)
    convert = lambda x: name if to_bool(x) else wiz.Unstorable
    pnode = wiz.StoreNonEmpty(XONTRIB_PROMPT,
                              converter=convert,
                              path=_xontrib_path)
    return mnode, pnode
Exemple #8
0
def make_xontrib(xontrib, package):
    """Makes a message and StoreNonEmpty node for a xontrib."""
    name = xontrib.get('name', '<unknown-xontrib-name>')
    msg = '\n{BOLD_CYAN}' + name + '{NO_COLOR}\n'
    if 'url' in xontrib:
        msg += '{RED}url:{NO_COLOR} ' + xontrib['url'] + '\n'
    if 'package' in xontrib:
        msg += '{RED}package:{NO_COLOR} ' + xontrib['package'] + '\n'
    if 'url' in package:
        if 'url' in xontrib and package['url'] != xontrib['url']:
            msg += '{RED}package-url:{NO_COLOR} ' + package['url'] + '\n'
    if 'license' in package:
        msg += '{RED}license:{NO_COLOR} ' + package['license'] + '\n'
    msg += '{PURPLE}installed?{NO_COLOR} '
    msg += ('no' if find_xontrib(name) is None else 'yes') + '\n'
    desc = xontrib.get('description', '')
    if not isinstance(desc, str):
        desc = ''.join(desc)
    msg += _wrap_paragraphs(desc, width=69)
    if msg.endswith('\n'):
        msg = msg[:-1]
    mnode = wiz.Message(message=msg)
    convert = lambda x: name if to_bool(x) else wiz.Unstorable
    pnode = wiz.StoreNonEmpty(XONTRIB_PROMPT, converter=convert,
                              path=_xontrib_path)
    return mnode, pnode
Exemple #9
0
def make_xontrib(xontrib, package):
    """Makes a message and StoreNonEmpty node for a xontrib."""
    name = xontrib.get('name', '<unknown-xontrib-name>')
    msg = '\n{BOLD_CYAN}' + name + '{NO_COLOR}\n'
    if 'url' in xontrib:
        msg += '{RED}url:{NO_COLOR} ' + xontrib['url'] + '\n'
    if 'package' in xontrib:
        msg += '{RED}package:{NO_COLOR} ' + xontrib['package'] + '\n'
    if 'url' in package:
        if 'url' in xontrib and package['url'] != xontrib['url']:
            msg += '{RED}package-url:{NO_COLOR} ' + package['url'] + '\n'
    if 'license' in package:
        msg += '{RED}license:{NO_COLOR} ' + package['license'] + '\n'
    msg += '{PURPLE}installed?{NO_COLOR} '
    msg += ('no' if find_xontrib(name) is None else 'yes') + '\n'
    desc = xontrib.get('description', '')
    if not isinstance(desc, str):
        desc = ''.join(desc)
    msg += _wrap_paragraphs(desc, width=69)
    if msg.endswith('\n'):
        msg = msg[:-1]
    mnode = wiz.Message(message=msg)
    convert = lambda x: name if to_bool(x) else wiz.Unstorable
    pnode = wiz.StoreNonEmpty(XONTRIB_PROMPT, converter=convert,
                              path=_xontrib_path)
    return mnode, pnode
Exemple #10
0
def make_xontrib(xontrib, package):
    """Makes a message and StoreNonEmpty node for a xontrib."""
    name = xontrib.get("name", "<unknown-xontrib-name>")
    msg = "\n{BOLD_CYAN}" + name + "{RESET}\n"
    if "url" in xontrib:
        msg += "{RED}url:{RESET} " + xontrib["url"] + "\n"
    if "package" in xontrib:
        msg += "{RED}package:{RESET} " + xontrib["package"] + "\n"
    if "url" in package:
        if "url" in xontrib and package["url"] != xontrib["url"]:
            msg += "{RED}package-url:{RESET} " + package["url"] + "\n"
    if "license" in package:
        msg += "{RED}license:{RESET} " + package["license"] + "\n"
    msg += "{PURPLE}installed?{RESET} "
    msg += ("no" if find_xontrib(name) is None else "yes") + "\n"
    desc = xontrib.get("description", "")
    if not isinstance(desc, str):
        desc = "".join(desc)
    msg += _wrap_paragraphs(desc, width=69)
    if msg.endswith("\n"):
        msg = msg[:-1]
    mnode = wiz.Message(message=msg)
    convert = lambda x: name if to_bool(x) else wiz.Unstorable
    pnode = wiz.StoreNonEmpty(XONTRIB_PROMPT,
                              converter=convert,
                              path=_xontrib_path)
    return mnode, pnode
Exemple #11
0
def make_xontrib(xontrib, package):
    """Makes a message and StoreNonEmpty node for a xontrib."""
    name = xontrib.get("name", "<unknown-xontrib-name>")
    msg = "\n{BOLD_CYAN}" + name + "{NO_COLOR}\n"
    if "url" in xontrib:
        msg += "{RED}url:{NO_COLOR} " + xontrib["url"] + "\n"
    if "package" in xontrib:
        msg += "{RED}package:{NO_COLOR} " + xontrib["package"] + "\n"
    if "url" in package:
        if "url" in xontrib and package["url"] != xontrib["url"]:
            msg += "{RED}package-url:{NO_COLOR} " + package["url"] + "\n"
    if "license" in package:
        msg += "{RED}license:{NO_COLOR} " + package["license"] + "\n"
    msg += "{PURPLE}installed?{NO_COLOR} "
    msg += ("no" if find_xontrib(name) is None else "yes") + "\n"
    desc = xontrib.get("description", "")
    if not isinstance(desc, str):
        desc = "".join(desc)
    msg += _wrap_paragraphs(desc, width=69)
    if msg.endswith("\n"):
        msg = msg[:-1]
    mnode = wiz.Message(message=msg)
    convert = lambda x: name if to_bool(x) else wiz.Unstorable
    pnode = wiz.StoreNonEmpty(XONTRIB_PROMPT, converter=convert, path=_xontrib_path)
    return mnode, pnode
Exemple #12
0
def test_to_bool():
    cases = [
        (True, True),
        (False, False),
        (None, False),
        ('', False),
        ('0', False),
        ('False', False),
        ('NONE', False),
        ('TRUE', True),
        ('1', True),
        (0, False),
        (1, True),
        ]
    for inp, exp in cases:
        obs = to_bool(inp)
        yield assert_equal, exp, obs
Exemple #13
0
def test_to_bool():
    cases = [
        (True, True),
        (False, False),
        (None, False),
        ('', False),
        ('0', False),
        ('False', False),
        ('NONE', False),
        ('TRUE', True),
        ('1', True),
        (0, False),
        (1, True),
    ]
    for inp, exp in cases:
        obs = to_bool(inp)
        yield assert_equal, exp, obs
Exemple #14
0
 def _querycompletions(self, completions, loc):
     """Returns whether or not we should show completions. 0 means that prefixes
     should not be shown, 1 means that there is a common prefix among all completions
     and they should be shown, while 2 means that there is no common prefix but
     we are under the query limit and they should be shown.
     """
     if os.path.commonprefix([c[loc:] for c in completions]):
         return 1
     elif len(completions) <= builtins.__xonsh__.env.get(
             "COMPLETION_QUERY_LIMIT"):
         return 2
     msg = "\nDisplay all {} possibilities? ".format(len(completions))
     msg += "({GREEN}y{NO_COLOR} or {RED}n{NO_COLOR})"
     self.print_color(msg, end="", flush=True, file=sys.stderr)
     yn = "x"
     while yn not in "yn":
         yn = sys.stdin.read(1)
     show_completions = to_bool(yn)
     print()
     if not show_completions:
         rl_on_new_line()
         return 0
     w, h = shutil.get_terminal_size()
     lines = columnize(completions, width=w)
     more_msg = self.format_color(
         "{YELLOW}==={NO_COLOR} more or "
         "{PURPLE}({NO_COLOR}q{PURPLE}){NO_COLOR}uit "
         "{YELLOW}==={NO_COLOR}")
     while len(lines) > h - 1:
         print("".join(lines[:h - 1]), end="", flush=True, file=sys.stderr)
         lines = lines[h - 1:]
         print(more_msg, end="", flush=True, file=sys.stderr)
         q = sys.stdin.read(1).lower()
         print(flush=True, file=sys.stderr)
         if q == "q":
             rl_on_new_line()
             return 0
     print("".join(lines), end="", flush=True, file=sys.stderr)
     rl_on_new_line()
     return 0
Exemple #15
0
 def _querycompletions(self, completions, loc):
     """Returns whether or not we should show completions. 0 means that prefixes
     should not be shown, 1 means that there is a common prefix among all completions
     and they should be shown, while 2 means that there is no common prefix but
     we are under the query limit and they should be shown.
     """
     if os.path.commonprefix([c[loc:] for c in completions]):
         return 1
     elif len(completions) <= builtins.__xonsh__.env.get("COMPLETION_QUERY_LIMIT"):
         return 2
     msg = "\nDisplay all {} possibilities? ".format(len(completions))
     msg += "({GREEN}y{NO_COLOR} or {RED}n{NO_COLOR})"
     self.print_color(msg, end="", flush=True, file=sys.stderr)
     yn = "x"
     while yn not in "yn":
         yn = sys.stdin.read(1)
     show_completions = to_bool(yn)
     print()
     if not show_completions:
         rl_on_new_line()
         return 0
     w, h = shutil.get_terminal_size()
     lines = columnize(completions, width=w)
     more_msg = self.format_color(
         "{YELLOW}==={NO_COLOR} more or "
         "{PURPLE}({NO_COLOR}q{PURPLE}){NO_COLOR}uit "
         "{YELLOW}==={NO_COLOR}"
     )
     while len(lines) > h - 1:
         print("".join(lines[: h - 1]), end="", flush=True, file=sys.stderr)
         lines = lines[h - 1 :]
         print(more_msg, end="", flush=True, file=sys.stderr)
         q = sys.stdin.read(1).lower()
         print(flush=True, file=sys.stderr)
         if q == "q":
             rl_on_new_line()
             return 0
     print("".join(lines), end="", flush=True, file=sys.stderr)
     rl_on_new_line()
     return 0
Exemple #16
0
def test_to_bool(inp, exp):
    obs = to_bool(inp)
    assert exp == obs
Exemple #17
0
def test_to_bool(inp, exp):
    obs = to_bool(inp)
    assert exp == obs