Beispiel #1
0
    def __init__(self, *args, **kwargs):
        """EQL Shell."""
        super(EqlShell, self).__init__(*args, **kwargs)
        self.tty = callmethod(self.stdout, "isatty", False)
        self.multiline = False
        self.stop = False
        self.last_results = []
        self.columns = []
        self.input_file = None
        self.empty_count = 0
        self.prompt_session = False
        self.config = None
        self.last_display_fn = None
        self.display_fn = None
        self.last_query = None

        if prompt_toolkit and self.tty:
            self.tk_lexer = None
            if EqlLexer:
                self.tk_lexer = PygmentsLexer(EqlLexer)

            self.tk_completer = ShellCompleter(self)
            self.tk_history = FileHistory(self.history_file + ".tk")
            style_cls = None

            # switch to something more friendly
            if get_style_by_name:
                style = get_style_by_name("rrt" if sys.platform.startswith("win") else "monokai")
                if style:
                    style_cls = style_from_pygments_cls(style)

            self.default_style = style_cls
            self.prompt_session = PromptSession(style=style_cls, history=self.tk_history,
                                                completer=self.tk_completer)
Beispiel #2
0
    def _init_prompt(self):
        if self.batch_mode:
            return None
        else:
            try:
                from prompt_toolkit.clipboard.pyperclip import PyperclipClipboard
                clipboard = PyperclipClipboard()
            except ImportError:
                clipboard = None

            return PromptSession(
                style=style_from_pygments_cls(PeekStyle),
                lexer=PygmentsLexer(PeekLexer),
                auto_suggest=AutoSuggestFromHistory(),
                completer=self.completer,
                history=self.history,
                multiline=True,
                key_bindings=key_bindings(self),
                enable_open_in_editor=True,
                enable_system_prompt=False,
                enable_suspend=True,
                search_ignore_case=True,
                clipboard=clipboard,
                mouse_support=Condition(self._should_support_mouse),
                swap_light_and_dark_colors=self.config.as_bool('swap_colour'),
                input_processors=[
                    HighlightMatchingBracketProcessor(chars="[](){}"),
                ],
            )
Beispiel #3
0
    def style_factory(self, style_name):
        """Retrieve the specified pygments style.

        If the specified style is not found, the vim style is returned.

        :type style_name: str
        :param style_name: The pygments style name.

        :rtype: :class:`pygments.style.StyleMeta`
        :return: Pygments style info.
        """
        # try:
        #     style = get_style_by_name(style_name)
        # except ClassNotFound:
        #     style = get_style_by_name('vim')
        #
        # # Create a style dictionary.
        # styles = {}
        # styles.update(style.styles)
        # styles.update(default_style_extensions)
        # t = Token
        # styles.update({
        #     t.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000',
        #     t.Menu.Completions.Completion: 'bg:#008888 #ffffff',
        #     t.Menu.Completions.Meta.Current: 'bg:#00aaaa #000000',
        #     t.Menu.Completions.Meta: 'bg:#00aaaa #ffffff',
        #     t.Scrollbar.Button: 'bg:#003333',
        #     t.Scrollbar: 'bg:#00aaaa',
        #     t.Toolbar: 'bg:#222222 #cccccc',
        #     t.Toolbar.Off: 'bg:#222222 #696969',
        #     t.Toolbar.On: 'bg:#222222 #ffffff',
        #     t.Toolbar.Search: 'noinherit bold',
        #     t.Toolbar.Search.Text: 'nobold',
        #     t.Toolbar.System: 'noinherit bold',
        #     t.Toolbar.Arg: 'noinherit bold',
        #     t.Toolbar.Arg.Text: 'nobold'
        # })

        #return style_from_dict(styles)
        return merge_styles([
            style_from_pygments_cls(DefaultStyle),
            Style.from_dict({
                # User input (default text).
                # '': '#ff0066',

                # Prompt.
                # 'username': '******',
                # 'at': '#00aa00',
                # 'colon': '#0000aa',
                # 'pound': '#00aa00',
                # 'host': '#00ffff bg:#444400',
                # 'path': 'ansicyan underline',
                # 'prompt': '#0000aa bold',
                # 'state': '#00aa00 bold',
                # 'danger': '#aa0000 bold',
                'prompt': 'fg:ansiblue bold',
                'state': 'fg:ansigreen bold',
                'danger': 'fg:ansired bold'
            }),
        ])
Beispiel #4
0
def patched_style() -> Style:
    ''' Our patched solarized style.
    '''  # pylint: disable=protected-access
    style = style_from_pygments_cls(SolarizedDarkStyle)
    for i in range(len(style._style_rules)):
        tpl = style._style_rules[i]
        if tpl[0] == 'pygments.generic.heading':
            style._style_rules[i] = (tpl[0], 'nobold #b58900')
        if tpl[0] == 'pygments.generic.subheading':
            style._style_rules[i] = (tpl[0], 'nobold #d33682')

    style._style_rules += [
        ('pygments.commit', 'noinherit'),
        ('pygments.commit.author', 'ansigreen'),
        ('pygments.commit.authordate', 'ansiblue'),
        ('pygments.commit.id', 'ansimagenta'),
        ('pygments.commit.committer', 'italic ansigreen'),
        ('pygments.commit.commitdate', 'italic ansiblue'),
        ('pygments.commit.diffsummary', 'ansiyellow'),
        ('pygments.commit.filename', 'ansiblue'),
        ('pygments.commit.refs', 'ansiyellow'),
        ('pygments.commit.modules', 'ansiyellow'),
        ('pygments.commit.subject', 'bold'),
        ('pygments.commit.diffstart', 'bold'),
    ]
    return style
