示例#1
0
    def diff(
        a,
        b,
        reopen=False,
        verbose=False,
        _stdout=None,
    ):
        """Diff two xonsh history files

        Parameters
        ----------
        left:
            The first file to diff
        right:
            The second file to diff
        reopen: -r, --reopen
            make lazy file loading reopen files each time
        verbose: -v, --verbose
            whether to print even more information
        """

        hist = XSH.history
        if isinstance(hist, JsonHistory):
            hd = xdh.HistoryDiffer(a, b, reopen=reopen, verbose=verbose)
            xt.print_color(hd.format(), file=_stdout)
示例#2
0
def _list(
    names: Annotated[tuple, Arg(nargs="*")] = (),
    to_json=False,
):
    """List xontribs, whether they are installed, and loaded.

    Parameters
    ----------
    to_json : -j, --json
        reports results as json
    names
        names of xontribs
    """
    data = xontrib_data(names)
    if to_json:
        s = json.dumps(data)
        print(s)
    else:
        nname = max([6] + [len(x) for x in data])
        s = ""
        for name, d in data.items():
            lname = len(name)
            s += "{PURPLE}" + name + "{RESET}  " + " " * (nname - lname)
            if d["installed"]:
                s += "{GREEN}installed{RESET}      "
            else:
                s += "{RED}not-installed{RESET}  "
            if d["loaded"]:
                s += "{GREEN}loaded{RESET}"
            else:
                s += "{RED}not-loaded{RESET}"
            s += "\n"
        print_color(s[:-1])
示例#3
0
def _colors(
    style: Annotated[str, Arg(nargs="?", completer=xonfig_color_completer)] = None
):
    """Preview color style

    Parameters
    ----------
    style
        name of the style to preview. If not given, current style name is used.
    """
    columns, _ = shutil.get_terminal_size()
    columns -= int(bool(ON_WINDOWS))
    style_stash = XSH.env["XONSH_COLOR_STYLE"]

    if style is not None:
        if style not in color_style_names():
            print(f"Invalid style: {style}")
            return
        XSH.env["XONSH_COLOR_STYLE"] = style

    color_map = color_style()
    if not color_map:
        print("Empty color map - using non-interactive shell?")
        return
    akey = next(iter(color_map))
    if isinstance(akey, str):
        s = _str_colors(color_map, columns)
    else:
        s = _tok_colors(color_map, columns)
    print_color(s)
    XSH.env["XONSH_COLOR_STYLE"] = style_stash
示例#4
0
def test_left_prompt_process_ansi_pre_post(format_prompt):
    # tok.field=None fg='' bg=''
    # tok.field='env_name' fg='INTENSE_WHITE' bg='#009B77'
    # tok.field='user_at_host' fg='INTENSE_WHITE' bg='#6B5B95'
    # tok.field='cwd' fg='white' bg='#181818'
    exp_first = ("\x01\x1b]133;A\x07\x02"
                 "{BACKGROUND_#009B77}{INTENSE_WHITE}venv1"
                 "{BACKGROUND_#6B5B95}{#009B77}"
                 "{INTENSE_WHITE}user1✸bot"
                 "{BACKGROUND_#181818}{#6B5B95}"
                 "{WHITE}/home/tst"
                 "{RESET}{#181818}{RESET}")
    exp_sec = ("{BACKGROUND_#181818}{WHITE}gitstatus"
               "{RESET}{#181818}{RESET}"
               "{INTENSE_WHITE}❯ "
               "\x01\x1b]133;B\x07\x02")
    template = (
        "\x01\x1b]133;A\x07\x02"  # empty prefix
        "{env_name}{user_at_host}{cwd}\n{gitstatus}{prompt_end}"
        "\x01\x1b]133;B\x07\x02"  # empty suffix
    )
    prompt = format_prompt(template)
    first_line, sec_line = prompt.splitlines(keepends=False)

    # for debugging
    from xonsh.tools import print_color

    print_color(first_line)
    print_color(sec_line)
    assert first_line == exp_first
    assert sec_line == exp_sec
示例#5
0
    def pinfo(self, obj, oname='', info=None, detail_level=0):
        """Show detailed information about an object.

        Parameters
        ----------
        obj : object
        oname : str, optional
            name of the variable pointing to the object.
        info : dict, optional
            a structure with some information fields which may have been
            precomputed already.
        detail_level : int, optional
            if set to 1, more information is given.
        """
        info = self.info(obj,
                         oname=oname,
                         info=info,
                         detail_level=detail_level)
        displayfields = []

        def add_fields(fields):
            for title, key in fields:
                field = info[key]
                if field is not None:
                    displayfields.append((title, field.rstrip()))

        add_fields(self.pinfo_fields1)
        add_fields(self.pinfo_fields2)

        # Namespace
        if (info['namespace'] is not None and
           info['namespace'] != 'Interactive'):
                displayfields.append(("Namespace", info['namespace'].rstrip()))

        add_fields(self.pinfo_fields3)
        if info['isclass'] and info['init_definition']:
            displayfields.append(("Init definition",
                                  info['init_definition'].rstrip()))

        # Source or docstring, depending on detail level and whether
        # source found.
        if detail_level > 0 and info['source'] is not None:
            displayfields.append(("Source", cast_unicode(info['source'])))
        elif info['docstring'] is not None:
            displayfields.append(("Docstring", info["docstring"]))

        # Constructor info for classes
        if info['isclass']:
            if info['init_docstring'] is not None:
                displayfields.append(("Init docstring",
                                      info['init_docstring']))

        # Info for objects:
        else:
            add_fields(self.pinfo_fields_obj)

        # Finally send to printer/pager:
        if displayfields:
            print_color(self._format_fields(displayfields))
