Exemplo n.º 1
0
def main():
    cli = CommandLineInterface(layout=Layout(
        before_input=DefaultPrompt('Enter HTML: '),
        lexer=HtmlLexer))

    html_code_obj = cli.read_input()
    print('You said: ' + html_code_obj.text)
Exemplo n.º 2
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)
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()
Exemplo n.º 4
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)
Exemplo n.º 5
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
Exemplo n.º 6
0
def main():
    cli = CommandLineInterface(layout=layout,
                               style=TestStyle,
                               line=Line(validator=EmailValidator()))

    document = cli.read_input()
    print('You said: ' + document.text)
Exemplo n.º 7
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\n(second line)\n(third line)', token=Token.TopToolbar1, height=3),
            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 a multiline bottom toolbar\n(second line)\n(third line)', token=Token.BottomToolbar2, height=3),
        ],
        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)
Exemplo n.º 8
0
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()
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
Exemplo n.º 10
0
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
Exemplo n.º 11
0
def main():
    layout = Layout(before_input=DefaultPrompt('> '), lexer=HyLexer, menus=[CompletionMenu()])
    line = Line(completer=HyCompleter())
    cli = CommandLineInterface(layout=layout, line=line)
    try:
        while True:
            code_obj = cli.read_input(on_exit=AbortAction.RAISE_EXCEPTION)
            print 'You entered:', code_obj.text
    except Exit:
        print 'GoodBye!'
Exemplo n.º 12
0
def main():
    cli = CommandLineInterface(style=AnimalStyle,
                   layout=Layout(before_input=DefaultPrompt('Give some animals: '),
                                 menus=[CompletionMenu()]),
                   line=Line(completer=AnimalCompleter()),
                   create_async_autocompleters=True,
            )

    print('Press tab to complete')
    code_obj = cli.read_input()
    print('You said: ' + code_obj.text)
Exemplo n.º 13
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)
Exemplo n.º 14
0
    def _get_input(self):
        """
        Read PDB input. Return input text.
        """
        g = self._create_grammar()

        cli = CommandLineInterface(
            layout=Layout(
                before_input=PdbPrompt(self._get_current_pdb_commands()),
                show_tildes=True,
                min_height=15,
                lexer=GrammarLexer(
                    g,
                    tokens={'pdb_command': Token.PdbCommand},
                    lexers={'python_code': PythonLexer}
                ),
                after_input=CompletionHint(),
                menus=[CompletionsMenu()],
                top_toolbars=[],
                bottom_toolbars=[
                    SystemToolbar(),
                    ArgToolbar(),
                    SearchToolbar(),
                    SourceCodeToolbar(weakref.ref(self)),
                    ValidationToolbar(),
                    ShortcutsToolbar(),
                    PdbStatusToolbar(weakref.ref(self)),
                ]),
            line=Line(
                completer=GrammarCompleter(g, completers={
                    'enabled_breakpoint': BreakPointListCompleter(only_enabled=True),
                    'disabled_breakpoint': BreakPointListCompleter(only_disabled=True),
                    'alias_name': AliasCompleter(self),
                    'python_code': PythonCompleter(lambda: self.curframe.f_globals, lambda: self.curframe.f_locals),
                    'breakpoint': BreakPointListCompleter(),
                    'pdb_command': PdbCommandsCompleter(self),
                    'python_file': PythonFileCompleter(),
                    'python_function': PythonFunctionCompleter(self),
                }),
                history=self._cli_history,
                validator=GrammarValidator(g, {
                    'python_code': PythonValidator()
                }),
            ),
            key_binding_factories=[emacs_bindings, custom_pdb_key_bindings],
            style=PdbStyle)

        try:
            return cli.read_input(on_exit=AbortAction.RAISE_EXCEPTION).text
        except Exit:
            # Turn Control-D key press into a 'quit' command.
            return 'q'
Exemplo n.º 15
0
def main(database):
    connection = sqlite3.connect(database)
    layout = Layout(before_input=DefaultPrompt('> '),
                    lexer=SqlLexer, menus=[CompletionMenu()])
    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!'
