Exemplo n.º 1
0
    def _kill(job):
        _send_signal(job, signal.SIGKILL)

    def _hup(job):
        _send_signal(job, signal.SIGHUP)

    def ignore_sigtstp():
        signal.signal(signal.SIGTSTP, signal.SIG_IGN)

    _shell_pgrp = os.getpgrp()  # type:ignore

    _block_when_giving = LazyObject(
        lambda: (
            signal.SIGTTOU,  # type:ignore
            signal.SIGTTIN,  # type:ignore
            signal.SIGTSTP,  # type:ignore
            signal.SIGCHLD,  # type:ignore
        ),
        globals(),
        "_block_when_giving",
    )

    if ON_CYGWIN or ON_MSYS:
        # on cygwin, signal.pthread_sigmask does not exist in Python, even
        # though pthread_sigmask is defined in the kernel.  thus, we use
        # ctypes to mimic the calls in the "normal" version below.
        LIBC.pthread_sigmask.restype = ctypes.c_int
        LIBC.pthread_sigmask.argtypes = [
            ctypes.c_int,
            ctypes.POINTER(ctypes.c_ulong),
            ctypes.POINTER(ctypes.c_ulong),
        ]
Exemplo n.º 2
0
Arquivo: vc.py Projeto: dyuri/xonsh
import os
import pathlib
import queue
import re
import subprocess
import sys
import threading

import xonsh.tools as xt
from xonsh.built_ins import XSH
from xonsh.lazyasd import LazyObject

RE_REMOVE_ANSI = LazyObject(
    lambda: re.compile(r"(?:\x1B[@-_]|[\x80-\x9F])[0-?]*[ -/]*[@-~]"),
    globals(),
    "RE_REMOVE_ANSI",
)


def _run_git_cmd(cmd):
    # create a safe detyped env dictionary and update with the additional git environment variables
    # when running git status commands we do not want to acquire locks running command like git status
    denv = dict(XSH.env.detype())
    denv.update({"GIT_OPTIONAL_LOCKS": "0"})
    return subprocess.check_output(cmd, env=denv, stderr=subprocess.DEVNULL)


def _get_git_branch(q):
    try:
        cmd = ["git", "rev-parse", "--abbrev-ref", "HEAD"]
Exemplo n.º 3
0
"""Tools for color handling in xonsh.

This includes Convert values between RGB hex codes and xterm-256
color codes. Parts of this file were originally forked from Micah Elliott
http://MicahElliott.com Copyright (C) 2011 Micah Elliott. All rights reserved.
WTFPL http://sam.zoy.org/wtfpl/
"""
import re
import math

from xonsh.lazyasd import lazyobject, LazyObject

RE_BACKGROUND = LazyObject(lambda: re.compile("(BG#|BGHEX|BACKGROUND)"),
                           globals(), "RE_BACKGROUND")


@lazyobject
def BASE_XONSH_COLORS():
    return {
        "BLACK": (0, 0, 0),
        "RED": (170, 0, 0),
        "GREEN": (0, 170, 0),
        "YELLOW": (170, 85, 0),
        "BLUE": (0, 0, 170),
        "PURPLE": (170, 0, 170),
        "CYAN": (0, 170, 170),
        "WHITE": (170, 170, 170),
        "INTENSE_BLACK": (85, 85, 85),
        "INTENSE_RED": (255, 85, 85),
        "INTENSE_GREEN": (85, 255, 85),
        "INTENSE_YELLOW": (255, 255, 85),
Exemplo n.º 4
0
from xonsh.platform import ON_POSIX, ON_WINDOWS
from xonsh.tools import (
    expand_path,
    globpath,
    XonshError,
    XonshCalledProcessError,
    print_color,
)
from xonsh.commands_cache import CommandsCache
from xonsh.events import events

import xonsh.procs.specs
import xonsh.completers.init

BUILTINS_LOADED = False
INSPECTOR = LazyObject(Inspector, globals(), "INSPECTOR")

warnings.filterwarnings("once", category=DeprecationWarning)


@lazyobject
def AT_EXIT_SIGNALS():
    sigs = (
        signal.SIGABRT,
        signal.SIGFPE,
        signal.SIGILL,
        signal.SIGSEGV,
        signal.SIGTERM,
    )
    if ON_POSIX:
        sigs += (signal.SIGTSTP, signal.SIGQUIT, signal.SIGHUP)
Exemplo n.º 5
0
)
from xonsh.tools import (
    suggest_commands,
    expand_path,
    globpath,
    XonshError,
    XonshCalledProcessError,
)
from xonsh.lazyimps import pty, termios
from xonsh.commands_cache import CommandsCache
from xonsh.events import events

import xonsh.completers.init

BUILTINS_LOADED = False
INSPECTOR = LazyObject(Inspector, globals(), "INSPECTOR")


@lazyobject
def AT_EXIT_SIGNALS():
    sigs = (
        signal.SIGABRT,
        signal.SIGFPE,
        signal.SIGILL,
        signal.SIGSEGV,
        signal.SIGTERM,
    )
    if ON_POSIX:
        sigs += (signal.SIGTSTP, signal.SIGQUIT, signal.SIGHUP)
    return sigs
Exemplo n.º 6
0
        target = styler
        styles = styler.styles

        def __new__(cls, *args, **kwargs):
            return cls.target

    return XonshStyleProxy