示例#6
0
    def pinfo(self, obj, oname='', info=None, detail_level=0):
        """Show detailed information about an object.

        Parameters
        ----------
        obj : object
        oname : str, optional
            name of the variable pointing to the object.
        info : dict, optional
            a structure with some information fields which may have been
            precomputed already.
        detail_level : int, optional
            if set to 1, more information is given.
        """
        info = self.info(obj,
                         oname=oname,
                         info=info,
                         detail_level=detail_level)
        displayfields = []

        def add_fields(fields):
            for title, key in fields:
                field = info[key]
                if field is not None:
                    displayfields.append((title, field.rstrip()))

        add_fields(self.pinfo_fields1)
        add_fields(self.pinfo_fields2)

        # Namespace
        if (info['namespace'] is not None
                and info['namespace'] != 'Interactive'):
            displayfields.append(("Namespace", info['namespace'].rstrip()))

        add_fields(self.pinfo_fields3)
        if info['isclass'] and info['init_definition']:
            displayfields.append(
                ("Init definition", info['init_definition'].rstrip()))

        # Source or docstring, depending on detail level and whether
        # source found.
        if detail_level > 0 and info['source'] is not None:
            displayfields.append(("Source", cast_unicode(info['source'])))
        elif info['docstring'] is not None:
            displayfields.append(("Docstring", info["docstring"]))

        # Constructor info for classes
        if info['isclass']:
            if info['init_docstring'] is not None:
                displayfields.append(
                    ("Init docstring", info['init_docstring']))

        # Info for objects:
        else:
            add_fields(self.pinfo_fields_obj)

        # Finally send to printer/pager:
        if displayfields:
            print_color(self._format_fields(displayfields))
示例#7
0
def _colors(ns):
    cols, _ = shutil.get_terminal_size()
    cmap = tools.color_style()
    akey = next(iter(cmap))
    if isinstance(akey, str):
        s = _str_colors(cmap, cols)
    else:
        s = _tok_colors(cmap, cols)
    tools.print_color(s)
示例#8
0
文件: environ.py 项目: Carreau/xonsh
 def help(self, key):
     """Get information about a specific enviroment variable."""
     vardocs = self.get_docs(key)
     width = min(79, os.get_terminal_size()[0])
     docstr = "\n".join(textwrap.wrap(vardocs.docstr, width=width))
     template = HELP_TEMPLATE.format(
         envvar=key, docstr=docstr, default=vardocs.default, configurable=vardocs.configurable
     )
     print_color(template)
示例#9
0
def _colors(ns):
    cols, _ = shutil.get_terminal_size()
    cmap = tools.color_style()
    akey = next(iter(cmap))
    if isinstance(akey, str):
        s = _str_colors(cmap, cols)
    else:
        s = _tok_colors(cmap, cols)
    tools.print_color(s)
示例#10
0
def show():
    fig = plt.gcf()
    w, h = shutil.get_terminal_size()
    if ON_WINDOWS:
        w -= 1  # @melund reports that win terminals are too thin
    h -= 1  # leave space for next prompt
    buf = figure_to_rgb_array(fig, w, h)
    s = buf_to_color_str(buf)
    print_color(s)
示例#11
0
def show():
    fig = plt.gcf()
    w, h = shutil.get_terminal_size()
    if ON_WINDOWS:
        w -= 1  # @melund reports that win terminals are too thin
    h -= 1  # leave space for next prompt
    buf = figure_to_rgb_array(fig, w, h)
    s = buf_to_color_str(buf)
    print_color(s)
示例#12
0
def print_welcome_screen():
    subst = dict(tagline=random.choice(list(TAGLINES)), version=XONSH_VERSION)
    for elem in WELCOME_MSG:
        if isinstance(elem, str):
            elem = (elem, "", "")
        line = elem[0].format(**subst)
        termwidth = os.get_terminal_size().columns
        line = _align_string(line, elem[1], elem[2], width=termwidth)
        print_color(line)
示例#13
0
文件: xonfig.py 项目: roblabla/xonsh
def print_welcome_screen():
    subst = dict(tagline=random.choice(list(TAGLINES)), version=XONSH_VERSION)
    for elem in WELCOME_MSG:
        if isinstance(elem, str):
            elem = (elem, "", "")
        line = elem[0].format(**subst)
        termwidth = os.get_terminal_size().columns
        line = _align_string(line, elem[1], elem[2], width=termwidth)
        print_color(line)
示例#14
0
 def help(self, key):
     """Get information about a specific enviroment variable."""
     vardocs = self.get_docs(key)
     width = min(79, os.get_terminal_size()[0])
     docstr = '\n'.join(textwrap.wrap(vardocs.docstr, width=width))
     template = HELP_TEMPLATE.format(envvar=key,
                                     docstr=docstr,
                                     default=vardocs.default,
                                     configurable=vardocs.configurable)
     print_color(template)
示例#15
0
文件: xonfig.py 项目: Siecje/xonsh
def _colors(ns):
    cols, _ = shutil.get_terminal_size()
    if ON_WINDOWS:
        cols -= 1
    cmap = color_style()
    akey = next(iter(cmap))
    if isinstance(akey, str):
        s = _str_colors(cmap, cols)
    else:
        s = _tok_colors(cmap, cols)
    print_color(s)
示例#16
0
def _colors(ns):
    cols, _ = shutil.get_terminal_size()
    if ON_WINDOWS:
        cols -= 1
    cmap = color_style()
    akey = next(iter(cmap))
    if isinstance(akey, str):
        s = _str_colors(cmap, cols)
    else:
        s = _tok_colors(cmap, cols)
    print_color(s)