Beispiel #5
0
    def app_initialize(self, mp):
        if sys.platform.startswith('win'):
            encoding = api.encoding()
            callbacks.ENCODING = encoding

        if not interface.get_option("rtichoke.suppress_reticulate_message", False):
            interface.reticulate_set_message(RETICULATE_MESSAGE)

        if interface.get_option("rtichoke.editing_mode", "emacs") in ["vim", "vi"]:
            mp.app.editing_mode = EditingMode.VI
        else:
            mp.app.editing_mode = EditingMode.EMACS

        color_scheme = interface.get_option("rtichoke.color_scheme", "native")
        mp.style = style_from_pygments_cls(get_style_by_name(color_scheme))

        mp.app.auto_match = interface.get_option("rtichoke.auto_match", False)
        mp.app.auto_indentation = interface.get_option("rtichoke.auto_indentation", True)
        mp.app.tab_size = int(interface.get_option("rtichoke.tab_size", 4))
        mp.complete_while_typing = interface.get_option("rtichoke.complete_while_typing", True)
        mp.history_search_no_duplicates = interface.get_option("rtichoke.history_search_no_duplicates", False)
        mp.insert_new_line = interface.get_option("rtichoke.insert_new_line", True)

        prompt = interface.get_option("rtichoke.prompt", None)
        if prompt:
            mp.set_prompt_mode_message("r", ANSI(prompt))
        else:
            sys_prompt = interface.get_option("prompt")
            if sys_prompt == "> ":
                prompt = PROMPT
            else:
                prompt = sys_prompt

        mp.default_prompt = prompt
        mp.set_prompt_mode_message("r", ANSI(prompt))
        interface.set_option("prompt", prompt)

        shell_prompt = interface.get_option("rtichoke.shell_prompt", SHELL_PROMPT)
        mp.set_prompt_mode_message("shell", ANSI(shell_prompt))

        mp.browse_prompt = interface.get_option("rtichoke.browse_prompt", BROWSE_PROMPT)

        set_width_on_resize = interface.get_option("setWidthOnResize", True)
        mp.auto_width = interface.get_option("rtichoke.auto_width", set_width_on_resize)

        if mp.auto_width:
            interface.set_option("width", mp.app.output.get_size().columns)

        # necessary on windows
        interface.set_option("menu.graphics", False)

        # enables completion of installed package names
        if interface.rcopy(interface.reval("rc.settings('ipck')")) is None:
            interface.reval("rc.settings(ipck = TRUE)")

        interface.installed_packages()

        # print welcome message
        sys.stdout.write(interface.greeting())
Beispiel #6
0
 def prompt_user(self, prompt_text='» '): # pragma: no cover
     lexer = self.get_lexer()
     pygments_lexer = PygmentsLexer(lexer.__class__) if lexer else None
     # ^^ we have to wrap lexer in PygmentsLexer of prompt toolkit
     self.last_run['user_code'] = prompt(
         prompt_text,
         default = self.code,
         lexer = pygments_lexer,
         style = style_from_pygments_cls(self.HighlightStyle),
         )
    def __init__(self, uri=None, **settings):
        self.output_file = settings.pop("file", None)
        verbose = settings.pop("verbose", False)
        connection_data = get_connection_data(uri, **settings)
        try:
            self.graph = Graph(uri, **settings)
        except ServiceUnavailable as error:
            raise ConsoleError("Could not connect to {} -- {}".format(
                connection_data["uri"], error))
        try:
            makedirs(HISTORY_FILE_DIR)
        except OSError:
            pass
        self.history = FileHistory(path_join(HISTORY_FILE_DIR, HISTORY_FILE))
        self.prompt_args = {
            "history":
            self.history,
            "lexer":
            PygmentsLexer(CypherLexer),
            "style":
            merge_styles([
                style_from_pygments_cls(NativeStyle),
                style_from_pygments_dict({
                    Token.Prompt:
                    "#ansi{}".format(self.prompt_colour.replace(
                        "cyan", "teal")),
                    Token.TxCounter:
                    "#ansi{} bold".format(
                        self.tx_colour.replace("cyan", "teal")),
                })
            ])
        }
        self.lexer = CypherLexer()
        self.result_writer = Table.write
        if verbose:
            from neobolt.diagnostics import watch
            self.watcher = watch("neo4j.%s" % connection_data["scheme"])

        self.commands = {
            "//": self.set_multi_line,
            "/e": self.edit,
            "/?": self.help,
            "/h": self.help,
            "/help": self.help,
            "/x": self.exit,
            "/exit": self.exit,
            "/play": self.play,
            "/csv": self.set_csv_result_writer,
            "/table": self.set_tabular_result_writer,
            "/tsv": self.set_tsv_result_writer,
            "/config": self.config,
            "/kernel": self.kernel,
        }
        self.tx = None
        self.tx_counter = 0