Exemplo n.º 16
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!'
Exemplo n.º 17
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!"
Exemplo n.º 18
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!'
Exemplo n.º 19
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!')
Exemplo n.º 20
0
def get_input(message, raise_exception_on_abort=False, multiline=False,
        is_password=False, vi_mode=False):
    """
    Replacement for `raw_input`.
    Ask for input, return the answer.
    This returns `None` when Ctrl-D was pressed.
    """
    layout = Layout(
        before_input=DefaultPrompt(message),
        input_processors=([PasswordProcessor()] if is_password else []))

    cli = CommandLineInterface(
        layout=layout,
        line=Line(is_multiline=multiline),
        key_binding_factories=[(vi_bindings if vi_mode else emacs_bindings)])

    on_abort = AbortAction.RAISE_EXCEPTION if raise_exception_on_abort else AbortAction.RETURN_NONE
    code = cli.read_input(on_abort=on_abort, on_exit=AbortAction.IGNORE)

    if code:
        return code.text
Exemplo n.º 21
0
def main():
    cli = CommandLineInterface(layout=Layout(before_input=ClockPrompt()))

    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 cli.is_reading_input:
                time.sleep(1)
                cli.request_redraw()

        cli.run_in_executor(run)
    cli.onReadInputStart += on_read_start

    code_obj = cli.read_input()
    print('You said: ' + code_obj.text)
Exemplo n.º 22
0
def main():
    cli = CommandLineInterface(layout=Layout(before_input=ClockPrompt()))

    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 cli.is_reading_input:
                time.sleep(1)
                cli.request_redraw()

        cli.run_in_executor(run)

    cli.onReadInputStart += on_read_start

    code_obj = cli.read_input()
    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)
Exemplo n.º 24
0
    def run_cli(self):
        pgexecute = self.pgexecute
        prompt = '%s> ' % pgexecute.dbname
        logger = self.logger
        original_less_opts = self.adjust_less_opts()

        completer = self.completer
        self.refresh_completions()
        key_binding_manager = pgcli_bindings(self.vi_mode)
        print('Version:', __version__)
        print('Chat: https://gitter.im/dbcli/pgcli')
        print('Mail: https://groups.google.com/forum/#!forum/pgcli')
        print('Home: http://pgcli.com')

        layout = Layout(before_input=DefaultPrompt(prompt),
            menus=[CompletionsMenu(max_height=10)],
            lexer=PostgresLexer,
            bottom_toolbars=[PGToolbar(key_binding_manager)])
        buf = PGBuffer(always_multiline=self.multi_line, completer=completer,
                history=FileHistory(os.path.expanduser('~/.pgcli-history')))
        cli = CommandLineInterface(style=style_factory(self.syntax_style),
                layout=layout, buffer=buf,
                key_bindings_registry=key_binding_manager.registry)

        try:
            while True:
                cli.layout.before_input = DefaultPrompt(prompt)
                document = cli.read_input(on_exit=AbortAction.RAISE_EXCEPTION)

                # The reason we check here instead of inside the pgexecute is
                # because we want to raise the Exit exception which will be
                # caught by the try/except block that wraps the pgexecute.run()
                # statement.
                if quit_command(document.text):
                    raise Exit

                # Keep track of whether or not the query is mutating. In case
                # of a multi-statement query, the overall query is considered
                # mutating if any one of the component statements is mutating
                mutating = False

                try:
                    logger.debug('sql: %r', document.text)
                    successful = False
                    # Initialized to [] because res might never get initialized
                    # if an exception occurs in pgexecute.run(). Which causes
                    # finally clause to fail.
                    res = []
                    start = time()
                    # Run the query.
                    res = pgexecute.run(document.text)
                    duration = time() - start
                    successful = True
                    output = []
                    total = 0
                    for title, cur, headers, status in res:
                        logger.debug("headers: %r", headers)
                        logger.debug("rows: %r", cur)
                        logger.debug("status: %r", status)
                        start = time()
                        threshold = 1000
                        if (is_select(status) and
                                cur and cur.rowcount > threshold):
                            click.secho('The result set has more than %s rows.'
                                    % threshold, fg='red')
                            if not click.confirm('Do you want to continue?'):
                                click.secho("Aborted!", err=True, fg='red')
                                break
                        output.extend(format_output(title, cur, headers,
                            status, self.table_format))
                        end = time()
                        total += end - start
                        mutating = mutating or is_mutating(status)

                except KeyboardInterrupt:
                    # Restart connection to the database
                    pgexecute.connect()
                    logger.debug("cancelled query, sql: %r", document.text)
                    click.secho("cancelled query", err=True, fg='red')
                except NotImplementedError:
                    click.secho('Not Yet Implemented.', fg="yellow")
                except OperationalError as e:
                    reconnect = True
                    if ('server closed the connection' in utf8tounicode(e.args[0])):
                        reconnect = click.prompt('Connection reset. Reconnect (Y/n)',
                                show_default=False, type=bool, default=True)
                        if reconnect:
                            try:
                                pgexecute.connect()
                                click.secho('Reconnected!\nTry the command again.', fg='green')
                            except OperationalError as e:
                                click.secho(str(e), err=True, fg='red')
                    else:
                        logger.error("sql: %r, error: %r", document.text, e)
                        logger.error("traceback: %r", traceback.format_exc())
                        click.secho(str(e), err=True, fg='red')
                except Exception as e:
                    logger.error("sql: %r, error: %r", document.text, e)
                    logger.error("traceback: %r", traceback.format_exc())
                    click.secho(str(e), err=True, fg='red')
                else:
                    click.echo_via_pager('\n'.join(output))
                    if pgspecial.TIMING_ENABLED:
                        print('Command Time:', duration)
                        print('Format Time:', total)
                finally:
                    for cur, _, _ in res:
                        if hasattr(cur, 'close'):
                            cur.close()

                # Refresh the table names and column names if necessary.
                if need_completion_refresh(document.text):
                    prompt = '%s> ' % pgexecute.dbname
                    self.refresh_completions()

                # Refresh search_path to set default schema.
                if need_search_path_refresh(document.text):
                    logger.debug('Refreshing search path')
                    completer.set_search_path(pgexecute.search_path())
                    logger.debug('Search path: %r', completer.search_path)

                query = Query(document.text, successful, mutating)
                self.query_history.append(query)

        except Exit:
            print ('Goodbye!')
        finally:  # Reset the less opts back to original.
            logger.debug('Restoring env var LESS to %r.', original_less_opts)
            os.environ['LESS'] = original_less_opts