示例#17
0
def _pprint_displayhook(value):
    if value is not None:
        builtins._ = None  # Set '_' to None to avoid recursion
        if HAVE_PYGMENTS:
            s = pretty(value)  # color case
            lexer = pyghooks.XonshLexer()
            tokens = list(pygments.lex(s, lexer=lexer))
            print_color(tokens)
        else:
            pprint(value)  # black & white case
        builtins._ = value
示例#18
0
文件: main.py 项目: refi64/xonsh
def _pprint_displayhook(value):
    if value is None or isinstance(value, HiddenCompletedCommand):
        return
    builtins._ = None  # Set '_' to None to avoid recursion
    if HAVE_PYGMENTS:
        s = pretty(value)  # color case
        lexer = pyghooks.XonshLexer()
        tokens = list(pygments.lex(s, lexer=lexer))
        print_color(tokens)
    else:
        pprint(value)  # black & white case
    builtins._ = value
示例#19
0
文件: main.py 项目: aterrel/xonsh
def _pprint_displayhook(value):
    if value is None or isinstance(value, HiddenCompletedCommand):
        return
    builtins._ = None  # Set '_' to None to avoid recursion
    if HAS_PYGMENTS:
        s = pretty(value)  # color case
        lexer = pyghooks.XonshLexer()
        tokens = list(pygments.lex(s, lexer=lexer))
        print_color(tokens)
    else:
        pprint(value)  # black & white case
    builtins._ = value
示例#20
0
文件: tracer.py 项目: asmeurer/xonsh
 def trace(self, frame, event, arg):
     """Implements a line tracing function."""
     if event not in self.valid_events:
         return self.trace
     fname = inspectors.find_file(frame)
     if fname in self.files:
         lineno = frame.f_lineno
         curr = (fname, lineno)
         if curr != self._last:
             line = linecache.getline(fname, lineno).rstrip()
             s = format_line(fname, lineno, line, color=self.usecolor, lexer=self.lexer, formatter=self.formatter)
             print_color(s)
             self._last = curr
     return self.trace
示例#21
0
    def log(self, message, category="misc", data=None):
        """Logs a message, the timestamp, its category, and the
        and any data to the log file.
        """
        self._dirty = True
        entry = {"message": message, "timestamp": time.time(), "category": category}
        if data is not None:
            entry["data"] = data

        # write to log file
        json.appendline(entry, self.filename)
        # write to stdout
        msg = "{INTENSE_CYAN}" + category + "{PURPLE}:"
        msg += "{INTENSE_WHITE}" + message + "{NO_COLOR}"
        print_color(msg)
示例#22
0
文件: xonfig.py 项目: Siecje/xonsh
def _styles(ns):
    env = builtins.__xonsh_env__
    curr = env.get('XONSH_COLOR_STYLE')
    styles = sorted(color_style_names())
    if ns.json:
        s = json.dumps(styles, sort_keys=True, indent=1)
        print(s)
        return
    lines = []
    for style in styles:
        if style == curr:
            lines.append('* {GREEN}' + style + '{NO_COLOR}')
        else:
            lines.append('  ' + style)
    s = '\n'.join(lines)
    print_color(s)
示例#23
0
文件: xonfig.py 项目: roblabla/xonsh
def _styles(ns):
    env = builtins.__xonsh__.env
    curr = env.get("XONSH_COLOR_STYLE")
    styles = sorted(color_style_names())
    if ns.json:
        s = json.dumps(styles, sort_keys=True, indent=1)
        print(s)
        return
    lines = []
    for style in styles:
        if style == curr:
            lines.append("* {GREEN}" + style + "{RESET}")
        else:
            lines.append("  " + style)
    s = "\n".join(lines)
    print_color(s)
示例#24
0
def _styles(ns):
    env = builtins.__xonsh__.env
    curr = env.get("XONSH_COLOR_STYLE")
    styles = sorted(color_style_names())
    if ns.json:
        s = json.dumps(styles, sort_keys=True, indent=1)
        print(s)
        return
    lines = []
    for style in styles:
        if style == curr:
            lines.append("* {GREEN}" + style + "{NO_COLOR}")
        else:
            lines.append("  " + style)
    s = "\n".join(lines)
    print_color(s)
示例#25
0
def _styles(ns):
    env = builtins.__xonsh_env__
    curr = env.get('XONSH_COLOR_STYLE')
    styles = sorted(color_style_names())
    if ns.json:
        s = json.dumps(styles, sort_keys=True, indent=1)
        print(s)
        return
    lines = []
    for style in styles:
        if style == curr:
            lines.append('* {GREEN}' + style + '{NO_COLOR}')
        else:
            lines.append('  ' + style)
    s = '\n'.join(lines)
    print_color(s)