PTK_STYLE = LazyObject(
    lambda: {
        Token.Menu.Completions: 'bg:ansigray ansiblack',
        Token.Menu.Completions.Completion: '',
        Token.Menu.Completions.Completion.Current:
        'bg:ansibrightblack ansiwhite',
        Token.Scrollbar: 'bg:ansibrightblack',
        Token.Scrollbar.Button: 'bg:ansiblack',
        Token.Scrollbar.Arrow: 'bg:ansiblack ansiwhite bold',
        Token.AutoSuggestion: 'ansibrightblack',
        Token.Aborted: 'ansibrightblack',
    }, globals(), 'PTK_STYLE')

XONSH_BASE_STYLE = LazyObject(
    lambda: {
        Whitespace: 'ansigray',
        Comment: 'underline ansicyan',
        Comment.Preproc: 'underline ansiyellow',
        Keyword: 'bold ansigreen',
        Keyword.Pseudo: 'nobold',
        Keyword.Type: 'nobold ansired',
        Operator: 'ansibrightblack',
Exemplo n.º 7
0
    xcd = env.get('XONSH_CONFIG_DIR')
    xc = os.path.join(xcd, 'config.json')
    return xc


def default_xonshrc():
    """Creates a new instance of the default xonshrc tuple."""
    if ON_WINDOWS:
        dxrc = (os.path.join(os.environ['ALLUSERSPROFILE'], 'xonsh',
                             'xonshrc'), os.path.expanduser('~/.xonshrc'))
    else:
        dxrc = ('/etc/xonshrc', os.path.expanduser('~/.xonshrc'))
    return dxrc


DEFAULT_XONSHRC = LazyObject(default_xonshrc, globals(), 'DEFAULT_XONSHRC')


# Default values should generally be immutable, that way if a user wants
# to set them they have to do a copy and write them to the environment.
# try to keep this sorted.
@lazyobject
def DEFAULT_VALUES():
    dv = {
        'AUTO_CD': False,
        'AUTO_PUSHD': False,
        'AUTO_SUGGEST': True,
        'BASH_COMPLETIONS': BASH_COMPLETIONS_DEFAULT,
        'CASE_SENSITIVE_COMPLETIONS': ON_LINUX,
        'CDPATH': (),
        'COLOR_INPUT': True,
Exemplo n.º 8
0
"""Lazy imports that may apply across the xonsh package."""
import importlib
import os

from xonsh.lazyasd import LazyObject, lazyobject
from xonsh.platform import ON_DARWIN, ON_WINDOWS

pygments = LazyObject(lambda: importlib.import_module("pygments"), globals(),
                      "pygments")
pyghooks = LazyObject(lambda: importlib.import_module("xonsh.pyghooks"),
                      globals(), "pyghooks")


@lazyobject
def pty():
    if ON_WINDOWS:
        return
    else:
        return importlib.import_module("pty")


@lazyobject
def termios():
    if ON_WINDOWS:
        return
    else:
        return importlib.import_module("termios")


@lazyobject
def fcntl():
Exemplo n.º 9
0
import linecache
import importlib
import typing as tp

from xonsh.cli_utils import ArgParserAlias, Annotated, Arg
from xonsh.lazyasd import LazyObject
from xonsh.platform import HAS_PYGMENTS
from xonsh.tools import DefaultNotGiven, print_color, normabspath, to_bool
from xonsh.inspectors import find_file
from xonsh.lazyimps import pygments, pyghooks
import xonsh.procs.pipelines as xpp
import xonsh.prompt.cwd as prompt

terminal = LazyObject(
    lambda: importlib.import_module("pygments.formatters.terminal"),
    globals(),
    "terminal",
)


class TracerType(object):
    """Represents a xonsh tracer object, which keeps track of all tracing
    state. This is a singleton.
    """

    _inst: tp.Optional["TracerType"] = None
    valid_events = frozenset(["line", "call"])

    def __new__(cls, *args, **kwargs):
        if cls._inst is None:
            cls._inst = super(TracerType, cls).__new__(cls, *args, **kwargs)
Exemplo n.º 10
0
"""Tools for helping with ANSI color codes."""
import re
import string
import warnings

from xonsh.lazyasd import LazyObject, LazyDict

RE_BACKGROUND = LazyObject(lambda: re.compile('(bg|bg#|bghex|background)'),
                           globals(), 'RE_BACKGROUND')


def ansi_partial_color_format(template,
                              style='default',
                              cmap=None,
                              hide=False):
    """Formats a template string but only with respect to the colors.
    Another template string is returned, with the color values filled in.

    Parameters
    ----------
    template : str
        The template string, potentially with color names.
    style : str, optional
        Sytle name to look up color map from.
    cmap : dict, optional
        A color map to use, this will prevent the color map from being
        looked up via the style name.
    hide : bool, optional
        Whether to wrap the color codes in the \\001 and \\002 escape
        codes, so that the color codes are not counted against line
        length.
Exemplo n.º 11
0
import inspect
import itertools
import linecache
import collections

from xonsh.lazyasd import LazyObject
from xonsh.tokenize import detect_encoding
from xonsh.openpy import read_py_file
from xonsh.tools import (cast_unicode, safe_hasattr, indent, print_color,
                         format_color)
from xonsh.platform import HAS_PYGMENTS, PYTHON_VERSION_INFO
from xonsh.lazyimps import pygments, pyghooks
from xonsh.style_tools import partial_color_tokenize

# builtin docstrings to ignore
_func_call_docstring = LazyObject(lambda: types.FunctionType.__call__.__doc__,
                                  globals(), '_func_call_docstring')
_object_init_docstring = LazyObject(lambda: object.__init__.__doc__, globals(),
                                    '_object_init_docstring')
_builtin_type_docstrings = LazyObject(
    lambda: {
        t.__doc__
        for t in (types.ModuleType, types.MethodType, types.FunctionType)
    }, globals(), '_builtin_type_docstrings')

_builtin_func_type = LazyObject(lambda: type(all), globals(),
                                '_builtin_func_type')
# Bound methods have the same type as builtin functions
_builtin_meth_type = LazyObject(lambda: type(str.upper), globals(),
                                '_builtin_meth_type')

info_fields = LazyObject(
Exemplo n.º 12
0
        return importlib.import_module('pty')


@lazyobject
def termios():
    if ON_WINDOWS:
        return
    else:
        return importlib.import_module('termios')


# The following escape codes are xterm codes.
# See http://rtfm.etla.org/xterm/ctlseq.html for more.
MODE_NUMS = ('1049', '47', '1047')
START_ALTERNATE_MODE = LazyObject(
    lambda: frozenset('\x1b[?{0}h'.format(i).encode() for i in MODE_NUMS),
    globals(), 'START_ALTERNATE_MODE')
END_ALTERNATE_MODE = LazyObject(
    lambda: frozenset('\x1b[?{0}l'.format(i).encode() for i in MODE_NUMS),
    globals(), 'END_ALTERNATE_MODE')
ALTERNATE_MODE_FLAGS = LazyObject(
    lambda: tuple(START_ALTERNATE_MODE) + tuple(END_ALTERNATE_MODE), globals(),
    'ALTERNATE_MODE_FLAGS')
RE_HIDDEN_BYTES = LazyObject(lambda: re.compile(b'(\001.*?\002)'), globals(),
                             'RE_HIDDEN')
RE_COLOR = LazyObject(lambda: re.compile(b'\033\[\d+;?\d*m'), globals(),
                      'RE_COLOR')


def _findfirst(s, substrs):
    """Finds whichever of the given substrings occurs first in the given string
Exemplo n.º 13
0
    parser = argparse.ArgumentParser(prog="pushd")
    parser.add_argument('dir', nargs='?')
    parser.add_argument('-n',
                        dest='cd',
                        help='Suppresses the normal change of directory when'
                        ' adding directories to the stack, so that only the'
                        ' stack is manipulated.',
                        action='store_false')
    parser.add_argument('-q',
                        dest='quiet',
                        help='Do not call dirs, regardless of $PUSHD_SILENT',
                        action='store_true')
    return parser


pushd_parser = LazyObject(_pushd_parser, globals(), 'pushd_parser')
del _pushd_parser


def pushd(args, stdin=None):
    """xonsh command: pushd

    Adds a directory to the top of the directory stack, or rotates the stack,
    making the new top of the stack the current working directory.
    """
    global DIRSTACK

    try:
        args = pushd_parser.parse_args(args)
    except SystemExit:
        return None, None, 1
Exemplo n.º 14
0
    tokens = {
        'root': [(r'^(>>>|\.\.\.) ', Generic.Prompt),
                 (r'\n(>>>|\.\.\.)', Generic.Prompt),
                 (r'\n(?![>.][>.][>.] )([^\n]*)', Generic.Output),
                 (r'\n(?![>.][>.][>.] )(.*?)$', Generic.Output), inherit]
    }


#
# Colors and Styles
#

Color = Token.Color  # alias to new color token namespace

RE_BACKGROUND = LazyObject(lambda: re.compile('(BG#|BGHEX|BACKGROUND)'),
                           globals(), 'RE_BACKGROUND')


def norm_name(name):
    """Normalizes a color name."""
    return name.replace('#', 'HEX').replace('BGHEX', 'BACKGROUND_HEX')


def color_by_name(name, fg=None, bg=None):
    """Converts a color name to a color token, foreground name,
    and background name.  Will take into consideration current foreground
    and background colors, if provided.

    Parameters
    ----------
    name : str
Exemplo n.º 15
0
import itertools
import collections
from token import (
    AMPER, AMPEREQUAL, AT, CIRCUMFLEX, CIRCUMFLEXEQUAL, COLON, COMMA, DEDENT,
    DOT, DOUBLESLASH, DOUBLESLASHEQUAL, DOUBLESTAR, DOUBLESTAREQUAL, ENDMARKER,
    EQEQUAL, EQUAL, ERRORTOKEN, GREATER, GREATEREQUAL, INDENT, LBRACE,
    LEFTSHIFT, LEFTSHIFTEQUAL, LESS, LESSEQUAL, LPAR, LSQB, MINEQUAL, MINUS,
    NAME, NEWLINE, NOTEQUAL, NUMBER, N_TOKENS, OP, PERCENT, PERCENTEQUAL, PLUS,
    PLUSEQUAL, RBRACE, RIGHTSHIFT, RIGHTSHIFTEQUAL, RPAR, RSQB, SEMI, SLASH,
    SLASHEQUAL, STAR, STAREQUAL, STRING, TILDE, VBAR, VBAREQUAL, tok_name)

from xonsh.lazyasd import LazyObject
from xonsh.platform import PYTHON_VERSION_INFO

cookie_re = LazyObject(
    lambda: re.compile(r'^[ \t\f]*#.*coding[:=][ \t]*([-\w.]+)', re.ASCII),
    globals(), 'cookie_re')
blank_re = LazyObject(lambda: re.compile(br'^[ \t\f]*(?:[#\r\n]|$)', re.ASCII),
                      globals(), 'blank_re')

#
# token modifications
#
import token
__all__ = token.__all__ + [
    "COMMENT", "tokenize", "detect_encoding", "NL", "untokenize", "ENCODING",
    "TokenInfo", "TokenError", 'SEARCHPATH', 'ATDOLLAR', 'ATEQUAL',
    'DOLLARNAME', 'IOREDIRECT'
]
PY35 = PYTHON_VERSION_INFO >= (3, 5, 0)
if PY35:
Exemplo n.º 16
0
DEFAULT_STYLE_DICT = LazyObject(
    lambda: defaultdict(
        lambda: "",
        {
            Token: "",
            Token.Aborted: "ansibrightblack",
            Token.AutoSuggestion: "ansibrightblack",
            Token.Color.BACKGROUND_BLACK: "bg:ansiblack",
            Token.Color.BACKGROUND_BLUE: "bg:ansiblue",
            Token.Color.BACKGROUND_CYAN: "bg:ansicyan",
            Token.Color.BACKGROUND_GREEN: "bg:ansigreen",
            Token.Color.BACKGROUND_INTENSE_BLACK: "bg:ansibrightblack",
            Token.Color.BACKGROUND_INTENSE_BLUE: "bg:ansibrightblue",
            Token.Color.BACKGROUND_INTENSE_CYAN: "bg:ansibrightcyan",
            Token.Color.BACKGROUND_INTENSE_GREEN: "bg:ansibrightgreen",
            Token.Color.BACKGROUND_INTENSE_PURPLE: "bg:ansibrightmagenta",
            Token.Color.BACKGROUND_INTENSE_RED: "bg:ansibrightred",
            Token.Color.BACKGROUND_INTENSE_WHITE: "bg:ansiwhite",
            Token.Color.BACKGROUND_INTENSE_YELLOW: "bg:ansibrightyellow",
            Token.Color.BACKGROUND_PURPLE: "bg:ansimagenta",
            Token.Color.BACKGROUND_RED: "bg:ansired",
            Token.Color.BACKGROUND_WHITE: "bg:ansigray",
            Token.Color.BACKGROUND_YELLOW: "bg:ansiyellow",
            Token.Color.BLACK: "ansiblack",
            Token.Color.BLUE: "ansiblue",
            Token.Color.BOLD_BLACK: "bold ansiblack",
            Token.Color.BOLD_BLUE: "bold ansiblue",
            Token.Color.BOLD_CYAN: "bold ansicyan",
            Token.Color.BOLD_GREEN: "bold ansigreen",
            Token.Color.BOLD_INTENSE_BLACK: "bold ansibrightblack",
            Token.Color.BOLD_INTENSE_BLUE: "bold ansibrightblue",
            Token.Color.BOLD_INTENSE_CYAN: "bold ansibrightcyan",
            Token.Color.BOLD_INTENSE_GREEN: "bold ansibrightgreen",
            Token.Color.BOLD_INTENSE_PURPLE: "bold ansibrightmagenta",
            Token.Color.BOLD_INTENSE_RED: "bold ansibrightred",
            Token.Color.BOLD_INTENSE_WHITE: "bold ansiwhite",
            Token.Color.BOLD_INTENSE_YELLOW: "bold ansibrightyellow",
            Token.Color.BOLD_PURPLE: "bold ansimagenta",
            Token.Color.BOLD_RED: "bold ansired",
            Token.Color.BOLD_UNDERLINE_BLACK: "bold underline ansiblack",
            Token.Color.BOLD_UNDERLINE_BLUE: "bold underline ansiblue",
            Token.Color.BOLD_UNDERLINE_CYAN: "bold underline ansicyan",
            Token.Color.BOLD_UNDERLINE_GREEN: "bold underline ansigreen",
            Token.Color.BOLD_UNDERLINE_INTENSE_BLACK:
            "bold underline ansibrightblack",
            Token.Color.BOLD_UNDERLINE_INTENSE_BLUE:
            "bold underline ansibrightblue",
            Token.Color.BOLD_UNDERLINE_INTENSE_CYAN:
            "bold underline ansibrightcyan",
            Token.Color.BOLD_UNDERLINE_INTENSE_GREEN:
            "bold underline ansibrightgreen",
            Token.Color.BOLD_UNDERLINE_INTENSE_PURPLE:
            "bold underline ansibrightmagenta",
            Token.Color.BOLD_UNDERLINE_INTENSE_RED:
            "bold underline ansibrightred",
            Token.Color.BOLD_UNDERLINE_INTENSE_WHITE:
            "bold underline ansiwhite",
            Token.Color.BOLD_UNDERLINE_INTENSE_YELLOW:
            "bold underline ansibrightyellow",
            Token.Color.BOLD_UNDERLINE_PURPLE: "bold underline ansimagenta",
            Token.Color.BOLD_UNDERLINE_RED: "bold underline ansired",
            Token.Color.BOLD_UNDERLINE_WHITE: "bold underline ansigray",
            Token.Color.BOLD_UNDERLINE_YELLOW: "bold underline ansiyellow",
            Token.Color.BOLD_WHITE: "bold ansigray",
            Token.Color.BOLD_YELLOW: "bold ansiyellow",
            Token.Color.CYAN: "ansicyan",
            Token.Color.GREEN: "ansigreen",
            Token.Color.INTENSE_BLACK: "ansibrightblack",
            Token.Color.INTENSE_BLUE: "ansibrightblue",
            Token.Color.INTENSE_CYAN: "ansibrightcyan",
            Token.Color.INTENSE_GREEN: "ansibrightgreen",
            Token.Color.INTENSE_PURPLE: "ansibrightmagenta",
            Token.Color.INTENSE_RED: "ansibrightred",
            Token.Color.INTENSE_WHITE: "ansiwhite",
            Token.Color.INTENSE_YELLOW: "ansibrightyellow",
            Token.Color.RESET: "noinherit",
            Token.Color.PURPLE: "ansimagenta",
            Token.Color.RED: "ansired",
            Token.Color.UNDERLINE_BLACK: "underline ansiblack",
            Token.Color.UNDERLINE_BLUE: "underline ansiblue",
            Token.Color.UNDERLINE_CYAN: "underline ansicyan",
            Token.Color.UNDERLINE_GREEN: "underline ansigreen",
            Token.Color.UNDERLINE_INTENSE_BLACK: "underline ansibrightblack",
            Token.Color.UNDERLINE_INTENSE_BLUE: "underline ansibrightblue",
            Token.Color.UNDERLINE_INTENSE_CYAN: "underline ansibrightcyan",
            Token.Color.UNDERLINE_INTENSE_GREEN: "underline ansibrightgreen",
            Token.Color.UNDERLINE_INTENSE_PURPLE:
            "underline ansibrightmagenta",
            Token.Color.UNDERLINE_INTENSE_RED: "underline ansibrightred",
            Token.Color.UNDERLINE_INTENSE_WHITE: "underline ansiwhite",
            Token.Color.UNDERLINE_INTENSE_YELLOW: "underline ansibrightyellow",
            Token.Color.UNDERLINE_PURPLE: "underline ansimagenta",
            Token.Color.UNDERLINE_RED: "underline ansired",
            Token.Color.UNDERLINE_WHITE: "underline ansigray",
            Token.Color.UNDERLINE_YELLOW: "underline ansiyellow",
            Token.Color.WHITE: "ansigray",
            Token.Color.YELLOW: "ansiyellow",
            Token.Comment: "underline ansicyan",
            Token.Comment.Hashbang: "",
            Token.Comment.Multiline: "",
            Token.Comment.Preproc: "underline ansiyellow",
            Token.Comment.PreprocFile: "",
            Token.Comment.Single: "",
            Token.Comment.Special: "",
            Token.Error: "ansibrightred",
            Token.Escape: "",
            Token.Generic: "",
            Token.Generic.Deleted: "ansired",
            Token.Generic.Emph: "underline",
            Token.Generic.Error: "bold ansibrightred",
            Token.Generic.Heading: "bold ansiblue",
            Token.Generic.Inserted: "ansibrightgreen",
            Token.Generic.Output: "ansiblue",
            Token.Generic.Prompt: "bold ansiblue",
            Token.Generic.Strong: "",
            Token.Generic.Subheading: "bold ansimagenta",
            Token.Generic.Traceback: "ansiblue",
            Token.Keyword: "bold ansigreen",
            Token.Keyword.Constant: "",
            Token.Keyword.Declaration: "",
            Token.Keyword.Namespace: "",
            Token.Keyword.Pseudo: "nobold",
            Token.Keyword.Reserved: "",
            Token.Keyword.Type: "nobold ansired",
            Token.Literal: "",
            Token.Literal.Date: "",
            Token.Literal.Number: "ansibrightblack",
            Token.Literal.Number.Bin: "",
            Token.Literal.Number.Float: "",
            Token.Literal.Number.Hex: "",
            Token.Literal.Number.Integer: "",
            Token.Literal.Number.Integer.Long: "",
            Token.Literal.Number.Oct: "",
            Token.Literal.String: "ansibrightred",
            Token.Literal.String.Affix: "",
            Token.Literal.String.Backtick: "",
            Token.Literal.String.Char: "",
            Token.Literal.String.Delimiter: "",
            Token.Literal.String.Doc: "underline",
            Token.Literal.String.Double: "",
            Token.Literal.String.Escape: "bold ansiyellow",
            Token.Literal.String.Heredoc: "",
            Token.Literal.String.Interpol: "bold ansimagenta",
            Token.Literal.String.Other: "ansigreen",
            Token.Literal.String.Regex: "ansimagenta",
            Token.Literal.String.Single: "",
            Token.Literal.String.Symbol: "ansiyellow",
            Token.Menu.Completions: "bg:ansigray ansiblack",
            Token.Menu.Completions.Completion: "",
            Token.Menu.Completions.Completion.Current:
            "bg:ansibrightblack ansiwhite",
            Token.Name: "",
            Token.Name.Attribute: "ansibrightyellow",
            Token.Name.Builtin: "ansigreen",
            Token.Name.Builtin.Pseudo: "",
            Token.Name.Class: "bold ansibrightblue",
            Token.Name.Constant: "ansired",
            Token.Name.Decorator: "ansibrightmagenta",
            Token.Name.Entity: "bold ansigray",
            Token.Name.Exception: "bold ansibrightred",
            Token.Name.Function: "ansibrightblue",
            Token.Name.Function.Magic: "",
            Token.Name.Label: "ansibrightyellow",
            Token.Name.Namespace: "bold ansibrightblue",
            Token.Name.Other: "",
            Token.Name.Property: "",
            Token.Name.Tag: "bold ansigreen",
            Token.Name.Variable: "ansiblue",
            Token.Name.Variable.Class: "",
            Token.Name.Variable.Global: "",
            Token.Name.Variable.Instance: "",
            Token.Name.Variable.Magic: "",
            Token.Operator: "ansibrightblack",
            Token.Operator.Word: "bold ansimagenta",
            Token.Other: "",
            Token.Punctuation: "",
            Token.Scrollbar: "bg:ansibrightblack",
            Token.Scrollbar.Arrow: "bg:ansiblack ansiwhite bold",
            Token.Scrollbar.Button: "bg:ansiblack",
            Token.Text: "",
            Token.Text.Whitespace: "ansigray",
        },
    ),
    globals(),
    "DEFAULT_STYLE_DICT",
)
Exemplo n.º 17
0
import os
import re
import sys
import inspect
import linecache
import importlib
from functools import lru_cache
from argparse import ArgumentParser

from xonsh.lazyasd import LazyObject
from xonsh.platform import HAS_PYGMENTS
from xonsh.tools import DefaultNotGiven, print_color, normabspath, to_bool
from xonsh.inspectors import find_file, getouterframes
from xonsh.environ import _replace_home

pygments = LazyObject(lambda: importlib.import_module('pygments'), globals(),
                      'pygments')
terminal = LazyObject(
    lambda: importlib.import_module('pygments.formatters.terminal'), globals(),
    'terminal')
pyghooks = LazyObject(lambda: importlib.import_module('xonsh.pyghooks'),
                      globals(), 'pyghooks')


class TracerType(object):
    """Represents a xonsh tracer object, which keeps track of all tracing
    state. This is a singleton.
    """
    _inst = None
    valid_events = frozenset(['line', 'call'])

    def __new__(cls, *args, **kwargs):
Exemplo n.º 18
0
KNOWN_COLORS = LazyObject(lambda: frozenset([
    'BACKGROUND_BLACK',
    'BACKGROUND_BLUE',
    'BACKGROUND_CYAN',
    'BACKGROUND_GREEN',
    'BACKGROUND_INTENSE_BLACK',
    'BACKGROUND_INTENSE_BLUE',
    'BACKGROUND_INTENSE_CYAN',
    'BACKGROUND_INTENSE_GREEN',
    'BACKGROUND_INTENSE_PURPLE',
    'BACKGROUND_INTENSE_RED',
    'BACKGROUND_INTENSE_WHITE',
    'BACKGROUND_INTENSE_YELLOW',
    'BACKGROUND_PURPLE',
    'BACKGROUND_RED',
    'BACKGROUND_WHITE',
    'BACKGROUND_YELLOW',
    'BLACK',
    'BLUE',
    'BOLD_BLACK',
    'BOLD_BLUE',
    'BOLD_CYAN',
    'BOLD_GREEN',
    'BOLD_INTENSE_BLACK',
    'BOLD_INTENSE_BLUE',
    'BOLD_INTENSE_CYAN',
    'BOLD_INTENSE_GREEN',
    'BOLD_INTENSE_PURPLE',
    'BOLD_INTENSE_RED',
    'BOLD_INTENSE_WHITE',
    'BOLD_INTENSE_YELLOW',
    'BOLD_PURPLE',
    'BOLD_RED',
    'BOLD_UNDERLINE_BLACK',
    'BOLD_UNDERLINE_BLUE',
    'BOLD_UNDERLINE_CYAN',
    'BOLD_UNDERLINE_GREEN',
    'BOLD_UNDERLINE_INTENSE_BLACK',
    'BOLD_UNDERLINE_INTENSE_BLUE',
    'BOLD_UNDERLINE_INTENSE_CYAN',
    'BOLD_UNDERLINE_INTENSE_GREEN',
    'BOLD_UNDERLINE_INTENSE_PURPLE',
    'BOLD_UNDERLINE_INTENSE_RED',
    'BOLD_UNDERLINE_INTENSE_WHITE',
    'BOLD_UNDERLINE_INTENSE_YELLOW',
    'BOLD_UNDERLINE_PURPLE',
    'BOLD_UNDERLINE_RED',
    'BOLD_UNDERLINE_WHITE',
    'BOLD_UNDERLINE_YELLOW',
    'BOLD_WHITE',
    'BOLD_YELLOW',
    'CYAN',
    'GREEN',
    'INTENSE_BLACK',
    'INTENSE_BLUE',
    'INTENSE_CYAN',
    'INTENSE_GREEN',
    'INTENSE_PURPLE',
    'INTENSE_RED',
    'INTENSE_WHITE',
    'INTENSE_YELLOW',
    'NO_COLOR',
    'PURPLE',
    'RED',
    'UNDERLINE_BLACK',
    'UNDERLINE_BLUE',
    'UNDERLINE_CYAN',
    'UNDERLINE_GREEN',
    'UNDERLINE_INTENSE_BLACK',
    'UNDERLINE_INTENSE_BLUE',
    'UNDERLINE_INTENSE_CYAN',
    'UNDERLINE_INTENSE_GREEN',
    'UNDERLINE_INTENSE_PURPLE',
    'UNDERLINE_INTENSE_RED',
    'UNDERLINE_INTENSE_WHITE',
    'UNDERLINE_INTENSE_YELLOW',
    'UNDERLINE_PURPLE',
    'UNDERLINE_RED',
    'UNDERLINE_WHITE',
    'UNDERLINE_YELLOW',
    'WHITE',
    'YELLOW',
    ]), globals(), 'KNOWN_COLORS')
Exemplo n.º 19
0
    """
    if dtp is None:
        dtp = _deferred_type_pprinters
    key = (type_module, type_name)
    oldfunc = dtp.get(key, None)
    if func is not None:
        # To support easy restoration of old pprinters, we need to ignore Nones.
        dtp[key] = func
    return oldfunc


#: printers for the default singletons
_singleton_pprinters = LazyObject(
    lambda: dict.fromkeys(
        map(id, [None, True, False, Ellipsis, NotImplemented]), _repr_pprint
    ),
    globals(),
    "_singleton_pprinters",
)


def _defaultdict_pprint(obj, p, cycle):
    name = obj.__class__.__name__
    with p.group(len(name) + 1, name + "(", ")"):
        if cycle:
            p.text("...")
        else:
            p.pretty(obj.default_factory)
            p.text(",")
            p.breakable()
            p.pretty(dict(obj))
Exemplo n.º 20
0
import importlib.util

from xonsh.lazyasd import LazyObject, LazyBool


def _distro():
    try:
        import distro as d
    except ImportError:
        d = None
    except:
        raise
    return d


distro = LazyObject(_distro, globals(), 'distro')
del _distro

# do not import any xonsh-modules here to avoid circular dependencies

#
# OS
#
ON_DARWIN = LazyBool(lambda: platform.system() == 'Darwin', globals(),
                     'ON_DARWIN')
""" ``True`` if executed on a Darwin platform, else ``False``. """
ON_LINUX = LazyBool(lambda: platform.system() == 'Linux', globals(),
                    'ON_LINUX')
""" ``True`` if executed on a Linux platform, else ``False``. """
ON_WINDOWS = LazyBool(lambda: platform.system() == 'Windows', globals(),
                      'ON_WINDOWS')
Exemplo n.º 21
0
from xonsh.jobs import add_job
from xonsh.platform import ON_POSIX, ON_WINDOWS
from xonsh.proc import (PopenThread, ProcProxyThread, ProcProxy,
                        ConsoleParallelReader, pause_call_resume,
                        CommandPipeline, HiddenCommandPipeline,
                        STDOUT_CAPTURE_KINDS)
from xonsh.tools import (suggest_commands, expandvars, globpath, XonshError,
                         XonshCalledProcessError, XonshBlockError)
from xonsh.lazyimps import pty
from xonsh.commands_cache import CommandsCache
from xonsh.events import events

import xonsh.completers.init

BUILTINS_LOADED = False
INSPECTOR = LazyObject(Inspector, globals(), 'INSPECTOR')


@lazyobject
def AT_EXIT_SIGNALS():
    sigs = (signal.SIGABRT, signal.SIGFPE, signal.SIGILL, signal.SIGSEGV,
            signal.SIGTERM)
    if ON_POSIX:
        sigs += (signal.SIGTSTP, signal.SIGQUIT, signal.SIGHUP)
    return sigs


def resetting_signal_handle(sig, f):
    """Sets a new signal handle that will automatically restore the old value
    once the new handle is finished.
    """
Exemplo n.º 22
0
        highlight_color = styler.highlight_color
        background_color = styler.background_color

        def __new__(cls, *args, **kwargs):
            return cls.target

    return XonshStyleProxy


PTK_STYLE = LazyObject(
    lambda: {
        Token.Menu.Completions: "bg:ansigray ansiblack",
        Token.Menu.Completions.Completion: "",
        Token.Menu.Completions.Completion.Current: "bg:ansibrightblack ansiwhite",
        Token.Scrollbar: "bg:ansibrightblack",
        Token.Scrollbar.Button: "bg:ansiblack",
        Token.Scrollbar.Arrow: "bg:ansiblack ansiwhite bold",
        Token.AutoSuggestion: "ansibrightblack",
        Token.Aborted: "ansibrightblack",
    },
    globals(),
    "PTK_STYLE",
)


XONSH_BASE_STYLE = LazyObject(
    lambda: {
        Whitespace: "ansigray",
        Comment: "underline ansicyan",
        Comment.Preproc: "underline ansiyellow",
        Keyword: "bold ansigreen",
        Keyword.Pseudo: "nobold",
Exemplo n.º 23
0
        styles = styler.styles

        def __new__(cls, *args, **kwargs):
            return cls.target

    return XonshStyleProxy


PTK_STYLE = LazyObject(
    lambda: {
        Token.Menu.Completions: "bg:ansigray ansiblack",
        Token.Menu.Completions.Completion: "",
        Token.Menu.Completions.Completion.Current:
        "bg:ansibrightblack ansiwhite",
        Token.Scrollbar: "bg:ansibrightblack",
        Token.Scrollbar.Button: "bg:ansiblack",
        Token.Scrollbar.Arrow: "bg:ansiblack ansiwhite bold",
        Token.AutoSuggestion: "ansibrightblack",
        Token.Aborted: "ansibrightblack",
    },
    globals(),
    "PTK_STYLE",
)

XONSH_BASE_STYLE = LazyObject(
    lambda: {
        Whitespace: "ansigray",
        Comment: "underline ansicyan",
        Comment.Preproc: "underline ansiyellow",
        Keyword: "bold ansigreen",
        Keyword.Pseudo: "nobold",
Exemplo n.º 24
0
import sys
import types
import inspect
import itertools
import linecache

from xonsh.lazyasd import LazyObject
from xonsh.tokenize import detect_encoding
from xonsh.openpy import read_py_file
from xonsh.tools import cast_unicode, safe_hasattr, indent, print_color, format_color
from xonsh.platform import HAS_PYGMENTS
from xonsh.lazyimps import pygments, pyghooks
from xonsh.style_tools import partial_color_tokenize

# builtin docstrings to ignore
_func_call_docstring = LazyObject(lambda: types.FunctionType.__call__.__doc__,
                                  globals(), "_func_call_docstring")
_object_init_docstring = LazyObject(lambda: object.__init__.__doc__, globals(),
                                    "_object_init_docstring")

_builtin_type_docstrings = LazyObject(
    lambda: {
        inspect.getdoc(t)
        for t in
        (types.ModuleType, types.MethodType, types.FunctionType, property)
    },
    globals(),
    "_builtin_type_docstrings",
)

_builtin_func_type = LazyObject(lambda: type(all), globals(),
                                "_builtin_func_type")
Exemplo n.º 25
0
# -*- coding: utf-8 -*-
"""Job control for the xonsh shell."""
import os
import sys
import time
import ctypes
import signal
import builtins
import subprocess
import collections

from xonsh.lazyasd import LazyObject
from xonsh.platform import FD_STDERR, ON_DARWIN, ON_WINDOWS, ON_CYGWIN, ON_MSYS, LIBC
from xonsh.tools import unthreadable

tasks = LazyObject(collections.deque, globals(), "tasks")
# Track time stamp of last exit command, so that two consecutive attempts to
# exit can kill all jobs and exit.
_last_exit_time = None

if ON_DARWIN:

    def _send_signal(job, signal):
        # On OS X, os.killpg() may cause PermissionError when there are
        # any zombie processes in the process group.
        # See github issue #1012 for details
        for pid in job["pids"]:
            if pid is None:  # the pid of an aliased proc is None
                continue
            try:
                os.kill(pid, signal)
Exemplo n.º 26
0
        if isinstance(comp,
                      xct.RichCompletion) and comp.prefix_len is not None:
            if comp.prefix_len:
                comp = prefix[:-comp.prefix_len] + comp
            else:
                comp = prefix + comp
        elif chopped:
            comp = chopped + comp
        rendered_completions.append(comp)

    return rendered_completions


DEDENT_TOKENS = LazyObject(
    lambda: frozenset(["raise", "return", "pass", "break", "continue"]),
    globals(),
    "DEDENT_TOKENS",
)


class ReadlineShell(BaseShell, cmd.Cmd):
    """The readline based xonsh shell."""
    def __init__(self, completekey="tab", stdin=None, stdout=None, **kwargs):
        BaseShell.__init__(self, **kwargs)
        # super() doesn't pass the stdin/stdout to Cmd's init method correctly.
        # so calling it explicitly
        cmd.Cmd.__init__(self,
                         completekey=completekey,
                         stdin=stdin,
                         stdout=stdout)
Exemplo n.º 27
0
"""Lazy imports that may apply across the xonsh package."""
import importlib

from xonsh.platform import ON_WINDOWS
from xonsh.lazyasd import LazyObject, lazyobject

pygments = LazyObject(lambda: importlib.import_module('pygments'), globals(),
                      'pygments')
pyghooks = LazyObject(lambda: importlib.import_module('xonsh.pyghooks'),
                      globals(), 'pyghooks')


@lazyobject
def pty():
    if ON_WINDOWS:
        return
    else:
        return importlib.import_module('pty')


@lazyobject
def termios():
    if ON_WINDOWS:
        return
    else:
        return importlib.import_module('termios')


@lazyobject
def fcntl():
    if ON_WINDOWS:
Exemplo n.º 28
0
import builtins
import importlib
import threading
import collections

from xonsh.lazyjson import LazyJSON
from xonsh.lazyasd import LazyObject
from xonsh.base_shell import BaseShell
from xonsh.ansi_colors import ansi_partial_color_format, ansi_color_style_names, ansi_color_style
from xonsh.environ import partial_format_prompt, multiline_prompt
from xonsh.tools import print_exception
from xonsh.platform import ON_WINDOWS, ON_CYGWIN, ON_DARWIN
from xonsh.lazyimps import pygments, pyghooks

terminal256 = LazyObject(
    lambda: importlib.import_module('pygments.formatters.terminal256'),
    globals(), 'terminal')

readline = None
RL_COMPLETION_SUPPRESS_APPEND = RL_LIB = RL_STATE = None
RL_CAN_RESIZE = False
RL_DONE = None
RL_VARIABLE_VALUE = None
_RL_STATE_DONE = 0x1000000
_RL_STATE_ISEARCH = 0x0000080

_RL_PREV_CASE_SENSITIVE_COMPLETIONS = 'to-be-set'


def setup_readline():
    """Sets up the readline module and completion suppression, if available."""
Exemplo n.º 29
0

Token = _TokenType()

events.transmogrify('on_ptk_create', 'LoadEvent')
events.doc('on_ptk_create', """
on_ptk_create(prompter: Prompter, history: PromptToolkitHistory, completer: PromptToolkitCompleter, bindings: KeyBindingManager) ->

Fired after prompt toolkit has been initialized
""")

# Convert new ansicolor names to names
# understood by PTK1
DEFAULT_STYLE_DICT = LazyObject(
    lambda: ansicolors_to_ptk1_names(_DEFAULT_STYLE_DICT),
    globals(),
    'DEFAULT_STYLE_DICT'
)


class PromptToolkitShell(BaseShell):
    """The xonsh shell."""

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        if ON_WINDOWS:
            winutils.enable_virtual_terminal_processing()
        self._first_prompt = True
        self.prompter = Prompter()
        self.history = PromptToolkitHistory()
        self.pt_completer = PromptToolkitCompleter(self.completer, self.ctx, self)
Exemplo n.º 30
0
    SLASHEQUAL,
    STAR,
    STAREQUAL,
    STRING,
    TILDE,
    VBAR,
    VBAREQUAL,
    tok_name,
)

from xonsh.lazyasd import LazyObject
from xonsh.platform import PYTHON_VERSION_INFO

cookie_re = LazyObject(
    lambda: re.compile(r"^[ \t\f]*#.*coding[:=][ \t]*([-\w.]+)", re.ASCII),
    globals(),
    "cookie_re",
)
blank_re = LazyObject(lambda: re.compile(br"^[ \t\f]*(?:[#\r\n]|$)", re.ASCII),
                      globals(), "blank_re")

#
# token modifications
#
tok_name = tok_name.copy()
__all__ = token.__all__ + [
    "COMMENT",
    "tokenize",
    "detect_encoding",
    "NL",
    "untokenize",