Example #1
0
def main():
    layout = Layout(left_margin=LeftMarginWithLineNumbers(),
                    before_input=DefaultPrompt(text='Before input >> '),
                    after_input=Prompt(' << after input'),
                    top_toolbars=[
                        TextToolbar('This is a top toolbar',
                                    token=Token.TopToolbar1),
                        TextToolbar('This is another top toolbar',
                                    token=Token.TopToolbar2),
                    ],
                    bottom_toolbars=[
                        ArgToolbar(),
                        SearchToolbar(),
                        CompletionsToolbar(),
                        TextToolbar('This is a bottom toolbar',
                                    token=Token.BottomToolbar1),
                        TextToolbar('This is another bottom toolbar',
                                    token=Token.BottomToolbar2),
                    ],
                    show_tildes=True,
                    menus=[CompletionsMenu()])

    cli = CommandLineInterface(layout=layout,
                               style=TestStyle,
                               line=Line(is_multiline=True,
                                         completer=TestCompleter()))

    code_obj = cli.read_input(initial_value=lipsum)
    print('You said: ' + code_obj.text)
def main():
    cli = CommandLineInterface(layout=layout,
                               style=TestStyle,
                               line=Line(validator=EmailValidator()))

    document = cli.read_input()
    print('You said: ' + document.text)
Example #3
0
def create_cli(message='',
               multiline=False,
               is_password=False,
               vi_mode=False,
               lexer=None,
               enable_system_prompt=False,
               enable_open_in_editor=False,
               validator=None,
               completer=None,
               style=None,
               history=None,
               get_bottom_toolbar_tokens=None):

    # Create history instance.
    if history is None:
        history = History()

    # Load all key bindings.
    manager = KeyBindingManager(enable_vi_mode=vi_mode,
                                enable_system_prompt=enable_system_prompt,
                                enable_open_in_editor=enable_open_in_editor)

    # Create interface.
    return CommandLineInterface(
        layout=create_default_layout(message=message, lexer=lexer, is_password=is_password,
                                     reserve_space_for_menu=(completer is not None),
                                     get_bottom_toolbar_tokens=get_bottom_toolbar_tokens),
        buffer=Buffer(
            is_multiline=multiline,
            history=history,
            validator=validator,
            completer=completer,
        ),
        key_bindings_registry=manager.registry,
        style=style)
Example #4
0
 def _create_cli(self):
     """Create the prompt_toolkit's CommandLineInterface."""
     history = FileHistory(os.path.expanduser('~/.haxornewshistory'))
     toolbar = Toolbar(lambda: self.paginate_comments)
     layout = create_default_layout(
         message=u'haxor> ',
         reserve_space_for_menu=8,
         get_bottom_toolbar_tokens=toolbar.handler,
     )
     cli_buffer = Buffer(
         history=history,
         auto_suggest=AutoSuggestFromHistory(),
         enable_history_search=True,
         completer=self.completer,
         complete_while_typing=Always(),
         accept_action=AcceptAction.RETURN_DOCUMENT)
     self.key_manager = self._create_key_manager()
     style_factory = StyleFactory(self.theme)
     application = Application(
         mouse_support=False,
         style=style_factory.style,
         layout=layout,
         buffer=cli_buffer,
         key_bindings_registry=self.key_manager.manager.registry,
         on_exit=AbortAction.RAISE_EXCEPTION,
         on_abort=AbortAction.RETRY,
         ignore_case=True)
     eventloop = create_eventloop()
     self.cli = CommandLineInterface(
         application=application,
         eventloop=eventloop)