示例#26
0
def source_alias(args, stdin=None):
    """Executes the contents of the provided files in the current context.
    If sourced file isn't found in cwd, search for file along $PATH to source
    instead.
    """
    env = builtins.__xonsh__.env
    encoding = env.get("XONSH_ENCODING")
    errors = env.get("XONSH_ENCODING_ERRORS")
    for i, fname in enumerate(args):
        fpath = fname
        if not os.path.isfile(fpath):
            fpath = locate_binary(fname)
            if fpath is None:
                if env.get("XONSH_DEBUG"):
                    print("source: {}: No such file".format(fname), file=sys.stderr)
                if i == 0:
                    raise RuntimeError(
                        "must source at least one file, " + fname + "does not exist."
                    )
                break
        _, fext = os.path.splitext(fpath)
        if fext and fext != ".xsh" and fext != ".py":
            raise RuntimeError(
                "attempting to source non-xonsh file! If you are "
                "trying to source a file in another language, "
                "then please use the appropriate source command. "
                "For example, source-bash script.sh"
            )
        with open(fpath, "r", encoding=encoding, errors=errors) as fp:
            src = fp.read()
        if not src.endswith("\n"):
            src += "\n"
        ctx = builtins.__xonsh__.ctx
        updates = {"__file__": fpath, "__name__": os.path.abspath(fpath)}
        with env.swap(**make_args_env(args[i + 1 :])), swap_values(ctx, updates):
            try:
                builtins.execx(src, "exec", ctx, filename=fpath)
            except Exception:
                print_color(
                    "{RED}You may be attempting to source non-xonsh file! "
                    "{NO_COLOR}If you are trying to source a file in "
                    "another language, then please use the appropriate "
                    "source command. For example, {GREEN}source-bash "
                    "script.sh{NO_COLOR}",
                    file=sys.stderr,
                )
                raise
示例#27
0
def source_alias(args, stdin=None):
    """Executes the contents of the provided files in the current context.
    If sourced file isn't found in cwd, search for file along $PATH to source
    instead.
    """
    env = builtins.__xonsh_env__
    encoding = env.get("XONSH_ENCODING")
    errors = env.get("XONSH_ENCODING_ERRORS")
    for i, fname in enumerate(args):
        fpath = fname
        if not os.path.isfile(fpath):
            fpath = locate_binary(fname)
            if fpath is None:
                if env.get("XONSH_DEBUG"):
                    print("source: {}: No such file".format(fname),
                          file=sys.stderr)
                if i == 0:
                    raise RuntimeError("must source at least one file, " +
                                       fname + "does not exist.")
                break
        _, fext = os.path.splitext(fpath)
        if fext and fext != ".xsh" and fext != ".py":
            raise RuntimeError(
                "attempting to source non-xonsh file! If you are "
                "trying to source a file in another language, "
                "then please use the appropriate source command. "
                "For example, source-bash script.sh")
        with open(fpath, "r", encoding=encoding, errors=errors) as fp:
            src = fp.read()
        if not src.endswith("\n"):
            src += "\n"
        ctx = builtins.__xonsh_ctx__
        updates = {"__file__": fpath, "__name__": os.path.abspath(fpath)}
        with env.swap(**make_args_env(args[i + 1:])), swap_values(
                ctx, updates):
            try:
                builtins.execx(src, "exec", ctx, filename=fpath)
            except Exception:
                print_color(
                    "{RED}You may be attempting to source non-xonsh file! "
                    "{NO_COLOR}If you are trying to source a file in "
                    "another language, then please use the appropriate "
                    "source command. For example, {GREEN}source-bash "
                    "script.sh{NO_COLOR}",
                    file=sys.stderr,
                )
                raise
示例#28
0
def source_alias(args, stdin=None):
    """Executes the contents of the provided files in the current context.
    If sourced file isn't found in cwd, search for file along $PATH to source
    instead.
    """
    env = builtins.__xonsh_env__
    encoding = env.get('XONSH_ENCODING')
    errors = env.get('XONSH_ENCODING_ERRORS')
    for i, fname in enumerate(args):
        fpath = fname
        if not os.path.isfile(fpath):
            fpath = locate_binary(fname)
            if fpath is None:
                if env.get('XONSH_DEBUG'):
                    print('source: {}: No such file'.format(fname),
                          file=sys.stderr)
                if i == 0:
                    raise RuntimeError('must source at least one file, ' +
                                       fname + 'does not exist.')
                break
        _, fext = os.path.splitext(fpath)
        if fext and fext != '.xsh' and fext != '.py':
            raise RuntimeError(
                'attempting to source non-xonsh file! If you are '
                'trying to source a file in another language, '
                'then please use the appropriate source command. '
                'For example, source-bash script.sh')
        with open(fpath, 'r', encoding=encoding, errors=errors) as fp:
            src = fp.read()
        if not src.endswith('\n'):
            src += '\n'
        ctx = builtins.__xonsh_ctx__
        updates = {'__file__': fpath, '__name__': os.path.abspath(fpath)}
        with env.swap(**make_args_env(args[i + 1:])), swap_values(
                ctx, updates):
            try:
                builtins.execx(src, 'exec', ctx, filename=fpath)
            except Exception:
                print_color(
                    '{RED}You may be attempting to source non-xonsh file! '
                    '{NO_COLOR}If you are trying to source a file in '
                    'another language, then please use the appropriate '
                    'source command. For example, {GREEN}source-bash '
                    'script.sh{NO_COLOR}',
                    file=sys.stderr)
                raise
示例#29
0
文件: tracer.py 项目: moealmaw/xonsh
 def trace(self, frame, event, arg):
     """Implements a line tracing function."""
     if event not in self.valid_events:
         return self.trace
     fname = find_file(frame)
     if fname in self.files:
         lineno = frame.f_lineno
         curr = (fname, lineno)
         if curr != self._last:
             line = linecache.getline(fname, lineno).rstrip()
             s = tracer_format_line(fname, lineno, line,
                                    color=self.usecolor,
                                    lexer=self.lexer,
                                    formatter=self.formatter)
             print_color(s)
             self._last = curr
     return self.trace
示例#30
0
def show():
    '''Run the mpl display sequence by printing the most recent figure to console'''
    try:
        minimal = __xonsh_env__['XONTRIB_MPL_MINIMAL']
    except KeyError:
        minimal = XONTRIB_MPL_MINIMAL_DEFAULT
    fig = plt.gcf()
    if _use_iterm:
        display_figure_with_iterm2(fig)
    else:
        # Display the image using terminal characters to fit into the console
        w, h = shutil.get_terminal_size()
        if ON_WINDOWS:
            w -= 1  # @melund reports that win terminals are too thin
        h -= 1  # leave space for next prompt
        buf = figure_to_tight_array(fig, w, h, minimal)
        s = buf_to_color_str(buf)
        print_color(s)