Exemplo n.º 25
0
    def run_cli(self):
        pgexecute = self.pgexecute
        prompt = '%s> ' % pgexecute.dbname
        logger = self.logger
        original_less_opts = self.adjust_less_opts()

        completer = self.completer
        self.refresh_completions()
        key_binding_manager = pgcli_bindings(self.vi_mode)
        print('Version:', __version__)
        print('Chat: https://gitter.im/amjith/pgcli')
        print('Mail: https://groups.google.com/forum/#!forum/pgcli')
        print('Home: http://pgcli.com')

        layout = Layout(before_input=DefaultPrompt(prompt),
                        menus=[CompletionsMenu(max_height=10)],
                        lexer=PostgresLexer,
                        bottom_toolbars=[PGToolbar(key_binding_manager)])
        buf = PGBuffer(always_multiline=self.multi_line,
                       completer=completer,
                       history=FileHistory(
                           os.path.expanduser('~/.pgcli-history')))
        cli = CommandLineInterface(
            style=style_factory(self.syntax_style),
            layout=layout,
            buffer=buf,
            key_bindings_registry=key_binding_manager.registry)

        try:
            while True:
                cli.layout.before_input = DefaultPrompt(prompt)
                document = cli.read_input(on_exit=AbortAction.RAISE_EXCEPTION)

                # The reason we check here instead of inside the pgexecute is
                # because we want to raise the Exit exception which will be
                # caught by the try/except block that wraps the pgexecute.run()
                # statement.
                if quit_command(document.text):
                    raise Exit

                # Keep track of whether or not the query is mutating. In case
                # of a multi-statement query, the overall query is considered
                # mutating if any one of the component statements is mutating
                mutating = False

                try:
                    logger.debug('sql: %r', document.text)
                    successful = False
                    # Initialized to [] because res might never get initialized
                    # if an exception occurs in pgexecute.run(). Which causes
                    # finally clause to fail.
                    res = []
                    start = time()
                    # Run the query.
                    res = pgexecute.run(document.text)
                    duration = time() - start
                    successful = True
                    output = []
                    total = 0
                    for title, cur, headers, status in res:
                        logger.debug("headers: %r", headers)
                        logger.debug("rows: %r", cur)
                        logger.debug("status: %r", status)
                        start = time()
                        threshold = 1000
                        if (is_select(status) and cur
                                and cur.rowcount > threshold):
                            click.secho(
                                'The result set has more than %s rows.' %
                                threshold,
                                fg='red')
                            if not click.confirm('Do you want to continue?'):
                                click.secho("Aborted!", err=True, fg='red')
                                break
                        output.extend(
                            format_output(title, cur, headers, status,
                                          self.table_format))
                        end = time()
                        total += end - start
                        mutating = mutating or is_mutating(status)

                except KeyboardInterrupt:
                    # Restart connection to the database
                    pgexecute.connect()
                    logger.debug("cancelled query, sql: %r", document.text)
                    click.secho("cancelled query", err=True, fg='red')
                except Exception as e:
                    logger.error("sql: %r, error: %r", document.text, e)
                    logger.error("traceback: %r", traceback.format_exc())
                    click.secho(str(e), err=True, fg='red')
                else:
                    click.echo_via_pager('\n'.join(output))
                    if pgspecial.TIMING_ENABLED:
                        print('Command Time:', duration)
                        print('Format Time:', total)
                finally:
                    for cur, _, _ in res:
                        if hasattr(cur, 'close'):
                            cur.close()

                # Refresh the table names and column names if necessary.
                if need_completion_refresh(document.text):
                    prompt = '%s> ' % pgexecute.dbname
                    self.refresh_completions()

                # Refresh search_path to set default schema.
                if need_search_path_refresh(document.text):
                    logger.debug('Refreshing search path')
                    completer.set_search_path(pgexecute.search_path())
                    logger.debug('Search path: %r', completer.search_path)

                query = Query(document.text, successful, mutating)
                self.query_history.append(query)

        except Exit:
            print('Goodbye!')
        finally:  # Reset the less opts back to original.
            logger.debug('Restoring env var LESS to %r.', original_less_opts)
            os.environ['LESS'] = original_less_opts