Example #5
0
    def initialize(self):
        history = InMemoryHistory()
        toolbar_handler = create_toolbar_handler(self.get_long_options)

        layout = create_prompt_layout(
            get_prompt_tokens=self.get_prompt_tokens,
            lexer=create_lexer(),
            get_bottom_toolbar_tokens=toolbar_handler)

        buf = Buffer(history=history,
                     completer=CrutchCompleter(self.renv),
                     complete_while_typing=Always(),
                     accept_action=AcceptAction.RETURN_DOCUMENT)

        manager = get_key_manager(self.set_long_options, self.get_long_options)

        application = Application(style=style_factory(),
                                  layout=layout,
                                  buffer=buf,
                                  key_bindings_registry=manager.registry,
                                  on_exit=AbortAction.RAISE_EXCEPTION,
                                  on_abort=AbortAction.RETRY,
                                  ignore_case=True)

        eventloop = create_eventloop()

        self.cli = CommandLineInterface(application=application,
                                        eventloop=eventloop)
Example #6
0
    def run(self):
      labels = self.neo4j.get_labels()
      relationship_types = self.neo4j.get_relationship_types()
      properties = self.neo4j.get_property_keys()

      if self.filename:
        with open(self.filename, "rb") as f:
          queries = split_queries_on_semicolons(f.read())

          for query in queries:
            print("> " + query)
            self.handle_query(query)
            print()

          return

      click.secho(" ______     __  __     ______     __         __    ", fg="red")
      click.secho("/\  ___\   /\ \_\ \   /\  ___\   /\ \       /\ \   ", fg="yellow")
      click.secho("\ \ \____  \ \____ \  \ \ \____  \ \ \____  \ \ \  ", fg="green")
      click.secho(" \ \_____\  \/\_____\  \ \_____\  \ \_____\  \ \_\ ", fg="blue")
      click.secho("  \/_____/   \/_____/   \/_____/   \/_____/   \/_/ ", fg="magenta")

      print("Cycli version: {}".format(__version__))
      print("Neo4j version: {}".format(".".join(map(str, self.neo4j.neo4j_version))))
      print("Bug reports: https://github.com/nicolewhite/cycli/issues\n")

      completer = CypherCompleter(labels, relationship_types, properties)

      layout = create_prompt_layout(
        lexer=CypherLexer,
        get_prompt_tokens=get_tokens,
        reserve_space_for_menu=8,
      )

      buff = CypherBuffer(
        accept_action=AcceptAction.RETURN_DOCUMENT,
        history=FileHistory(filename=os.path.expanduser('~/.cycli_history')),
        completer=completer,
        complete_while_typing=True,
      )

      application = Application(
        style=PygmentsStyle(CypherStyle),
        buffer=buff,
        layout=layout,
        on_exit=AbortAction.RAISE_EXCEPTION,
        key_bindings_registry=CypherBinder.registry
      )

      cli = CommandLineInterface(application=application, eventloop=create_eventloop())

      try:
        while True:
          document = cli.run()
          query = document.text
          self.handle_query(query)
      except UserWantsOut:
        print("Goodbye!")
      except Exception as e:
        print(e)
Example #7
0
def main(args=sys.argv[1:]):
    parser, args = parseargs(args)

    if args.debug:
        log.setLevel(logging.DEBUG)

    loop = asyncio.get_event_loop()
    grbl = SerialGrbl(args.device, args.baudrate, loop)

    registry = load_key_bindings_for_prompt()
    history = InMemoryHistory()

    app_loop = create_asyncio_eventloop(loop=loop)
    app = create_prompt_application(message='> ',
                                    history=history,
                                    key_bindings_registry=registry)
    cli = CommandLineInterface(application=app, eventloop=app_loop)

    for key, func in key_to_func.items():
        func = functools.partial(func, grbl=grbl, loop=loop)
        registry.add_binding(key, eager=True)(func)

    try:
        main_task = asyncio.ensure_future(main_coro(loop, grbl, cli))
        return loop.run_until_complete(main_task)
    except (EOFError, KeyboardInterrupt):
        main_task.cancel()
        return 1
    except serial.SerialException as error:
        log.fatal(error)
        return 1