示例#31
0
 def visit_load(self, node):
     if node.check:
         ap = 'Would you like to load an existing file, ' + YN
         asker = TrueFalse(prompt=ap)
         do_load = self.visit(asker)
         if not do_load:
             return Unstorable
     fname = self.visit_input(node)
     if fname is None or len(fname) == 0:
         fname = node.default_file
     if os.path.isfile(fname):
         with open(fname, 'r') as f:
             self.state = json.load(f)
         print_color('{{GREEN}}{0!r} loaded.{{NO_COLOR}}'.format(fname))
     else:
         print_color(('{{RED}}{0!r} could not be found, '
                      'continuing.{{NO_COLOR}}').format(fname))
     return fname
示例#32
0
文件: main.py 项目: kevindwei/xonsh
def _pprint_displayhook(value):
    if value is None:
        return
    builtins._ = None  # Set '_' to None to avoid recursion
    if isinstance(value, HiddenCommandPipeline):
        builtins._ = value
        return
    env = builtins.__xonsh_env__
    if env.get('PRETTY_PRINT_RESULTS'):
        printed_val = pretty(value)
    else:
        printed_val = repr(value)
    if HAS_PYGMENTS and env.get('COLOR_RESULTS'):
        tokens = list(pygments.lex(printed_val, lexer=pyghooks.XonshLexer()))
        print_color(tokens)
    else:
        print(printed_val)  # black & white case
    builtins._ = value
示例#33
0
def show():
    """Run the mpl display sequence by printing the most recent figure to console"""
    try:
        minimal = __xonsh__.env["XONTRIB_MPL_MINIMAL"]
    except KeyError:
        minimal = XONTRIB_MPL_MINIMAL_DEFAULT
    fig = plt.gcf()
    if _use_iterm:
        display_figure_with_iterm2(fig)
    else:
        # Display the image using terminal characters to fit into the console
        w, h = shutil.get_terminal_size()
        if ON_WINDOWS:
            w -= 1  # @melund reports that win terminals are too thin
        h -= 1  # leave space for next prompt
        buf = figure_to_tight_array(fig, w, h, minimal)
        s = buf_to_color_str(buf)
        print_color(s)
示例#34
0
文件: main.py 项目: vsajip/xonsh
def _pprint_displayhook(value):
    if value is None:
        return
    builtins._ = None  # Set '_' to None to avoid recursion
    if isinstance(value, HiddenCommandPipeline):
        builtins._ = value
        return
    env = builtins.__xonsh_env__
    if env.get('PRETTY_PRINT_RESULTS'):
        printed_val = pretty(value)
    else:
        printed_val = repr(value)
    if HAS_PYGMENTS and env.get('COLOR_RESULTS'):
        tokens = list(pygments.lex(printed_val, lexer=pyghooks.XonshLexer()))
        print_color(tokens)
    else:
        print(printed_val)  # black & white case
    builtins._ = value
示例#35
0
文件: main.py 项目: sailychen/xonsh
def _pprint_displayhook(value):
    if value is None:
        return
    builtins._ = None  # Set '_' to None to avoid recursion
    if isinstance(value, HiddenCommandPipeline):
        builtins._ = value
        return
    env = builtins.__xonsh__.env
    if env.get("PRETTY_PRINT_RESULTS"):
        printed_val = pretty(value)
    else:
        printed_val = repr(value)
    if HAS_PYGMENTS and env.get("COLOR_RESULTS"):
        tokens = list(pygments.lex(printed_val, lexer=pyghooks.XonshLexer()))
        end = "" if env.get("SHELL_TYPE") == "prompt_toolkit2" else "\n"
        print_color(tokens, end=end)
    else:
        print(printed_val)  # black & white case
    builtins._ = value
示例#36
0
文件: main.py 项目: mitnk/xonsh
def _pprint_displayhook(value):
    if value is None:
        return
    builtins._ = None  # Set '_' to None to avoid recursion
    if isinstance(value, HiddenCommandPipeline):
        builtins._ = value
        return
    env = builtins.__xonsh__.env
    if env.get("PRETTY_PRINT_RESULTS"):
        printed_val = pretty(value)
    else:
        printed_val = repr(value)
    if HAS_PYGMENTS and env.get("COLOR_RESULTS"):
        tokens = list(pygments.lex(printed_val, lexer=pyghooks.XonshLexer()))
        end = "" if env.get("SHELL_TYPE") == "prompt_toolkit2" else "\n"
        print_color(tokens, end=end)
    else:
        print(printed_val)  # black & white case
    builtins._ = value
示例#37
0
    def log(self, message, category='misc', data=None):
        """Logs a message, the timestamp, its category, and the
        and any data to the log file.
        """
        self._dirty = True
        entry = {
            'message': message,
            'timestamp': time.time(),
            'category': category
        }
        if data is not None:
            entry['data'] = data

        # write to log file
        json.appendline(entry, self.filename)
        # write to stdout
        msg = '{INTENSE_CYAN}' + category + '{PURPLE}:'
        msg += '{INTENSE_WHITE}' + message + '{NO_COLOR}'
        print_color(msg)