Beispiel #8
0
def load_settings(session):
    if roption("radian.editing_mode", "emacs") in ["vim", "vi"]:
        session.app.editing_mode = EditingMode.VI
    else:
        session.app.editing_mode = EditingMode.EMACS

    color_scheme = roption("radian.color_scheme", "native")
    session.style = style_from_pygments_cls(get_style_by_name(color_scheme))

    session.auto_match = roption("radian.auto_match", False)
    session.auto_indentation = roption("radian.auto_indentation", True)
    session.tab_size = int(roption("radian.tab_size", 4))
    session.complete_while_typing = roption("radian.complete_while_typing",
                                            True)
    session.completion_timeout = roption("radian.completion_timeout", 0.05)

    session.history_search_no_duplicates = roption(
        "radian.history_search_no_duplicates", False)
    session.insert_new_line = roption("radian.insert_new_line", True)
    session.indent_lines = roption("radian.indent_lines", True)

    prompt = roption("radian.prompt", None)
    if not prompt:
        sys_prompt = roption("prompt")
        if sys_prompt == "> ":
            prompt = PROMPT
        else:
            prompt = sys_prompt

    session.default_prompt = prompt
    setoption("prompt", prompt)

    shell_prompt = roption("radian.shell_prompt", SHELL_PROMPT)
    session.shell_prompt = shell_prompt

    browse_prompt = roption("radian.browse_prompt", BROWSE_PROMPT)
    session.browse_prompt = browse_prompt

    set_width_on_resize = roption("setWidthOnResize", True)
    session.auto_width = roption("radian.auto_width", set_width_on_resize)
    output_width = session.app.output.get_size().columns
    if output_width and session.auto_width:
        setoption("width", output_width)

    # necessary on windows
    setoption("menu.graphics", False)

    # enables completion of installed package names
    if rcopy(reval("rc.settings('ipck')")) is None:
        reval("rc.settings(ipck = TRUE)")

    # backup the updated settings
    session._backup_settings()
Beispiel #9
0
def main():
    """The main function."""
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument('--config',
                    default=str(Path.home() / '.philipshue.ini'),
                    help='the config file location')
    args = ap.parse_args()

    while True:
        try:
            cp = configparser.ConfigParser()
            cp.read(args.config)
            cf = cp['DEFAULT']
            bridge_location = cf['bridge_location']
            bridge_username = cf['bridge_username']
        except KeyError:
            setup(args.config)
            continue
        break

    print(f'Connecting to {bridge_location}...')
    try:
        bridge = qhue.Bridge(bridge_location, bridge_username)
        num_lights = len(bridge.lights())
        print(f'Connected to {bridge_location}. {num_lights} lights found.')
    except requests.ConnectionError as err:
        print(f'{sgr(1, 31)}{err.__class__.__name__}{sgr(0)}: {err}')
        sys.exit(1)

    session = PromptSession(
        '> ',
        lexer=PygmentsLexer(Python3Lexer),
        style=style_from_pygments_cls(PYGMENTS_STYLE),
        auto_suggest=AutoSuggestFromHistory(),
        input_processors=[HighlightMatchingBracketProcessor('()[]{}')],
        history=FileHistory(Path.home() / '.philipshue.hist'))
    while True:
        try:
            cmd = session.prompt()
            start = time.perf_counter()
            out = exec_cmd(cmd, bridge=bridge)
            time_taken = time.perf_counter() - start
            prettyprinter.cpprint(out)
            print(f'Time taken: {sgr(1, 34)}{time_taken*1000:.3f} ms{sgr(0)}')
        except KeyboardInterrupt:
            pass
        except EOFError:
            break
        except requests.ConnectionError as err:
            print(f'{sgr(1, 31)}{err.__class__.__name__}{sgr(0)}: {err}')
            sys.exit(1)
        except Exception as err:
            print(f'{sgr(1, 31)}{err.__class__.__name__}{sgr(0)}: {err}')
Beispiel #10
0
    def _next_style(self):
        styles = list(get_all_styles())
        for i in range(0, len(styles)):
            if styles[i] == self.style_name:
                if i + 1 == len(styles):
                    self.style_name = styles[0]
                else:
                    self.style_name = styles[i + 1]
                    break

        self.style = style_from_pygments_cls(get_style_by_name(
            self.style_name))
        self.app.style = self.style
        self.console.update_info()
        self.app.invalidate()
Beispiel #11
0
        def do_style(self, line):
            """Change the color theme used for syntax highlighting."""
            styles = set(get_all_styles())
            if "reset" in line.split():
                self.prompt_session.style = self.default_style
                return
            elif line in styles:
                pygments_style_cls = get_style_by_name(line)
                self.prompt_session.style = style_from_pygments_cls(pygments_style_cls)
                return
            elif line:
                print_formatted_text("Invalid style\n")

            # Print the list of available styles
            self.print_topics("Available styles", list(sorted(styles)), 15, 80)