Exemplo n.º 26
0
def main():
    manager = KeyBindingManager(enable_system_prompt=True)

    D = LayoutDimension
    layout = HSplit([
        VSplit([
            Window(width=D(min=15, max=30, preferred=30),
                   content=FillControl('a', token=Token.A)),
            Window(width=D.exact(1),
                   content=FillControl('|', token=Token.Line)),
            Window(content=TokenListControl.static([(Token.HelloWorld, lipsum)])),
            Window(width=D.exact(1),
                   content=FillControl('|', token=Token.Line)),
            Window(content=BufferControl(lexer=PythonLexer,
                                         show_line_numbers=Always(),
                                         input_processors=[
                                                DefaultPrompt('python> '),
                                                AfterInput.static(' <python', token=Token.AfterInput),
                                         ]),
            ),
            Window(width=D.exact(1),
                   content=FillControl('|', token=Token.Line)),
            HSplit([
                Window(width=D(max=40),
                      height=D.exact(4),
                      content=FillControl('b', token=Token.B)),
                Window(width=D(max=40),
                      content=FillControl('f', token=Token.F)),
                Window(width=D.exact(30),
                      height=D.exact(2),
                      content=FillControl('c', token=Token.C)),
            ]),
            #CompletionsMenu(),
        ]),
        Window(height=D.exact(1),
              content=FillControl('-', token=Token.Line)),
        Window(height=D.exact(3),
              content=FillControl('d', token=Token.D)),
        SystemToolbar(),
        ArgToolbar(),
        CompletionsToolbar(),
        SearchToolbar(),
    ])

    layout = FloatContainer(
        content=layout,
        floats=[
            Float(xcursor=True,
                  ycursor=True,
                  content=VSplit([
                      Window(width=D.exact(5),
                             content=FillControl('f', token=Token.F)),
                      CompletionsMenu(),
                  ])
            ),
        ]
    )

    eventloop = create_eventloop()
    cli = CommandLineInterface(eventloop=eventloop,
                               layout=layout,
                               style=TestStyle,
                               key_bindings_registry=manager.registry,
                               buffer=Buffer(is_multiline=Always(), completer=TestCompleter()))
    cli.read_input()
    eventloop.close()