示例#38
0
文件: xonfig.py 项目: Carreau/xonsh
def _colors(args):
    columns, _ = shutil.get_terminal_size()
    columns -= int(ON_WINDOWS)
    style_stash = builtins.__xonsh_env__["XONSH_COLOR_STYLE"]

    if args.style is not None:
        if args.style not in color_style_names():
            print("Invalid style: {}".format(args.style))
            return
        builtins.__xonsh_env__["XONSH_COLOR_STYLE"] = args.style

    color_map = color_style()
    akey = next(iter(color_map))
    if isinstance(akey, str):
        s = _str_colors(color_map, columns)
    else:
        s = _tok_colors(color_map, columns)
    print_color(s)
    builtins.__xonsh_env__["XONSH_COLOR_STYLE"] = style_stash
示例#39
0
文件: xonfig.py 项目: roblabla/xonsh
def _colors(args):
    columns, _ = shutil.get_terminal_size()
    columns -= int(ON_WINDOWS)
    style_stash = builtins.__xonsh__.env["XONSH_COLOR_STYLE"]

    if args.style is not None:
        if args.style not in color_style_names():
            print("Invalid style: {}".format(args.style))
            return
        builtins.__xonsh__.env["XONSH_COLOR_STYLE"] = args.style

    color_map = color_style()
    akey = next(iter(color_map))
    if isinstance(akey, str):
        s = _str_colors(color_map, columns)
    else:
        s = _tok_colors(color_map, columns)
    print_color(s)
    builtins.__xonsh__.env["XONSH_COLOR_STYLE"] = style_stash
示例#40
0
文件: aliases.py 项目: VHarisop/xonsh
def source_alias(args, stdin=None):
    """Executes the contents of the provided files in the current context.
    If sourced file isn't found in cwd, search for file along $PATH to source
    instead.
    """
    env = builtins.__xonsh_env__
    encoding = env.get('XONSH_ENCODING')
    errors = env.get('XONSH_ENCODING_ERRORS')
    for i, fname in enumerate(args):
        fpath = fname
        if not os.path.isfile(fpath):
            fpath = locate_binary(fname)
            if fpath is None:
                if env.get('XONSH_DEBUG'):
                    print('source: {}: No such file'.format(fname), file=sys.stderr)
                if i == 0:
                    raise RuntimeError('must source at least one file, ' + fname +
                                       'does not exist.')
                break
        _, fext = os.path.splitext(fpath)
        if fext and fext != '.xsh' and fext != '.py':
            raise RuntimeError('attempting to source non-xonsh file! If you are '
                               'trying to source a file in another language, '
                               'then please use the appropriate source command. '
                               'For example, source-bash script.sh')
        with open(fpath, 'r', encoding=encoding, errors=errors) as fp:
            src = fp.read()
        if not src.endswith('\n'):
            src += '\n'
        ctx = builtins.__xonsh_ctx__
        updates = {'__file__': fpath, '__name__': os.path.abspath(fpath)}
        with env.swap(ARGS=args[i+1:]), swap_values(ctx, updates):
            try:
                builtins.execx(src, 'exec', ctx, filename=fpath)
            except Exception:
                print_color('{RED}You may be attempting to source non-xonsh file! '
                            '{NO_COLOR}If you are trying to source a file in '
                            'another language, then please use the appropriate '
                            'source command. For example, {GREEN}source-bash '
                            'script.sh{NO_COLOR}', file=sys.stderr)
                raise
示例#41
0
def _list(ns):
    """Lists xontribs."""
    meta = xontrib_metadata()
    data = []
    nname = 6  # ensures some buffer space.
    names = None if len(ns.names) == 0 else set(ns.names)
    for md in meta['xontribs']:
        name = md['name']
        if names is not None and md['name'] not in names:
            continue
        nname = max(nname, len(name))
        spec = find_xontrib(name)
        if spec is None:
            installed = loaded = False
        else:
            installed = True
            loaded = spec.name in sys.modules
        d = {'name': name, 'installed': installed, 'loaded': loaded}
        data.append(d)
    if ns.json:
        jdata = {d.pop('name'): d for d in data}
        s = json.dumps(jdata)
        print(s)
    else:
        s = ""
        for d in data:
            name = d['name']
            lname = len(name)
            s += "{PURPLE}" + name + "{NO_COLOR}  " + " " * (nname - lname)
            if d['installed']:
                s += '{GREEN}installed{NO_COLOR}      '
            else:
                s += '{RED}not-installed{NO_COLOR}  '
            if d['loaded']:
                s += '{GREEN}loaded{NO_COLOR}'
            else:
                s += '{RED}not-loaded{NO_COLOR}'
            s += '\n'
        print_color(s[:-1])
示例#42
0
def _list(ns):
    """Lists xontribs."""
    meta = xontrib_metadata()
    data = []
    nname = 6  # ensures some buffer space.
    names = None if len(ns.names) == 0 else set(ns.names)
    for md in meta["xontribs"]:
        name = md["name"]
        if names is not None and md["name"] not in names:
            continue
        nname = max(nname, len(name))
        spec = find_xontrib(name)
        if spec is None:
            installed = loaded = False
        else:
            installed = True
            loaded = spec.name in sys.modules
        d = {"name": name, "installed": installed, "loaded": loaded}
        data.append(d)
    if ns.json:
        jdata = {d.pop("name"): d for d in data}
        s = json.dumps(jdata)
        print(s)
    else:
        s = ""
        for d in data:
            name = d["name"]
            lname = len(name)
            s += "{PURPLE}" + name + "{RESET}  " + " " * (nname - lname)
            if d["installed"]:
                s += "{GREEN}installed{RESET}      "
            else:
                s += "{RED}not-installed{RESET}  "
            if d["loaded"]:
                s += "{GREEN}loaded{RESET}"
            else:
                s += "{RED}not-loaded{RESET}"
            s += "\n"
        print_color(s[:-1])