Beispiel #12
0
    def __init__(self, project=None, instance=None, database=None, credentials=None, with_pager=False,
                 inp=None, output=None):
        # setup environment variables
        # less option for pager
        if not os.environ.get(config.EnvironmentVariables.LESS):
            os.environ[config.EnvironmentVariables.LESS] = config.Constants.LESS_FLAG
        self.with_pager = with_pager
        self.logger = logging.getLogger('spanner-cli')
        self.logger.debug("Staring spanner-cli project=%s, instance=%s, database=%s", project, instance, database)
        self.project = project
        with warnings.catch_warnings(record=True) as warns:
            warnings.simplefilter("always")
            self.client = spanner.Client(
                project=self.project,
                credentials=credentials,
                client_info=client_info.ClientInfo(user_agent=__name__),
            )
            if len(warns) > 0:
                for w in warns:
                    self.logger.debug(w)
                    click.echo(message=w.message, err=True, nl=True)

        self.instance = self.client.instance(instance)
        self.database = self.instance.database(database)
        self.prompt_message = self.get_prompt_message()
        self.completer = SQLCompleter()
        self.open_history_file()
        self.rehash()
        self.session = PromptSession(
            message=self.prompt_message,
            lexer=PygmentsLexer(lexer.SpannerLexer),
            completer=DynamicCompleter(lambda: self.completer),
            style=style_from_pygments_cls(get_style_by_name(config.get_pygment_style())),
            history=self.history,
            auto_suggest=AutoSuggestFromHistory(),
            input_processors=[ConditionalProcessor(
                processor=HighlightMatchingBracketProcessor(
                    chars='[](){}'),
                filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()  # pylint: disable=invalid-unary-operand-type
            )],
            input=inp,
            output=output,
        )

        self.formatter = tabular_output.TabularOutputFormatter('ascii')
Beispiel #13
0
 def run(self):
     repl_lines = []
     prolog_lines = []
     self.in_prolog = False
     encloser_counts = [0] * len(self.enclosers)
     while True:
         try:
             line = prompt('> ',
                           lexer=self.lexer,
                           style=style_from_pygments_cls(
                               get_style_by_name('native')),
                           history=self.history)
         except:
             break
         stat = self.process_line(line.rstrip(), repl_lines, prolog_lines,
                                  encloser_counts)
         if not stat:
             break
Beispiel #14
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self._output_style = None
     self._session = pt.PromptSession(
         message=self.prompt_text,
         history=FileHistory(cachedir / 'history.txt'),
         editing_mode=getattr(pt.enums.EditingMode,
                              self.options.edit_mode.upper()),
         auto_suggest=AutoSuggestFromHistory(),
         enable_open_in_editor=True,
         completer=self._create_completer(),
         multiline=self.options.multiline,
         style=style_from_pygments_cls(get_style_by_name(
             self.options.style)),
         prompt_continuation=self._prompt_continuation,
         lexer=pt.lexers.PygmentsLexer(RollitLexer, sync_from_start=True),
         search_ignore_case=True,
     )
Beispiel #15
0
    def read(self):
        prompt_args = {
            "history":
            self.history,
            "lexer":
            PygmentsLexer(CypherLexer),
            "style":
            merge_styles([
                style_from_pygments_cls(NativeStyle),
                style_from_pygments_dict({
                    Token.Prompt.User: "******",
                    Token.Prompt.At: "#ansigreen",
                    Token.Prompt.Host: "#ansigreen",
                    Token.Prompt.Slash: "#ansigreen",
                    Token.Prompt.Graph: "#ansiblue",
                    Token.Prompt.QID: "#ansiyellow",
                    Token.Prompt.Arrow: "#808080",
                })
            ])
        }

        if self.multi_line:
            self.multi_line = False
            return prompt(u"", multiline=True, **prompt_args)

        def get_prompt_tokens():
            graph_name = "~" if self.graph_name is None else self.graph_name
            tokens = [
                ("class:pygments.prompt.user", self.profile.user),
                ("class:pygments.prompt.at", "@"),
                ("class:pygments.prompt.host", self.profile.host),
                ("class:pygments.prompt.slash", "/"),
                ("class:pygments.prompt.graph", graph_name),
            ]
            if self.tx is None:
                tokens.append(("class:pygments.prompt.arrow", " -> "))
            else:
                tokens.append(("class:pygments.prompt.arrow", " "))
                tokens.append(("class:pygments.prompt.qid", str(self.qid)))
                tokens.append(("class:pygments.prompt.arrow", "> "))
            return tokens

        return prompt(get_prompt_tokens, **prompt_args)
Beispiel #16
0
    def setup_prompt(self):
        self.style = merge_styles([
            style_from_pygments_cls(RainbowDashStyle),

            Style.from_dict({
                'username': '******',
                'punctuation': '#090908',
                'host': '#8dc3fc',
                'database': '#aa83fc'
            })
        ])

        self.message = [
            ('class:username', self.database.database_url.username),
            ('class:punctuation', '@'),
            ('class:host', self.database.database_url.host),
            ('class:punctuation', ':'),
            ('class:database', self.database.get_current_db()),
            ('class:punctuation', '> '),
        ]
Beispiel #17
0
    class StyledPromptToolkitPrompter(PromptToolkitPrompter):
        """Prompter class which adds Pygments based terminal styling to the
        PromptToolKit prompt."""

        _prompt_toolkit_lexer = PygmentsLexer(ClojureLexer)
        _pygments_lexer = ClojureLexer()
        _style_settings = MappingProxyType({
            "style":
            style_from_pygments_cls(
                get_style_by_name(BASILISP_REPL_PYGMENTS_STYLE_NAME)),
            "include_default_pygments_style":
            False,
        })

        def print(self, msg: str) -> None:
            tokens = list(pygments.lex(msg, lexer=self._pygments_lexer))
            print_formatted_text(
                PygmentsTokens(tokens),
                **self._style_settings  # type: ignore[arg-type]
            )