Exemplo n.º 27
0
def main():
    cli = CommandLineInterface(layout=Layout(
        before_input=DefaultPrompt('Enter HTML: '), lexer=HtmlLexer))

    html_code_obj = cli.read_input()
    print('You said: ' + html_code_obj.text)
Exemplo n.º 28
0
Arquivo: main.py Projeto: B-Rich/pgcli
def cli(database, user, password, host, port):
    if password:
        passwd = click.prompt('Password', hide_input=True, show_default=False,
                type=str)
    else:
        passwd = ''

    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(default_config, '~/.pgclirc')

    # Load config.
    config = load_config('~/.pgclirc', default_config)
    smart_completion = config.getboolean('main', 'smart_completion')
    multi_line = config.getboolean('main', 'multi_line')
    log_file = config.get('main', 'log_file')
    log_level = config.get('main', 'log_level')

    initialize_logging(log_file, log_level)

    original_less_opts = adjust_less_opts()

    _logger.debug('Launch Params: \n'
            '\tdatabase: %r'
            '\tuser: %r'
            '\tpassword: %r'
            '\thost: %r'
            '\tport: %r', database, user, passwd, host, port)

    # Connect to the database.
    try:
        pgexecute = PGExecute(database, user, passwd, host, port)
    except Exception as e:  # Connecting to a database could fail.
        _logger.debug('Database connection failed: %r.', e.message)
        click.secho(e.message, err=True, fg='red')
        exit(1)
    layout = Layout(before_input=DefaultPrompt('%s> ' % pgexecute.dbname),
            menus=[CompletionsMenu(max_height=10)],
            lexer=SqlLexer,
            bottom_toolbars=[
                PGToolbar()])
    completer = PGCompleter(smart_completion)
    completer.extend_special_commands(CASE_SENSITIVE_COMMANDS.keys())
    completer.extend_special_commands(NON_CASE_SENSITIVE_COMMANDS.keys())
    refresh_completions(pgexecute, completer)
    line = PGLine(always_multiline=multi_line, completer=completer,
            history=FileHistory(os.path.expanduser('~/.pgcli-history')))
    cli = CommandLineInterface(style=PGStyle, layout=layout, line=line,
            key_binding_factories=[emacs_bindings, pgcli_bindings])

    try:
        while True:
            cli.layout.before_input = DefaultPrompt('%s> ' % pgexecute.dbname)
            document = cli.read_input(on_exit=AbortAction.RAISE_EXCEPTION)

            # The reason we check here instead of inside the pgexecute is
            # because we want to raise the Exit exception which will be caught
            # by the try/except block that wraps the pgexecute.run() statement.
            if quit_command(document.text):
                raise Exit
            try:
                _logger.debug('sql: %r', document.text)
                res = pgexecute.run(document.text)
                output = []
                for rows, headers, status in res:
                    _logger.debug("headers: %r", headers)
                    _logger.debug("rows: %r", rows)
                    if rows:
                        output.append(tabulate(rows, headers, tablefmt='psql'))
                    if status:  # Only print the status if it's not None.
                        output.append(status)
                    _logger.debug("status: %r", status)
                    click.echo_via_pager('\n'.join(output))
            except Exception as e:
                _logger.debug("sql: %r, error: %r", document.text, e.message)
                click.secho(e.message, err=True, fg='red')

            # Refresh the table names and column names if necessary.
            if need_completion_refresh(document.text):
                completer.reset_completions()
                refresh_completions(pgexecute, completer)
    except Exit:
        print ('GoodBye!')
    finally:  # Reset the less opts back to original.
        _logger.debug('Restoring env var LESS to %r.', original_less_opts)
        os.environ['LESS'] = original_less_opts