def main():
    eventloop = create_eventloop()

    cli = CommandLineInterface(layout=Window(
        BufferControl(input_processors=[ClockPrompt()])),
                               eventloop=eventloop)
    done = [False]  # Non local

    def on_read_start():
        """
        This function is called when we start reading at the input.
        (Actually the start of the read-input event loop.)
        """

        # Following function should be run in the background.
        # We do it by using an executor thread from the `CommandLineInterface`
        # instance.
        def run():
            # Send every second a redraw request.
            while not done[0]:
                time.sleep(1)
                cli.request_redraw()

        cli.eventloop.run_in_executor(run)

    def on_read_end():
        done[0] = True

    cli.onReadInputStart += on_read_start
    cli.onReadInputEnd += on_read_end

    code_obj = cli.read_input()
    print('You said: %s' % code_obj.text)

    eventloop.close()
Example #9
0
def run():
    validate_osenvironment()
    print_banner()

    cli_buffer = OSBuffer()
    ltobj = OSLayout(multiwindow=False)

    application = Application(style=PygmentsStyle(OSStyle),
                              layout=ltobj.layout,
                              buffers=cli_buffer.buffers,
                              on_exit=AbortAction.RAISE_EXCEPTION,
                              key_bindings_registry=OSKeyBinder.registry)

    cli = CommandLineInterface(application=application,
                               eventloop=create_eventloop())

    while True:
        try:
            document = cli.run(reset_current_buffer=True)
            process_document(document)
        except KeyboardInterrupt:
            # A keyboardInterrupt generated possibly due to Ctrl-C
            print "Keyboard Interrupt Generated"
            continue
        except EOFError:
            print "cntl-D"
            sys.exit()
Example #10
0
def main():
    # We start with a `KeyBindingManager` instance, because this will already
    # nicely load all the default key bindings.
    key_bindings_manager = KeyBindingManager()

    # Add our own key binding to the registry of the key bindings manager.
    @key_bindings_manager.registry.add_binding(Keys.F4)
    def _(event):
        """
        When F4 has been pressed. Insert "hello world" as text.
        """
        event.cli.current_buffer.insert_text('hello world')

    @key_bindings_manager.registry.add_binding('x', 'y')
    def _(event):
        """
        (Useless, but for demoing.)
        Typing 'xy' will insert 'z'.

        Note that when you type for instance 'xa', the insertion of 'x' is
        postponed until the 'a' is typed. because we don't know earlier whether
        or not a 'y' will follow.
        """
        event.cli.current_buffer.insert_text('z')

    # Create a CLI with the key bindings registry of this manager.
    cli = CommandLineInterface(key_bindings_registry=key_bindings_manager.registry)

    # Read input.
    print('Press F4 to insert "hello world", type "xy" to insert "z":')
    code_obj = cli.read_input()
    print('You said: %s' % code_obj.text)
Example #11
0
def loop(cmd, history_file):
    from prompt_toolkit import CommandLineInterface, AbortAction
    from prompt_toolkit import Exit
    from prompt_toolkit.layout import Layout
    from prompt_toolkit.line import Line
    from prompt_toolkit.renderer import Output

    cli_line = Line(completer=SQLCompleter(cmd.connection, cmd.lines),
                    history=TruncatedFileHistory(
                        history_file, max_length=MAX_HISTORY_LENGTH))
    layout = Layout(
        before_input=CrashPrompt(cmd.lines),
        menus=[],
        lexer=SqlLexer,
        bottom_toolbars=[],
        show_tildes=False,
    )
    key_binding_factories = _detect_key_bindings()
    cli = CommandLineInterface(style=MonokaiStyle,
                               layout=layout,
                               line=cli_line,
                               key_binding_factories=key_binding_factories)
    output = Output(cli.renderer.stdout)
    global get_num_columns

    def get_num_columns():
        return output.get_size().columns

    try:
        while True:
            doc = cli.read_input(on_exit=AbortAction.RAISE_EXCEPTION)
            cmd.process(doc.text)
    except Exit:  # Quit on Ctrl-D keypress
        cmd.logger.warn(u'Bye!')
        return