示例#43
0
def test_left_prompt_process_normal(format_prompt):
    """all parts have a field associated"""
    exp_first = ("{BACKGROUND_#009B77}{INTENSE_WHITE}venv1"
                 "{BACKGROUND_#6B5B95}{#009B77}"
                 "{INTENSE_WHITE}user1✸bot"
                 "{BACKGROUND_#181818}{#6B5B95}"
                 "{WHITE}/home/tst"
                 "{RESET}{#181818}{RESET}")
    exp_sec = ("{BACKGROUND_#181818}{WHITE}gitstatus"
               "{RESET}{#181818}{RESET}"
               "{INTENSE_WHITE}❯ ")
    template = "{env_name}{user_at_host}{cwd}\n{gitstatus}{prompt_end}"
    prompt = format_prompt(template)
    first_line, sec_line = prompt.splitlines(keepends=False)

    # for debugging
    from xonsh.tools import print_color

    print_color(first_line)
    print_color(sec_line)
    assert first_line == exp_first
    assert sec_line == exp_sec
示例#44
0
def _list(ns):
    """Lists xontribs."""
    data = xontrib_data(ns)
    if ns.json:
        s = json.dumps(data)
        print(s)
    else:
        nname = max([6] + [len(x) for x in data])
        s = ""
        for name, d in data.items():
            lname = len(name)
            s += "{PURPLE}" + name + "{RESET}  " + " " * (nname - lname)
            if d["installed"]:
                s += "{GREEN}installed{RESET}      "
            else:
                s += "{RED}not-installed{RESET}  "
            if d["loaded"]:
                s += "{GREEN}loaded{RESET}"
            else:
                s += "{RED}not-loaded{RESET}"
            s += "\n"
        print_color(s[:-1])
示例#45
0
def _list(ns):
    """Lists xontribs."""
    meta = xontrib_metadata()
    data = []
    nname = 6  # ensures some buffer space.
    names = None if len(ns.names) == 0 else set(ns.names)
    for md in meta["xontribs"]:
        name = md["name"]
        if names is not None and md["name"] not in names:
            continue
        nname = max(nname, len(name))
        spec = find_xontrib(name)
        if spec is None:
            installed = loaded = False
        else:
            installed = True
            loaded = spec.name in sys.modules
        d = {"name": name, "installed": installed, "loaded": loaded}
        data.append(d)
    if ns.json:
        jdata = {d.pop("name"): d for d in data}
        s = json.dumps(jdata)
        print(s)
    else:
        s = ""
        for d in data:
            name = d["name"]
            lname = len(name)
            s += "{PURPLE}" + name + "{NO_COLOR}  " + " " * (nname - lname)
            if d["installed"]:
                s += "{GREEN}installed{NO_COLOR}      "
            else:
                s += "{RED}not-installed{NO_COLOR}  "
            if d["loaded"]:
                s += "{GREEN}loaded{NO_COLOR}"
            else:
                s += "{RED}not-loaded{NO_COLOR}"
            s += "\n"
        print_color(s[:-1])
示例#46
0
文件: xontribs.py 项目: laerus/xonsh
def _list(ns):
    """Lists xontribs."""
    meta = xontrib_metadata()
    data = []
    nname = 6  # ensures some buffer space.
    names = None if len(ns.names) == 0 else set(ns.names)
    for md in meta['xontribs']:
        name = md['name']
        if names is not None and md['name'] not in names:
            continue
        nname = max(nname, len(name))
        spec = find_xontrib(name)
        if spec is None:
            installed = loaded = False
        else:
            installed = True
            loaded = spec.name in sys.modules
        d = {'name': name, 'installed': installed, 'loaded': loaded}
        data.append(d)
    if ns.json:
        jdata = {d.pop('name'): d for d in data}
        s = json.dumps(jdata)
        print(s)
    else:
        s = ""
        for d in data:
            name = d['name']
            lname = len(name)
            s += "{PURPLE}" + name + "{NO_COLOR}  " + " "*(nname - lname)
            if d['installed']:
                s += '{GREEN}installed{NO_COLOR}      '
            else:
                s += '{RED}not-installed{NO_COLOR}  '
            if d['loaded']:
                s += '{GREEN}loaded{NO_COLOR}'
            else:
                s += '{RED}not-loaded{NO_COLOR}'
            s += '\n'
        print_color(s[:-1])
示例#47
0
 def visit_input(self, node):
     need_input = True
     while need_input:
         self.env["PROMPT"] = node.prompt
         raw = self.shell.singleline(**self.shell_kwargs)
         if callable(node.converter):
             try:
                 x = node.converter(raw)
             except KeyboardInterrupt:
                 raise
             except Exception:
                 if node.retry:
                     msg = (
                         "{{BOLD_RED}}Invalid{{NO_COLOR}} input {0!r}, "
                         "please retry."
                     )
                     print_color(msg.format(raw))
                     continue
                 else:
                     raise
             if node.show_conversion and x is not Unstorable and str(x) != raw:
                 msg = "{{BOLD_PURPLE}}Converted{{NO_COLOR}} input {0!r} to {1!r}."
                 print_color(msg.format(raw, x))
         else:
             x = raw
         if node.confirm:
             msg = "Would you like to keep the input: {0}"
             print(msg.format(pprint.pformat(x)))
             confirmer = TrueFalseBreak(prompt=YNB)
             status = self.visit(confirmer)
             if isinstance(status, str) and status == "break":
                 x = Unstorable
                 break
             else:
                 need_input = not status
         else:
             need_input = False
     return x