Beispiel #18
0
    def __init__(self):
        self.style_name = 'trac'
        self.frame = None
        self.argsnlocals = ArgsnLocalsWindow(app=self)
        self.console = ConsoleWindow(app=self, callback=self._gdb_callback)
        self.source = SourceWindow(self)
        self.breakpoints = BreakpointsWindow(self, show=False)
        self.callstack = CallstackWindow(self, show=False)
        self.disassembly = DisassemblyWindow(self, show=False)
        self.registers = RegistersWindow(self, show=False)
        self.threads = ThreadsWindow(self, show=False)
        self.inferiors = ''

        self.col1 = HSplit([
            self.source.get_ui(),
            self.disassembly.get_ui(),
            self.console.get_ui()
        ])

        self.col2 = HSplit([
            self.argsnlocals.get_ui(),
            self.registers.get_ui(),
            self.callstack.get_ui(),
            self.threads.get_ui(),
            self.breakpoints.get_ui()
        ])

        self.container = VSplit([self.col1, self.col2])
        self.layout = Layout(container=self.container,
                             focused_element=self.console.get_ui())

        self.style = style_from_pygments_cls(get_style_by_name(
            self.style_name))

        kb = self._get_key_bindings()

        self.app = PromptApplication(layout=self.layout,
                                     style=self.style,
                                     full_screen=True,
                                     mouse_support=True,
                                     key_bindings=kb)
Beispiel #19
0
def run_shell(environment: dict):
    session = PromptSession()
    style = style_from_pygments_cls(NativeStyle)

    click.echo(f'{click.style("Welcome to as3 shell!", fg="yellow")}')

    while True:
        line = session.prompt(
            '>>> ',
            lexer=PygmentsLexer(ActionScript3Lexer),
            style=style,
            auto_suggest=AutoSuggestFromHistory(),
        )
        try:
            value = execute(line, '<shell>', environment)
        except Exception as e:
            print_exception(e)
        else:
            print(
                highlight(repr(value), ActionScript3Lexer(),
                          TerminalFormatter()))
Beispiel #20
0
    def style_factory(self, style_name):
        """Retrieve the specified pygments style.

        If the specified style is not found, the vim style is returned.

        :type style_name: str
        :param style_name: The pygments style name.

        :rtype: :class:`pygments.style.StyleMeta`
        :return: Pygments style info.
        """

        return merge_styles([
            style_from_pygments_cls(DefaultStyle),
            Style.from_dict({
                'path': 'ansicyan underline',
                'prompt': 'fg:ansiblue bold',
                'state': 'fg:ansigreen bold',
                'danger': 'fg:ansired bold',
            })
        ])
Beispiel #21
0
    def put_param(self, key=None, loop=False, display_hints=True) -> None:
        """
        Allows a user to define a PS name and add a new parameter at that named location. User will be prompted for a
        value, desc, and whether or not the parameter is a secret. If (Y) is selected for the secret, will encrypt the
        value with the appropriately mapped KMS key with the user's role.

        :param key: If specified, the user will be prompted for the specified key. Otherwise the user will be prompted
                    to specify the PS key to set.
        :param loop: Whether or not to continually loop and continue prompting the user for more keys.
        :param display_hints: Whether or not to display "Hints" to the user. You may want to turn this off if you are
                              looping and constantly calling put_param with a specified key.
        """

        value, desc, notify, put_another = True, None, False, True

        if display_hints:
            self._out.print(
                f"[[Hint:]] To upload a file's contents, pass in `file:///path/to/your/file` "
                f"in the value prompt.")

        while put_another:
            try:

                if not key:
                    lexer = PygmentsLexer(
                        FigLexer
                    ) if self.context.defaults.colors_enabled else None
                    style = style_from_pygments_cls(
                        FiggyPygment
                    ) if self.context.defaults.colors_enabled else None
                    key = Input.input(
                        'Please input a PS Name: ',
                        completer=self._config_view.get_config_completer(),
                        lexer=lexer,
                        style=style)
                    if self.parameter_is_existing_dir(key):
                        self._out.warn(
                            f'You attempted to store parameter named: {key},'
                            f' but it already exists in ParameterStore as a directory: {key}/'
                        )
                        key = None
                        continue

                if self._source_key:
                    plain_key = '/'.join(key.strip('/').split('/')[2:])
                    source_key = f'{self._source_key}/{plain_key}'
                    orig_value, orig_description = self._get.get_val_and_desc(
                        source_key)
                else:
                    orig_description = ''
                    orig_value = ''

                value = Input.input(f"Please input a value for {key}: ",
                                    default=orig_value if orig_value else '')

                if value.lower().startswith(self._FILE_PREFIX):
                    value = Utils.load_file(
                        value.replace(self._FILE_PREFIX, ""))

                existing_desc = self._ssm.get_description(key)
                desc = Input.input(
                    f"Please input an optional description: ",
                    optional=True,
                    default=existing_desc if existing_desc else
                    orig_description if orig_description else '')

                is_secret = Input.is_secret()
                parameter_type, kms_id = SSM_SECURE_STRING if is_secret else SSM_STRING, None
                if is_secret:
                    valid_keys = self._config_view.get_authorized_kms_keys()
                    if len(valid_keys) > 1:
                        key_name = Input.select_kms_key(valid_keys)
                    else:
                        key_name = valid_keys[0]

                    kms_id = self._config_view.get_authorized_key_id(
                        key_name, self.run_env)

                notify = True

                self._ssm.set_parameter(key,
                                        value,
                                        desc,
                                        parameter_type,
                                        key_id=kms_id)
                if key not in self._config_view.get_config_completer().words:
                    self._config_view.get_config_completer().words.append(key)

            except ClientError as e:
                if "AccessDeniedException" == e.response['Error']['Code']:
                    self._out.error(
                        f"\n\nYou do not have permissions to add config values at the path: [[{key}]]"
                    )
                    self._out.warn(
                        f"Your role of {self.context.role} may add keys under the following namespaces: "
                        f"{self._config_view.get_authorized_namespaces()}")
                    self._out.print(
                        f"Error message: {e.response['Error']['Message']}")
                else:
                    self._out.error(
                        f"Exception caught attempting to add config: {e}")

            print()
            if loop:
                to_continue = input(f"\nAdd another? (y/N): ")
                put_another = True if to_continue.lower() == 'y' else False
                key = None
            else:
                put_another = False