Example #12
0
    def _build_cli(self, history):
        def set_vi_mode(value):
            self.vi_mode = value

        key_binding_manager = mssqlcli_bindings(
            get_vi_mode_enabled=lambda: self.vi_mode,
            set_vi_mode_enabled=set_vi_mode)

        def prompt_tokens(_):
            prompt = self.get_prompt()
            return [(Token.Prompt, prompt)]

        def get_continuation_tokens(cli, width):
            continuation = self.multiline_continuation_char * (width - 1) + ' '
            return [(Token.Continuation, continuation)]

        get_toolbar_tokens = create_toolbar_tokens_func(
            lambda: self.vi_mode, None, None, None)

        layout = create_prompt_layout(
            lexer=PygmentsLexer(PostgresLexer),
            reserve_space_for_menu=self.min_num_menu_lines,
            get_prompt_tokens=prompt_tokens,
            get_continuation_tokens=get_continuation_tokens,
            get_bottom_toolbar_tokens=get_toolbar_tokens,
            display_completions_in_columns=self.wider_completion_menu,
            multiline=True,
            extra_input_processors=[
                # Highlight matching brackets while editing.
                ConditionalProcessor(
                    processor=HighlightMatchingBracketProcessor(
                        chars='[](){}'),
                    filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()),
            ])

        with self._completer_lock:
            buf = MssqlBuffer(auto_suggest=AutoSuggestFromHistory(),
                              always_multiline=self.multi_line,
                              multiline_mode=self.multiline_mode,
                              completer=self.completer,
                              history=history,
                              complete_while_typing=Always(),
                              accept_action=AcceptAction.RETURN_DOCUMENT)

            editing_mode = EditingMode.VI if self.vi_mode else EditingMode.EMACS

            application = Application(
                style=style_factory(self.syntax_style, self.cli_style),
                layout=layout,
                buffer=buf,
                key_bindings_registry=key_binding_manager.registry,
                on_exit=AbortAction.RAISE_EXCEPTION,
                on_abort=AbortAction.RETRY,
                ignore_case=True,
                editing_mode=editing_mode)

            cli = CommandLineInterface(application=application,
                                       eventloop=self.eventloop)

            return cli
Example #13
0
    def _build_cli(self):
        layout = create_prompt_layout(
            message='{0}> '.format(self.args['username']),
            lexer=PygmentsLexer(SqlLexer),
        )

        buf = Buffer(completer=self.completer,
                     history=self.history,
                     complete_while_typing=Always(),
                     accept_action=AcceptAction.RETURN_DOCUMENT)

        key_binding_manager = KeyBindingManager(
            enable_abort_and_exit_bindings=True, )

        application = Application(
            layout=layout,
            buffer=buf,
            key_bindings_registry=key_binding_manager.registry,
            on_exit=AbortAction.RAISE_EXCEPTION,
            on_abort=AbortAction.RETRY,
            ignore_case=True)

        cli = CommandLineInterface(application=application,
                                   eventloop=self.eventloop)

        return cli
Example #14
0
 def run(self):
     eventloop = create_eventloop()
     try:
         cli = CommandLineInterface(application=self.application,
                                    eventloop=eventloop)
         cli.run()
     finally:
         eventloop.close()
Example #15
0
    def _build_cli(self):
        eventloop = create_eventloop()

        if self._options.persistent_history:
            history = FileHistory(
                os.path.join(
                    os.path.expanduser("~"), ".{}_history".format(self._ctx.binary_name)
                )
            )
        else:
            history = InMemoryHistory()

        layout = create_prompt_layout(
            lexer=PygmentsLexer(NubiaLexer),
            reserve_space_for_menu=5,
            get_prompt_tokens=self.get_prompt_tokens,
            get_rprompt_tokens=self._status_bar.get_rprompt_tokens,
            get_bottom_toolbar_tokens=self._status_bar.get_tokens,
            display_completions_in_columns=False,
            multiline=True,
            extra_input_processors=[
                ConditionalProcessor(
                    processor=HighlightMatchingBracketProcessor(chars="[](){}"),
                    filter=HasFocus(DEFAULT_BUFFER) & ~IsDone(),
                )
            ],
        )

        buf = Buffer(
            completer=self._completer,
            history=history,
            auto_suggest=self._suggestor,
            complete_while_typing=Always(),
            accept_action=AcceptAction.RETURN_DOCUMENT,
        )

        # If EDITOR does not exist, take EMACS
        # if it does, try fit the EMACS/VI pattern using upper
        editor = getattr(
            EditingMode,
            os.environ.get("EDITOR", EditingMode.EMACS).upper(),
            EditingMode.EMACS,
        )

        application = Application(
            style=shell_style,
            buffer=buf,
            editing_mode=editor,
            key_bindings_registry=self._registry,
            layout=layout,
            on_exit=AbortAction.RAISE_EXCEPTION,
            on_abort=AbortAction.RETRY,
            ignore_case=True,
        )

        cli = CommandLineInterface(application=application, eventloop=eventloop)
        return cli