示例#48
0
def _styles(to_json=False, _stdout=None):
    """Prints available xonsh color styles

    Parameters
    ----------
    to_json: -j, --json
        reports results as json
    """
    env = XSH.env
    curr = env.get("XONSH_COLOR_STYLE")
    styles = sorted(color_style_names())
    if to_json:
        s = json.dumps(styles, sort_keys=True, indent=1)
        print(s)
        return
    lines = []
    for style in styles:
        if style == curr:
            lines.append("* {GREEN}" + style + "{RESET}")
        else:
            lines.append("  " + style)
    s = "\n".join(lines)
    print_color(s, file=_stdout)
示例#49
0
 def visit_input(self, node):
     need_input = True
     while need_input:
         self.env['PROMPT'] = node.prompt
         raw = self.shell.singleline(**self.shell_kwargs)
         if callable(node.converter):
             try:
                 x = node.converter(raw)
             except KeyboardInterrupt:
                 raise
             except Exception:
                 if node.retry:
                     msg = ('{{BOLD_RED}}Invalid{{NO_COLOR}} input {0!r}, '
                            'please retry.')
                     print_color(msg.format(raw))
                     continue
                 else:
                     raise
             if node.show_conversion and x is not Unstorable \
                                     and str(x) != raw:
                 msg = '{{BOLD_PURPLE}}Converted{{NO_COLOR}} input {0!r} to {1!r}.'
                 print_color(msg.format(raw, x))
         else:
             x = raw
         if node.confirm:
             msg = 'Would you like to keep the input: {0}'
             print(msg.format(pformat(x)))
             confirmer = TrueFalseBreak(prompt=YNB)
             status = self.visit(confirmer)
             if isinstance(status, str) and status == 'break':
                 x = Unstorable
                 break
             else:
                 need_input = not status
         else:
             need_input = False
     return x
示例#50
0
文件: wizard.py 项目: bvenkatr/xonsh
 def visit_input(self, node):
     need_input = True
     while need_input:
         self.env['PROMPT'] = node.prompt
         x = self.shell.singleline(**self.shell_kwargs)
         if callable(node.converter):
             x, raw = node.converter(x), x
             if node.show_conversion and x is not Unstorable \
                                     and str(x) != raw:
                 msg = '{{BOLD_PURPLE}}Converted{{NO_COLOR}} input {0!r} to {1!r}.'
                 print_color(msg.format(raw, x))
         if node.confirm:
             msg = 'Would you like to keep the input: {0}'
             print(msg.format(pformat(x)))
             confirmer = TrueFalseBreak(prompt=YNB)
             status = self.visit(confirmer)
             if isinstance(status, str) and status == 'break':
                 x = Unstorable
                 break
             else:
                 need_input = not status
         else:
             need_input = False
     return x
示例#51
0
def dh_main_action(ns, hist=None, stdout=None, stderr=None):
    hd = HistoryDiffer(ns.a, ns.b, reopen=ns.reopen, verbose=ns.verbose)
    print_color(hd.format(), file=stdout)
示例#52
0
    def _cmdloop(self, intro=None):
        """Repeatedly issue a prompt, accept input, parse an initial prefix
        off the received input, and dispatch to action methods, passing them
        the remainder of the line as argument.

        This was forked from Lib/cmd.py from the Python standard library v3.4.3,
        (C) Python Software Foundation, 2015.
        """
        self.preloop()
        if self.use_rawinput and self.completekey:
            try:
                import readline
                self.old_completer = readline.get_completer()
                readline.set_completer(self.complete)
                readline.parse_and_bind(self.completekey + ": complete")
                have_readline = True
            except ImportError:
                have_readline = False
        try:
            if intro is not None:
                self.intro = intro
            if self.intro:
                self.stdout.write(str(self.intro)+"\n")
            stop = None
            while not stop:
                line = None
                exec_now = False
                if len(self.cmdqueue) > 0:
                    line = self.cmdqueue.popleft()
                    exec_now = line.endswith('\n')
                if self.use_rawinput and not exec_now:
                    inserter = None if line is None \
                                    else _insert_text_func(line, readline)
                    if inserter is not None:
                        readline.set_pre_input_hook(inserter)
                    try:
                        line = input(self.prompt)
                    except EOFError:
                        if builtins.__xonsh_env__.get("IGNOREEOF"):
                            self.stdout.write('Use "exit" to leave the shell.'
                                              '\n')
                            line = ''
                        else:
                            line = 'EOF'
                    if inserter is not None:
                        readline.set_pre_input_hook(None)
                else:
                    print_color(self.prompt, file=self.stdout)
                    if line is not None:
                        os.write(self.stdin.fileno(), line.encode())
                    if not exec_now:
                        line = self.stdin.readline()
                    if len(line) == 0:
                        line = 'EOF'
                    else:
                        line = line.rstrip('\r\n')
                    if have_readline and line != 'EOF':
                        readline.add_history(line)
                if not ON_WINDOWS:
                    # select() is not fully functional on windows
                    self._load_remaining_input_into_queue()
                line = self.precmd(line)
                stop = self.onecmd(line)
                stop = self.postcmd(stop, line)
            self.postloop()
        finally:
            if self.use_rawinput and self.completekey:
                try:
                    import readline
                    readline.set_completer(self.old_completer)
                except ImportError:
                    pass
示例#53
0
文件: wizard.py 项目: BlaXpirit/xonsh
 def visit_message(self, node):
     print_color(node.message)
示例#54
0
def _dh_main_action(ns, hist=None):
    hd = HistoryDiffer(ns.a, ns.b, reopen=ns.reopen, verbose=ns.verbose)
    print_color(hd.format())