Beispiel #22
0
def create_radian_prompt_session(options, settings):

    history_file = ".radian_history"
    if options.no_history:
        history = ModalInMemoryHistory()
    elif not options.global_history and os.path.exists(history_file):
        history = ModalFileHistory(os.path.abspath(history_file))
    else:
        history = ModalFileHistory(
            os.path.join(os.path.expanduser("~"), history_file))

    if is_windows():
        output = None
    else:
        output = CustomVt100Output.from_pty(
            sys.stdout, term=get_term_environment_variable())

    def get_inputhook():
        terminal_width = [None]

        def _(context):
            while True:
                if context.input_is_ready():
                    break
                try:
                    process_events()
                except Exception:
                    pass

                output_width = session.app.output.get_size().columns
                if output_width and terminal_width[0] != output_width:
                    terminal_width[0] = output_width
                    setoption("width", max(terminal_width[0], 20))
                time.sleep(1.0 / 30)

        return _

    def vi_mode_prompt():
        if session.editing_mode.lower(
        ) == "vi" and settings.show_vi_mode_prompt:
            return settings.vi_mode_prompt.format(
                str(session.app.vi_state.input_mode)[3:6])
        return ""

    def message():
        if hasattr(session.current_mode, "get_message"):
            return ANSI(vi_mode_prompt() + session.current_mode.get_message())
        elif hasattr(session.current_mode, "message"):
            message = session.current_mode.message
            if callable(message):
                return ANSI(vi_mode_prompt() + message())
            else:
                return ANSI(vi_mode_prompt() + message)
        else:
            return ""

    session = ModalPromptSession(
        message=message,
        color_depth=ColorDepth.default(term=os.environ.get("TERM")),
        style=style_from_pygments_cls(get_style_by_name(
            settings.color_scheme)),
        editing_mode="VI"
        if settings.editing_mode in ["vim", "vi"] else "EMACS",
        history=history,
        enable_history_search=True,
        history_search_no_duplicates=settings.history_search_no_duplicates,
        search_ignore_case=settings.history_search_ignore_case,
        enable_suspend=True,
        tempfile_suffix=".R",
        input=CustomVt100Input(sys.stdin) if not is_windows() else None,
        output=output,
        inputhook=get_inputhook(),
        mode_class=RadianMode)

    apply_settings(session, settings)

    def browse_activator(session):
        message = session.prompt_text
        if BROWSE_PATTERN.match(message):
            session.browse_level = BROWSE_PATTERN.match(message).group(1)
            return True
        else:
            return False

    def browse_on_pre_accept(session):
        if session.default_buffer.text.strip() in [
                "n", "s", "f", "c", "cont", "Q", "where", "help"
        ]:
            session.add_history = False

    def shell_process_text(session):
        text = session.default_buffer.text
        shell.run_command(text)

    input_processors = []
    if settings.highlight_matching_bracket:
        input_processors.append(HighlightMatchingBracketProcessor())

    session.register_mode(
        "r",
        activator=lambda session: session.prompt_text == settings.prompt,
        insert_new_line=True,
        history_share_with="browse",
        get_message=lambda: settings.prompt,
        multiline=settings.indent_lines,
        complete_while_typing=settings.complete_while_typing,
        lexer=PygmentsLexer(SLexer),
        completer=RCompleter(timeout=settings.completion_timeout),
        key_bindings=create_key_bindings(),
        input_processors=input_processors,
        prompt_key_bindings=create_r_key_bindings(prase_text_complete))
    session.register_mode("shell",
                          on_post_accept=shell_process_text,
                          insert_new_line=True,
                          get_message=lambda: settings.shell_prompt,
                          multiline=settings.indent_lines,
                          complete_while_typing=settings.complete_while_typing,
                          lexer=None,
                          completer=SmartPathCompleter(),
                          prompt_key_bindings=create_shell_key_bindings())
    session.register_mode(
        "browse",
        activator=browse_activator,
        # on_pre_accept=browse_on_pre_accept,  # disable
        insert_new_line=True,
        history_share_with="r",
        get_message=lambda: settings.browse_prompt.format(session.browse_level
                                                          ),
        multiline=settings.indent_lines,
        complete_while_typing=True,
        lexer=PygmentsLexer(SLexer),
        completer=RCompleter(timeout=settings.completion_timeout),
        input_processors=input_processors,
        prompt_key_bindings=create_r_key_bindings(prase_text_complete),
        switchable_from=False,
        switchable_to=False)
    session.register_mode("unknown",
                          insert_new_line=False,
                          get_message=lambda: session.prompt_text,
                          complete_while_typing=False,
                          lexer=None,
                          completer=None,
                          prompt_key_bindings=None,
                          switchable_from=False,
                          switchable_to=False,
                          input_processors=[])

    return session