def main():
    cli = CommandLineInterface(line=Line(
        history=FileHistory('.example-history-file')))

    try:
        while True:
            document = cli.read_input(on_exit=AbortAction.RAISE_EXCEPTION)
            print('You said: ' + document.text)
    except Exit:
        pass
Example #17
0
File: saws.py Project: MaWich/saws
    def _create_cli(self):
        """Creates the prompt_toolkit's CommandLineInterface.

        Args:
            * None.

        Returns:
            None.
        """
        history = FileHistory(os.path.expanduser('~/.saws-history'))
        toolbar = Toolbar(self.get_color,
                          self.get_fuzzy_match,
                          self.get_shortcut_match)
        layout = create_default_layout(
            message='saws> ',
            reserve_space_for_menu=8,
            lexer=CommandLexer,
            get_bottom_toolbar_tokens=toolbar.handler,
            extra_input_processors=[
                ConditionalProcessor(
                    processor=HighlightMatchingBracketProcessor(
                        chars='[](){}'),
                    filter=HasFocus(DEFAULT_BUFFER) & ~IsDone())
            ]
        )
        cli_buffer = Buffer(
            history=history,
            auto_suggest=AutoSuggestFromHistory(),
            enable_history_search=True,
            completer=self.completer,
            complete_while_typing=Always(),
            accept_action=AcceptAction.RETURN_DOCUMENT)
        self.key_manager = KeyManager(
            self.set_color,
            self.get_color,
            self.set_fuzzy_match,
            self.get_fuzzy_match,
            self.set_shortcut_match,
            self.get_shortcut_match,
            self.refresh_resources_and_options,
            self.handle_docs)
        style_factory = StyleFactory(self.theme)
        application = Application(
            mouse_support=False,
            style=style_factory.style,
            layout=layout,
            buffer=cli_buffer,
            key_bindings_registry=self.key_manager.manager.registry,
            on_exit=AbortAction.RAISE_EXCEPTION,
            on_abort=AbortAction.RETRY,
            ignore_case=True)
        eventloop = create_eventloop()
        self.aws_cli = CommandLineInterface(
            application=application,
            eventloop=eventloop)
Example #18
0
 def _get_cli(self, loop):
     global history
     return CommandLineInterface(
         application=create_prompt_application(
             multiline=Condition(lambda: self._multi_line),
             get_prompt_tokens=self._get_prompt,
             history=history,
             wrap_lines=True,
         ),
         eventloop=loop,
     )
Example #19
0
def main():
    cli = CommandLineInterface(
        style=AnimalStyle,
        layout=Layout(before_input=DefaultPrompt('Give some animals: '),
                      menus=[CompletionsMenu()]),
        line=Line(completer=AnimalCompleter()),
        create_async_autocompleters=True,
    )

    print('Press tab to complete')
    code_obj = cli.read_input()
    print('You said: ' + code_obj.text)