Exemplo n.º 29
0
def main():
    manager = KeyBindingManager(enable_system_prompt=True)

    D = LayoutDimension
    layout = HSplit([
        VSplit([
            Window(width=D(min=15, max=30, preferred=30),
                   content=FillControl('a', token=Token.A)),
            Window(width=D.exact(1),
                   content=FillControl('|', token=Token.Line)),
            Window(content=TokenListControl.static([(Token.HelloWorld, lipsum)])),
            Window(width=D.exact(1),
                   content=FillControl('|', token=Token.Line)),
            Window(content=BufferControl(lexer=PythonLexer,
                                         show_line_numbers=AlwaysOn(),
                                         input_processors=[
                                                DefaultPrompt('python> '),
                                                AfterInput.static(' <python', token=Token.AfterInput),
                                         ]),
            ),
            Window(width=D.exact(1),
                   content=FillControl('|', token=Token.Line)),
            HSplit([
                Window(width=D(max=40),
                      height=D.exact(4),
                      content=FillControl('b', token=Token.B)),
                Window(width=D(max=40),
                      content=FillControl('f', token=Token.F)),
                Window(width=D.exact(30),
                      height=D.exact(2),
                      content=FillControl('c', token=Token.C)),
            ]),
            #CompletionsMenu(),
        ]),
        Window(height=D.exact(1),
              content=FillControl('-', token=Token.Line)),
        Window(height=D.exact(3),
              content=FillControl('d', token=Token.D)),
        SystemToolbar(),
        ArgToolbar(),
        CompletionsToolbar(),
        SearchToolbar(),
    ])

    layout = FloatContainer(
        content=layout,
        floats=[
            Float(xcursor=True,
                  ycursor=True,
                  content=VSplit([
                      Window(width=D.exact(5),
                             content=FillControl('f', token=Token.F)),
                      CompletionsMenu(),
                  ])
            ),
        ]
    )

    cli = CommandLineInterface(layout=layout,
                               style=TestStyle,
                               key_bindings_registry=manager.registry,
                               buffer=Buffer(is_multiline=True, completer=TestCompleter()))
    cli.read_input()
Exemplo n.º 30
0
if __name__ == '__main__':
    cli = CommandLineInterface(
        layout=Layout(before_input=DefaultPrompt('Shell> '),
                      #after_input=CompletionHint(grammar),
                      menus=[CompletionMenu()],
                      bottom_toolbars=[
                          StatusToolbar()
                      ]),
        line=Line(completer=ShellCompleter(grammar)),
        style=ExampleStyle)

    try:
        while True:
            try:
                document = cli.read_input(on_exit=AbortAction.RAISE_EXCEPTION)
                parse_info = get_parse_info(grammar, document)
            except InvalidCommandException:
                os.system(document.text)
                continue
            else:
                params = parse_info.get_variables()

                if params.get('command', '') == 'cd':
                    # Handle 'cd' command.
                    try:
                        os.chdir(params['directory'])
                    except OSError as e:
                        print(str(e))
                else:
                    os.system(document.text)
Exemplo n.º 31
0
        # Completion Menu
        Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000',
        Token.Menu.Completions.Completion: 'bg:#008888 #ffffff',
        Token.Menu.Completions.ProgressButton: 'bg:#003333',
        Token.Menu.Completions.ProgressBar: 'bg:#00aaaa',
    }


if __name__ == '__main__':
    cli = CommandLineInterface(layout=Layout(
        before_input=DefaultPrompt('(pdb) '),
        after_input=CompletionHint(grammar),
        menus=[CompletionsMenu()]),
                               line=Line(completer=ShellCompleter(grammar)),
                               style=PdbStyle)

    try:
        while True:
            document = cli.read_input(on_exit=AbortAction.RAISE_EXCEPTION)

            try:
                parse_info = get_parse_info(grammar, document)
            except InvalidCommandException:
                print('Invalid command\n')
                continue
            else:
                print(parse_info.get_variables())

    except Exit:
        pass