Beispiel #23
0
def session_initialize(session):
    if not sys.platform.startswith("win"):

        def reticulate_hook(*args):
            rcall(("base", "source"),
                  os.path.join(os.path.dirname(__file__), "data",
                               "patching_reticulate.R"), new_env())

        set_hook(package_event("reticulate", "onLoad"), reticulate_hook)

    if not roption("radian.suppress_reticulate_message", False):

        def reticulate_message_hook(*args):
            if not roption("radian.suppress_reticulate_message", False):
                rcall("packageStartupMessage", RETICULATE_MESSAGE)

        set_hook(package_event("reticulate", "onLoad"),
                 reticulate_message_hook)

    if roption("radian.enable_reticulate_prompt", True):

        def reticulate_prompt(*args):
            rcall(("base", "source"),
                  os.path.join(os.path.dirname(__file__), "data",
                               "register_reticulate.R"), new_env())

        set_hook(package_event("reticulate", "onLoad"), reticulate_prompt)

    if roption("radian.editing_mode", "emacs") in ["vim", "vi"]:
        session.app.editing_mode = EditingMode.VI
    else:
        session.app.editing_mode = EditingMode.EMACS

    color_scheme = roption("radian.color_scheme", "native")
    session.style = style_from_pygments_cls(get_style_by_name(color_scheme))

    session.auto_match = roption("radian.auto_match", False)
    session.auto_indentation = roption("radian.auto_indentation", True)
    session.tab_size = int(roption("radian.tab_size", 4))
    session.complete_while_typing = roption("radian.complete_while_typing",
                                            True)
    session.completion_timeout = roption("radian.completion_timeout", 0.05)

    session.history_search_no_duplicates = roption(
        "radian.history_search_no_duplicates", False)
    session.insert_new_line = roption("radian.insert_new_line", True)
    session.indent_lines = roption("radian.indent_lines", True)

    prompt = roption("radian.prompt", None)
    if not prompt:
        sys_prompt = roption("prompt")
        if sys_prompt == "> ":
            prompt = PROMPT
        else:
            prompt = sys_prompt

    session.default_prompt = prompt
    setoption("prompt", prompt)

    shell_prompt = roption("radian.shell_prompt", SHELL_PROMPT)
    session.shell_prompt = shell_prompt

    browse_prompt = roption("radian.browse_prompt", BROWSE_PROMPT)
    session.browse_prompt = browse_prompt

    set_width_on_resize = roption("setWidthOnResize", True)
    session.auto_width = roption("radian.auto_width", set_width_on_resize)
    output_width = session.app.output.get_size().columns
    if output_width and session.auto_width:
        setoption("width", output_width)

    # necessary on windows
    setoption("menu.graphics", False)

    # enables completion of installed package names
    if rcopy(reval("rc.settings('ipck')")) is None:
        reval("rc.settings(ipck = TRUE)")

    # backup the updated settings
    session._backup_settings()
Beispiel #24
0
#!/usr/bin/env python
from prompt_toolkit.styles import style_from_pygments_cls
from pygments.styles.tango import TangoStyle
from prompt_toolkit.shortcuts import clear
from prompt_toolkit import prompt
from prompt_toolkit.keys import Keys
from prompt_toolkit.key_binding.key_bindings import KeyBindings

kb = KeyBindings()


@kb.add(Keys.ControlC)
def handler(event):
    clear()


style = style_from_pygments_cls(TangoStyle)

if __name__ == '__main__':
    while True:
        prompt('tr0llb0x>>> ', key_bindings=kb)
Beispiel #25
0
                    filename += '/'
                elif self.only_directories:
                    continue

                if not self.file_filter(full_name):
                    continue

                yield Completion(completion, 0, display=filename)
        except OSError:
            pass


pathcompleter = PathCompleter(expanduser=False)
completer = merge_completers([pathcompleter, wordcompleter])

style = style_from_pygments_cls(MyGpStyle)


def prompt_info(text):
    print_formatted_text(HTML('<green>{0}</green>').format(text))


def prompt_error(text):
    print_formatted_text(HTML('<red>{0}</red>').format(text))