Example #20
0
    def _build_cli(self, history):
        def set_vi_mode(value):
            self.vi_mode = value

        key_binding_manager = pgcli_bindings(
            get_vi_mode_enabled=lambda: self.vi_mode,
            set_vi_mode_enabled=set_vi_mode)

        def prompt_tokens(_):
            return [(Token.Prompt, '%s> ' % self.pgexecute.dbname)]

        def get_continuation_tokens(cli, width):
            return [(Token.Continuation, '.' * (width - 1) + ' ')]

        get_toolbar_tokens = create_toolbar_tokens_func(
            lambda: self.vi_mode, self.completion_refresher.is_refreshing)

        layout = create_prompt_layout(
            lexer=PygmentsLexer(PostgresLexer),
            reserve_space_for_menu=4,
            get_prompt_tokens=prompt_tokens,
            get_continuation_tokens=get_continuation_tokens,
            get_bottom_toolbar_tokens=get_toolbar_tokens,
            display_completions_in_columns=self.wider_completion_menu,
            multiline=True,
            extra_input_processors=[
                # Highlight matching brackets while editing.
                ConditionalProcessor(
                    processor=HighlightMatchingBracketProcessor(
                        chars='[](){}'),
                    filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()),
            ])

        with self._completer_lock:
            buf = PGBuffer(always_multiline=self.multi_line,
                           completer=self.completer,
                           history=history,
                           complete_while_typing=Always(),
                           accept_action=AcceptAction.RETURN_DOCUMENT)

            application = Application(
                style=style_factory(self.syntax_style, self.cli_style),
                layout=layout,
                buffer=buf,
                key_bindings_registry=key_binding_manager.registry,
                on_exit=AbortAction.RAISE_EXCEPTION,
                on_abort=AbortAction.RETRY,
                ignore_case=True)

            cli = CommandLineInterface(application=application)

            return cli
Example #21
0
    def run(self):
        style = style_from_dict({
            Token.Prompt: 'bold',
            Token.Toolbar: '#ccc bg:#333',
            Token.Name: '#fff bold bg:#333',
        })

        history = InMemoryHistory()
        eventloop = create_eventloop()
        app = create_prompt_application(
            history=history,
            style=style,
            get_bottom_toolbar_tokens=self.get_bottom_toolbar_tokens,
            get_prompt_tokens=self.get_prompt_tokens)
        self.cli = CommandLineInterface(app, eventloop)

        with self.cli.patch_stdout_context(raw=True):
            while True:
                try:
                    self.cli.run()
                    doc = self.cli.return_value()
                    if doc is None:
                        return
                    cmd = shlex.split(doc.text)
                    app.buffer.reset(append_to_history=True)

                    if not cmd:
                        continue
                    elif cmd[0] in ('exit', 'quit'):
                        self.q.put(Exit())
                        return
                    elif cmd[0] == 'help':
                        print('Help text forthcoming.')
                    elif cmd[0] == 'skip':
                        self.q.put(Skip())
                    elif cmd[0] == 'set':
                        self.q.put(
                            Set(cmd[1], ast.literal_eval(' '.join(cmd[2:]))))
                    else:
                        print('Unknown command. Try \'help\'.')
                except KeyboardInterrupt:
                    continue
                except EOFError:
                    self.q.put(Exit())
                    return
                except Exception as err:
                    print(err)
                    self.q.put(Exit())
                    return
Example #22
0
File: repl.py Project: boseca/crash
def loop(cmd, history_file):
    key_binding_manager = KeyBindingManager(
        enable_search=True, enable_abort_and_exit_bindings=True)
    layout = create_prompt_layout(
        message=u'cr> ',
        multiline=True,
        lexer=SqlLexer,
        extra_input_processors=[
            ConditionalProcessor(
                processor=HighlightMatchingBracketProcessor(chars='[](){}'),
                filter=HasFocus(DEFAULT_BUFFER) & ~IsDone())
        ])
    buffer = CrashBuffer(history=TruncatedFileHistory(
        history_file, max_length=MAX_HISTORY_LENGTH),
                         accept_action=AcceptAction.RETURN_DOCUMENT,
                         completer=SQLCompleter(cmd))
    buffer.complete_while_typing = lambda cli=None: cmd.should_autocomplete()
    application = Application(
        layout=layout,
        buffer=buffer,
        style=PygmentsStyle.from_defaults(pygments_style_cls=CrateStyle),
        key_bindings_registry=key_binding_manager.registry,
        editing_mode=_get_editing_mode(),
        on_exit=AbortAction.RAISE_EXCEPTION,
        on_abort=AbortAction.RETRY,
    )
    eventloop = create_eventloop()
    output = create_output()
    cli = CommandLineInterface(application=application,
                               eventloop=eventloop,
                               output=output)

    def get_num_columns_override():
        return output.get_size().columns

    cmd.get_num_columns = get_num_columns_override

    while True:
        try:
            doc = cli.run(reset_current_buffer=True)
            if doc:
                cmd.process(doc.text)
        except KeyboardInterrupt:
            cmd.logger.warn(
                "Query not cancelled. Run KILL <jobId> to cancel it")
        except EOFError:
            cmd.logger.warn(u'Bye!')
            return