def gnuplot(lines):
    import subprocess
    proc = subprocess.Popen(
        ['gnuplot', '-p'],
        shell=False,
Beispiel #26
0
from prompt_toolkit.application import run_in_terminal
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.formatted_text import PygmentsTokens
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.key_binding.key_processor import KeyPressEvent
from prompt_toolkit.lexers import PygmentsLexer
from prompt_toolkit.styles import Style, style_from_pygments_cls, merge_styles
from pybreak import __version__
from pybreak.command import Command, After, Quit, PrintNearbyCode
from pybreak.frame_history import FrameHistory
from pybreak.utility import get_terminal_size

styles = Style.from_dict({"rprompt": "gray"})

styles = merge_styles(
    [styles, style_from_pygments_cls(get_style_by_name('monokai'))])


def prompt_continuation(width, line_number, is_soft_wrap):
    continuation = '.' * (width - 1)
    return HTML(f"<green>{continuation}</green>")


class Pybreak(Bdb):
    def __init__(self):
        super().__init__()
        self.num_prompts = 0
        self.frame_history = FrameHistory()
        self.eval_count: int = 0
        self.prev_command = None
Beispiel #27
0
data = client.send('listCommands', {}, True)
data = list(map(lambda c: c['name'], data))

sql_completer = WordCompleter(data, ignore_case=True)

style = Style.from_dict({
    'completion-menu.completion': 'bg:#008888 #ffffff',
    'completion-menu.completion.current': 'bg:#00aaaa #000000',
    'scrollbar.background': 'bg:#88aaaa',
    'scrollbar.button': 'bg:#222222',
})

session = PromptSession(history=FileHistory('./.main-prompt-history'),
                        lexer=PygmentsLexer(InputLexer),
                        completer=sql_completer,
                        style=style_from_pygments_cls(
                            get_style_by_name(u'monokai')),
                        reserve_space_for_menu=2)

while True:
    try:
        text = session.prompt('>>> ', auto_suggest=AutoSuggestFromHistory())
    except KeyboardInterrupt:
        continue
    except EOFError:
        break
    else:
        #print('You entered:', text)
        res = client.send('execCommand', {'payload': text}, True)
        res = json.dumps(res, indent=4)
        # if res[0:2] == '["' or res[0:2] == '{"':
Beispiel #28
0
 def __init__(self, app):
     self.app = app
     self.payload_lexer = PeekLexer(stack=('value',))
     self.style = style_from_pygments_cls(PeekStyle)
     self.style_transformation = ConditionalStyleTransformation(
         SwapLightAndDarkStyleTransformation(), self.app.config.as_bool('swap_colour'))
Beispiel #29
0
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
#

from prompt_toolkit.styles import (
    merge_styles,
    style_from_pygments_cls,
    style_from_pygments_dict,
)
from prompt_toolkit.styles import Style
from pygments.styles.monokai import MonokaiStyle
from pygments.token import Token, Name

shell_style = merge_styles([
    style_from_pygments_cls(MonokaiStyle),
    style_from_pygments_dict({
        # Commands
        Name.Command: "#f2b44f",
        Name.SubCommand: "#f2c46f",
        Name.InvalidCommand: "bg:#ff0066 #000000",
        Name.Select: "#0000ff",
        Name.Query: "#d78700",
        Name.Key: "#ffffff",
        Name.Path: "#fff484",
        Name.Help: "#00aa00",
        Name.Exit: "#ff0066",
        # User input.
        Token: "#ff0066",
        # Prompt.
        Token.Username: "******",
Beispiel #30
0
async def run():
    # We need to connect bash to a pseudo-terminal to trick it into making the
    # output unbuffered.
    # TODO: Figure out how to pipe stdout and stderr.
    bash_args = ['bash', '--noediting', '--noprofile', '--norc']
    env = os.environ.copy()
    env['PS1'] = ''

    key_bindings = KeyBindings()

    key_bindings.add('enter')(accept_line)

    @key_bindings.add(Keys.Escape, 'enter')
    def _newline(event):
        """
        Newline (in case of multiline input.
        """
        event.current_buffer.newline(copy_margin=not in_paste_mode())

    session = PromptSession(lexer=PygmentsLexer(BashLexer),
                            style=style_from_pygments_cls(
                                get_style_by_name('monokai')),
                            multiline=True,
                            prompt_continuation=ps2(),
                            key_bindings=key_bindings)

    git_watcher = setup_git_prompt(session)

    try:
        process = ptyprocess.PtyProcess.spawn(bash_args, env=env, echo=False)
        iostream = trio.lowlevel.FdStream(process.fd)

        async def _write_stdout():
            with patch_stdout(raw=True):
                while True:
                    sys.stdout.write((await
                                      iostream.receive_some()).decode('utf-8'))

        # stderr = process.stderr
        # async def _write_stderr():
        #     sys.stderr.buffer.write(await stderr.receive_some())
        async def _write_stdin(receive_channel):
            async with receive_channel:
                while True:
                    async for value in receive_channel:
                        await iostream.send_all(value)

        async def _get_command(send_channel):
            async with send_channel:
                while True:
                    command = await trio_asyncio.aio_as_trio(
                        session.prompt_async)(ps1())
                    await send_channel.send(command.encode('utf-8') + b'\n')

        try:
            async with trio.open_nursery() as nursery:
                send_channel, receive_channel = trio.open_memory_channel(0)
                nursery.start_soon(_write_stdout)
                nursery.start_soon(_get_command, send_channel)
                # nursery.start_soon(_write_stderr)
                nursery.start_soon(_write_stdin, receive_channel)
                nursery.start_soon(git_watcher)
        except EOFError:
            process.terminate()
    finally:
        process.terminate()
        sys.exit(process.exitstatus)