Example #23
0
def main(database):
    connection = sqlite3.connect(database)
    layout = Layout(before_input=DefaultPrompt('> '),
                    lexer=SqlLexer,
                    menus=[CompletionsMenu()])
    line = Line(completer=SqlCompleter())
    cli = CommandLineInterface(style=DocumentStyle, layout=layout, line=line)
    try:
        while True:
            document = cli.read_input(on_exit=AbortAction.RAISE_EXCEPTION)
            with connection:
                messages = connection.execute(document.text)
                for message in messages:
                    print message
    except Exit:
        print 'GoodBye!'
    def _build_cli(self):
        eventloop = create_eventloop()

        history = FileHistory(
            os.path.join(
                os.path.expanduser("~"),
                ".{}_history".format(self._ctx.binary_name),
            ))

        layout = create_prompt_layout(
            lexer=PygmentsLexer(NubiaLexer),
            reserve_space_for_menu=5,
            get_prompt_tokens=self.get_prompt_tokens,
            get_rprompt_tokens=self._status_bar.get_rprompt_tokens,
            get_bottom_toolbar_tokens=self._status_bar.get_tokens,
            display_completions_in_columns=False,
            multiline=True,
            extra_input_processors=[
                ConditionalProcessor(
                    processor=HighlightMatchingBracketProcessor(
                        chars="[](){}"),
                    filter=HasFocus(DEFAULT_BUFFER) & ~IsDone(),
                )
            ],
        )

        buf = Buffer(
            completer=self._completer,
            history=history,
            auto_suggest=self._suggestor,
            complete_while_typing=Always(),
            accept_action=AcceptAction.RETURN_DOCUMENT,
        )

        application = Application(
            style=shell_style,
            buffer=buf,
            key_bindings_registry=self._registry,
            layout=layout,
            on_exit=AbortAction.RAISE_EXCEPTION,
            on_abort=AbortAction.RETRY,
            ignore_case=True,
        )

        cli = CommandLineInterface(application=application,
                                   eventloop=eventloop)
        return cli
Example #25
0
    def _create_cli(self):
        self._create_layout()
        self._create_buffer()
        self._create_style()
        self._create_manage()

        application = Application(layout=self.layout,
                                  buffer=self.buffer,
                                  style=self.style,
                                  key_bindings_registry=self.manager.registry,
                                  mouse_support=False,
                                  on_exit=AbortAction.RAISE_EXCEPTION,
                                  on_abort=AbortAction.RETRY,
                                  ignore_case=True)
        event_loop = create_eventloop()
        self.network_cli = CommandLineInterface(application=application,
                                                eventloop=event_loop)
Example #26
0
 def __init__(self, parser, engine, options=None):
     self.parser = parser
     self.engine = engine
     self.options = options if options is not None else {}
     util.ensure_data_dir_exists()
     application = create_prompt_application(
         message='> ',
         lexer=PygmentsLexer(SqlLexer),
         history=FileHistory(os.path.expanduser('~/.aq/history')),
         completer=AqCompleter(schemas=engine.available_schemas,
                               tables=engine.available_tables),
         auto_suggest=AutoSuggestFromHistory(),
         validator=QueryValidator(parser),
         on_abort=AbortAction.RETRY,
     )
     loop = create_eventloop()
     self.cli = CommandLineInterface(application=application,
                                     eventloop=loop)
     self.patch_context = self.cli.patch_stdout_context()
Example #27
0
    def run_cli(self):
        """
        Run the main loop
        """
        print(u'Version:', __version__)
        print(u'Home: https://github.com/glasslion/saltcli')

        history = FileHistory(os.path.expanduser('~/.saltcli-history'))

        layout = create_prompt_layout(
            message=u'saltcli> ',
        )

        application = Application(
            layout=layout
        )

        eventloop = create_eventloop()

        self.cli = CommandLineInterface(
            application=application,
            eventloop=eventloop)

        while True:
            try:
                document = self.cli.run()

                if quit_command(document.text):
                    raise EOFError

            except KeyboardInterrupt:
                # user pressed Ctrl + C
                    click.echo('')
            except EOFError:
                break
            except Exception as ex:
                self.logger.debug('Exception: %r.', ex)
                self.logger.error("traceback: %r", traceback.format_exc())
                click.secho("{0}".format(ex), fg='red')
                break

        print('Goodbye!')
Example #28
0
def main():
    layout = Layout(before_input=DefaultPrompt('> '), menus=[CompletionMenu()])
    line = Line(RESTCompleter())
    cli = CommandLineInterface(style=DocumentStyle, layout=layout, line=line)
    try:
        while True:
            document = cli.read_input(on_exit=AbortAction.RAISE_EXCEPTION)

            input_args = document.text.split(' ')

            if len(input_args) < 2:
                raise AssertionError(
                    "Must provide at least a method and a url")

            response = process_request(input_args)

            print 'Response:', response.json()

    except Exit:
        print 'GoodBye!'
Example #29
0
def cli(database, user, password, host, port):

    from pgcli import __file__ as package_root
    package_root = os.path.dirname(package_root)

    default_config = os.path.join(package_root, 'pgclirc')
    # Write default config.
    write_default_config(default_config, '~/.pgclirc')

    # Load config.
    config = load_config('~/.pgclirc')

    # Connect to the database.
    try:
        pgexecute = PGExecute(database, user, password, host, port)
    except Exception as e:
        click.secho(e.message, err=True, fg='red')
        exit(1)
    layout = Layout(before_input=DefaultPrompt('%s> ' % database),
            menus=[CompletionsMenu()],
            lexer=SqlLexer)
    completer = PGCompleter(config.getboolean('main', 'smart_completion'))
    completer.extend_special_commands(pgexecute.special_commands.keys())
    completer.extend_table_names(pgexecute.tables())
    completer.extend_column_names(pgexecute.all_columns())
    line = Line(completer=completer,
            history=FileHistory(os.path.expanduser('~/.pgcli-history')))
    cli = CommandLineInterface(style=PGStyle, layout=layout, line=line)

    try:
        while True:
            document = cli.read_input(on_exit=AbortAction.RAISE_EXCEPTION)
            try:
                rows, headers, status = pgexecute.run(document.text)
                if rows:
                    print(tabulate(rows, headers, tablefmt='psql'))
                print(status)
            except Exception as e:
                click.secho(e.message, err=True, fg='red')
    except Exit:
        print ('GoodBye!')
    def __init__(self, style):
        self._commands = {}
        for d in dir(self.__class__):
            if d.startswith('do_'):
                name = d[3:]
                func = getattr(self, d)
                doc = textwrap.dedent(func.__doc__ or '')
                self._commands[name] = (func, doc)

        self._history = InMemoryHistory()

        self._application = create_prompt_application(
            get_prompt_tokens=self.get_prompt_tokens,
            style=style,
            on_abort=AbortAction.RETURN_NONE,
            history=self._history)

        self._cli = CommandLineInterface(application=self._application,
                                         output=create_output(true_color=True),
                                         eventloop=create_asyncio_eventloop())

        self._style = style