Ejemplo n.º 1
0
def cli(url, http_options):
    click.echo('Version: %s' % __version__)

    copied, config_path = config.initialize()
    if copied:
        click.echo('Config file not found. Initialized a new one: %s' %
                   config_path)

    cfg = config.load()

    # Override pager/less options
    os.environ['PAGER'] = cfg['pager']
    os.environ['LESS'] = '-RXF'

    url = fix_incomplete_url(url)
    context = Context(url)

    output_style = cfg.get('output_style')
    if output_style:
        context.options['--style'] = output_style

    # For prompt-toolkit
    history = InMemoryHistory()
    lexer = PygmentsLexer(HttpPromptLexer)
    completer = HttpPromptCompleter(context)
    try:
        style = get_style_by_name(cfg['command_style'])
    except ClassNotFound:
        style = style_from_pygments(Solarized256Style)
    else:
        style = style_from_pygments(style)

    listener = ExecutionListener(cfg)

    # Execute HTTPie options from CLI or load from last context
    if len(sys.argv) > 1:
        http_options = [smart_quote(a) for a in http_options]
        execute(' '.join(http_options), context, listener=listener)
    else:
        load_context(context)

    while True:
        try:
            text = prompt('%s> ' % context.url,
                          completer=completer,
                          lexer=lexer,
                          style=style,
                          history=history,
                          auto_suggest=AutoSuggestFromHistory(),
                          on_abort=AbortAction.RETRY)
        except EOFError:
            break  # Control-D pressed
        else:
            execute(text, context, listener=listener)
            if context.should_exit:
                break

    click.echo("Goodbye!")
Ejemplo n.º 2
0
def cli(url, http_options):
    click.echo('Version: %s' % __version__)

    # Override less options
    os.environ['LESS'] = '-RXF'

    url = fix_incomplete_url(url)
    context = Context(url)

    # For prompt-toolkit
    history = InMemoryHistory()
    lexer = PygmentsLexer(HttpPromptLexer)
    completer = HttpPromptCompleter(context)
    style = style_from_pygments(get_style_by_name('monokai'))

    # Execute default http options.
    execute(' '.join(http_options), context)

    while True:
        try:
            text = prompt('%s> ' % context.url,
                          completer=completer,
                          lexer=lexer,
                          style=style,
                          history=history)
        except EOFError:
            break  # Control-D pressed
        else:
            execute(text, context)
            if context.should_exit:
                break

    click.echo("Goodbye!")
Ejemplo n.º 3
0
def repl(parser, interpreter, style_name='default'):
    registry = load_key_bindings()

    @registry.add_binding(Keys.Escape, Keys.Enter)  # meta-enter/alt-enter
    def _(event):
        '''Evaluate the buffer
        '''
        code = buffers[DEFAULT_BUFFER].text
        try:
            ast = parser.parse(code)
        except (UnexpectedToken, UnexpectedInput) as e:
            toolbar_value = str(e)
            return

        try:
            start_eval_time = time.time()
            retval = interpreter.eval(ast)
        except Exception as e:
            toolbar_value = "Error: %s" % e.args
            return
        else:
            buffers['RESULT'].text = str(retval)
            toolbar_value = "Time: {:0.4f}, Value: {}".format(
                time.time() - start_eval_time, str(retval))

    @registry.add_binding(Keys.ControlC, eager=True)
    @registry.add_binding(Keys.ControlQ, eager=True)
    def _(event):
        '''Exit the REPL
        '''
        event.cli.set_return_value(None)

    buffers = {
        DEFAULT_BUFFER: Buffer(is_multiline=True),
        'RESULT': Buffer(is_multiline=True),
    }
    style = style_from_pygments(get_style_by_name(style_name))

    application = Application(layout=layout,
                              buffers=buffers,
                              mouse_support=True,
                              style=style,
                              use_alternate_screen=True,
                              key_bindings_registry=registry)

    eventloop = create_eventloop()

    try:
        cli = CommandLineInterface(application=application,
                                   eventloop=eventloop)
        cli.run()

    finally:
        eventloop.close()
Ejemplo n.º 4
0
def cli():
    history = InMemoryHistory()
    style = style_from_pygments(get_style_by_name('monokai'))
    lexer = PygmentsLexer(DiscogsCliLexer)
    completer = Completer(fuzzy_match=False, text_utils=TextUtils())

    SYNTAX = 'Syntax: ogs <command> [options]'

    click.secho('     _ _                                    _ _ ',
                fg='yellow')
    click.secho('  __| (_)___  ___ ___   __ _ ___        ___| (_)',
                fg='yellow')
    click.secho(' / _` | / __|/ __/ _ \ / _` / __|_____ / __| | |',
                fg='yellow')
    click.secho('| (_| | \__ \ (_| (_) | (_| \__ \_____| (__| | |',
                fg='yellow')
    click.secho(' \__,_|_|___/\___\___/ \__, |___/      \___|_|_|',
                fg='yellow')
    click.secho('                       |___/', fg='yellow')

    click.echo('Version:' + __version__)
    click.echo(SYNTAX)

    while True:

        try:
            text = prompt('discogs-cli >>> ',
                          style=style,
                          history=history,
                          lexer=lexer,
                          completer=completer,
                          complete_while_typing=Always())
        except EOFError:
            break

        if text in EXIT:
            break

        if text.startswith(TOKEN):
            execute(text)
        else:
            click.secho('Guru meditation error. ' + SYNTAX, fg='red')
Ejemplo n.º 5
0
    def run_cli(self):
        iterations = 0
        sqlexecute = self.sqlexecute
        logger = self.logger
        self.configure_pager()

        if self.smart_completion:
            self.refresh_completions()

        author_file = os.path.join(PACKAGE_ROOT, 'AUTHORS')
        sponsor_file = os.path.join(PACKAGE_ROOT, 'SPONSORS')

        key_binding_manager = mycli_bindings()

        if not self.less_chatty:
            print('Version:', __version__)
            print('Chat: https://gitter.im/dbcli/mycli')
            print('Mail: https://groups.google.com/forum/#!forum/mycli-users')
            print('Home: http://mycli.net')
            print('Thanks to the contributor -',
                  thanks_picker([author_file, sponsor_file]))

        def prompt_tokens(cli):
            prompt = self.get_prompt(self.prompt_format)
            if self.prompt_format == self.default_prompt and len(
                    prompt) > self.max_len_prompt:
                prompt = self.get_prompt('\\d> ')
            return [(Token.Prompt, prompt)]

        def get_continuation_tokens(cli, width):
            continuation_prompt = self.get_prompt(
                self.prompt_continuation_format)
            return [(Token.Continuation, ' ' *
                     (width - len(continuation_prompt)) + continuation_prompt)]

        def show_suggestion_tip():
            return iterations < 2

        def one_iteration(document=None):
            if document is None:
                document = self.cli.run()

                special.set_expanded_output(False)

                try:
                    document = self.handle_editor_command(self.cli, document)
                except RuntimeError as e:
                    logger.error("sql: %r, error: %r", document.text, e)
                    logger.error("traceback: %r", traceback.format_exc())
                    self.echo(str(e), err=True, fg='red')
                    return

            if not document.text.strip():
                return

            if self.destructive_warning:
                destroy = confirm_destructive_query(document.text)
                if destroy is None:
                    pass  # Query was not destructive. Nothing to do here.
                elif destroy is True:
                    self.echo('Your call!')
                else:
                    self.echo('Wise choice!')
                    return

            # 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)

                special.write_tee(
                    self.get_prompt(self.prompt_format) + document.text)
                if self.logfile:
                    self.logfile.write('\n# %s\n' % datetime.now())
                    self.logfile.write(document.text)
                    self.logfile.write('\n')

                successful = False
                start = time()
                res = sqlexecute.run(document.text)
                self.formatter.query = document.text
                successful = True
                result_count = 0
                for title, cur, headers, status in res:
                    logger.debug("headers: %r", headers)
                    logger.debug("rows: %r", cur)
                    logger.debug("status: %r", status)
                    threshold = 1000
                    if (is_select(status) and cur
                            and cur.rowcount > threshold):
                        self.echo(
                            'The result set has more than {} rows.'.format(
                                threshold),
                            fg='red')
                        if not click.confirm('Do you want to continue?'):
                            self.echo("Aborted!", err=True, fg='red')
                            break

                    if self.auto_vertical_output:
                        max_width = self.cli.output.get_size().columns
                    else:
                        max_width = None

                    formatted = self.format_output(
                        title, cur, headers, special.is_expanded_output(),
                        max_width)

                    t = time() - start
                    try:
                        if result_count > 0:
                            self.echo('')
                        try:
                            self.output(formatted, status)
                        except KeyboardInterrupt:
                            pass
                        if special.is_timing_enabled():
                            self.echo('Time: %0.03fs' % t)
                    except KeyboardInterrupt:
                        pass

                    start = time()
                    result_count += 1
                    mutating = mutating or is_mutating(status)
                special.unset_once_if_written()
            except EOFError as e:
                raise e
            except KeyboardInterrupt:
                # get last connection id
                connection_id_to_kill = sqlexecute.connection_id
                logger.debug("connection id to kill: %r",
                             connection_id_to_kill)
                # Restart connection to the database
                sqlexecute.connect()
                try:
                    for title, cur, headers, status in sqlexecute.run(
                            'kill %s' % connection_id_to_kill):
                        status_str = str(status).lower()
                        if status_str.find('ok') > -1:
                            logger.debug(
                                "cancelled query, connection id: %r, sql: %r",
                                connection_id_to_kill, document.text)
                            self.echo("cancelled query", err=True, fg='red')
                except Exception as e:
                    self.echo(
                        'Encountered error while cancelling query: {}'.format(
                            e),
                        err=True,
                        fg='red')
            except NotImplementedError:
                self.echo('Not Yet Implemented.', fg="yellow")
            except OperationalError as e:
                logger.debug("Exception: %r", e)
                if (e.args[0] in (2003, 2006, 2013)):
                    logger.debug('Attempting to reconnect.')
                    self.echo('Reconnecting...', fg='yellow')
                    try:
                        sqlexecute.connect()
                        logger.debug('Reconnected successfully.')
                        one_iteration(document)
                        return  # OK to just return, cuz the recursion call runs to the end.
                    except OperationalError as e:
                        logger.debug('Reconnect failed. e: %r', e)
                        self.echo(str(e), err=True, fg='red')
                        # If reconnection failed, don't proceed further.
                        return
                else:
                    logger.error("sql: %r, error: %r", document.text, e)
                    logger.error("traceback: %r", traceback.format_exc())
                    self.echo(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())
                self.echo(str(e), err=True, fg='red')
            else:
                if is_dropping_database(document.text, self.sqlexecute.dbname):
                    self.sqlexecute.dbname = None
                    self.sqlexecute.connect()

                # Refresh the table names and column names if necessary.
                if need_completion_refresh(document.text):
                    self.refresh_completions(
                        reset=need_completion_reset(document.text))
            finally:
                if self.logfile is False:
                    self.echo("Warning: This query was not logged.",
                              err=True,
                              fg='red')
            query = Query(document.text, successful, mutating)
            self.query_history.append(query)

        get_toolbar_tokens = create_toolbar_tokens_func(
            self.completion_refresher.is_refreshing, show_suggestion_tip)

        layout = create_prompt_layout(
            lexer=MyCliLexer,
            multiline=True,
            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,
            extra_input_processors=[
                ConditionalProcessor(
                    processor=HighlightMatchingBracketProcessor(
                        chars='[](){}'),
                    filter=HasFocus(DEFAULT_BUFFER) & ~IsDone())
            ],
            reserve_space_for_menu=self.get_reserved_space())
        with self._completer_lock:
            buf = CLIBuffer(always_multiline=self.multi_line,
                            completer=self.completer,
                            history=FileHistory(
                                os.path.expanduser(
                                    os.environ.get('MYCLI_HISTFILE',
                                                   '~/.mycli-history'))),
                            auto_suggest=AutoSuggestFromHistory(),
                            complete_while_typing=Always(),
                            accept_action=AcceptAction.RETURN_DOCUMENT)

            if self.key_bindings == 'vi':
                editing_mode = EditingMode.VI
            else:
                editing_mode = EditingMode.EMACS

            application = Application(
                style=style_from_pygments(style_cls=self.output_style),
                layout=layout,
                buffer=buf,
                key_bindings_registry=key_binding_manager.registry,
                on_exit=AbortAction.RAISE_EXCEPTION,
                on_abort=AbortAction.RETRY,
                editing_mode=editing_mode,
                ignore_case=True)
            self.cli = CommandLineInterface(application=application,
                                            eventloop=create_eventloop())

        try:
            while True:
                one_iteration()
                iterations += 1
        except EOFError:
            special.close_tee()
            if not self.less_chatty:
                self.echo('Goodbye!')
Ejemplo n.º 6
0
def cli(spec, url, http_options):
    click.echo('Version: %s' % __version__)

    copied, config_path = config.initialize()
    if copied:
        click.echo('Config file not found. Initialized a new one: %s' %
                   config_path)

    cfg = config.load()

    # Override pager/less options
    os.environ['PAGER'] = cfg['pager']
    os.environ['LESS'] = '-RXF'

    if spec:
        f = urlopen(spec)
        try:
            content = f.read().decode('utf-8')
            try:
                spec = json.loads(content)
            except json.JSONDecodeError:
                click.secho("Warning: Specification file '%s' is not JSON" %
                            spec,
                            err=True,
                            fg='red')
                spec = None
        finally:
            f.close()

    url = fix_incomplete_url(url)
    context = Context(url, spec=spec)

    output_style = cfg.get('output_style')
    if output_style:
        context.options['--style'] = output_style

    # For prompt-toolkit
    history = InMemoryHistory()
    lexer = PygmentsLexer(HttpPromptLexer)
    completer = HttpPromptCompleter(context)
    try:
        style_class = get_style_by_name(cfg['command_style'])
    except ClassNotFound:
        style_class = Solarized256Style
    style = style_from_pygments(style_class)

    listener = ExecutionListener(cfg)

    # Execute HTTPie options from CLI or load from last context
    if len(sys.argv) > 1:
        http_options = [smart_quote(a) for a in http_options]
        execute(' '.join(http_options), context, listener=listener)
    else:
        load_context(context)

    while True:
        try:
            text = prompt('%s> ' % context.url,
                          completer=completer,
                          lexer=lexer,
                          style=style,
                          history=history,
                          auto_suggest=AutoSuggestFromHistory(),
                          on_abort=AbortAction.RETRY,
                          vi_mode=cfg['vi'])
        except EOFError:
            break  # Control-D pressed
        else:
            execute(text, context, listener=listener, style=style_class)
            if context.should_exit:
                break

    click.echo("Goodbye!")
Ejemplo n.º 7
0
def cli(spec, env, url, http_options):
    click.echo('Version: %s' % __version__)

    copied, config_path = config.initialize()
    if copied:
        click.echo('Config file not found. Initialized a new one: %s' %
                   config_path)

    cfg = config.load()

    # Override pager/less options
    os.environ['PAGER'] = cfg['pager']
    os.environ['LESS'] = '-RXF'

    if spec:
        f = urlopen(spec)
        try:
            content = f.read().decode('utf-8')
            try:
                spec = json.loads(content)
            except json.JSONDecodeError:
                try:
                    spec = yaml.load(content, Loader=yaml.SafeLoader)
                except yaml.YAMLError:
                    click.secho(
                        "Warning: Specification file '%s' is neither valid JSON nor YAML"
                        % spec,
                        err=True,
                        fg='red')
                    spec = None
        finally:
            f.close()
    else:
        spec = "https://redfish.dmtf.org/schemas/openapi.yaml"
        click.echo(
            "Loading current Redfish OpenAPI schema from '%s' by default; use --spec option on launch if needed to override"
            % spec)
        f = urlopen(spec)
        content = f.read().decode('utf-8')
        try:
            spec = yaml.load(content, Loader=yaml.SafeLoader)
        except yaml.YAMLError:
            click.secho("Warning: Specification file '%s' is not valid YAML" %
                        spec,
                        err=True,
                        fg='red')
            spec = None
        finally:
            f.close()

    if url:
        url = fix_incomplete_url(url)
    context = Context(url, spec=spec)

    output_style = cfg.get('output_style')
    if output_style:
        context.options['--style'] = output_style

    # For prompt-toolkit
    history = FileHistory(os.path.join(get_data_dir(), 'history'))
    lexer = PygmentsLexer(HttpPromptLexer)
    completer = HttpPromptCompleter(context)
    try:
        style_class = get_style_by_name(cfg['command_style'])
    except ClassNotFound:
        style_class = Solarized256Style
    style = style_from_pygments(style_class)

    listener = ExecutionListener(cfg)

    if len(sys.argv) == 1:
        # load previous context if nothing defined
        load_context(context)
    else:
        if env:
            load_context(context, env)
            if url:
                # Overwrite the env url if not default
                context.url = url

        if http_options:
            # Execute HTTPie options from CLI (can overwrite env file values)
            http_options = [smart_quote(a) for a in http_options]
            execute(' '.join(http_options), context, listener=listener)

    while True:
        try:
            text = prompt('%s> ' % context.url,
                          completer=completer,
                          lexer=lexer,
                          style=style,
                          history=history,
                          auto_suggest=AutoSuggestFromHistory(),
                          on_abort=AbortAction.RETRY,
                          vi_mode=cfg['vi'])
        except EOFError:
            break  # Control-D pressed
        else:
            execute(text, context, listener=listener, style=style_class)
            if context.should_exit:
                break

    click.echo("Goodbye!")
Ejemplo n.º 8
0
    def _build_cli(self, history):
        key_binding_manager = cli_bindings()

        def prompt_tokens(cli):
            prompt = self.get_prompt(self.prompt)
            if len(prompt) > self.MAX_LEN_PROMPT:
                prompt = self.get_prompt('\\r:\\d> ')
            return [(Token.Prompt, prompt)]

        def get_continuation_tokens(cli, width):
            prompt = self.get_prompt(self.prompt_continuation_format)
            token = (Token.Continuation, ' ' * (width - len(prompt)) + prompt)
            return [token]

        def show_suggestion_tip():
            return self.iterations < 2

        get_toolbar_tokens = create_toolbar_tokens_func(
            self.completion_refresher.is_refreshing, show_suggestion_tip)

        layout = create_prompt_layout(
            lexer=Lexer,
            multiline=True,
            get_prompt_tokens=prompt_tokens,
            get_continuation_tokens=get_continuation_tokens,
            get_bottom_toolbar_tokens=get_toolbar_tokens,
            display_completions_in_columns=False,
            extra_input_processors=[
                ConditionalProcessor(
                    processor=HighlightMatchingBracketProcessor(
                        chars='[](){}'),
                    filter=HasFocus(DEFAULT_BUFFER) & ~IsDone())
            ],
            reserve_space_for_menu=self.get_reserved_space())

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

            if self.key_bindings == 'vi':
                editing_mode = EditingMode.VI
            else:
                editing_mode = EditingMode.EMACS

            application = Application(
                style=style_from_pygments(style_cls=self.output_style),
                layout=layout,
                buffer=buf,
                key_bindings_registry=key_binding_manager.registry,
                on_exit=AbortAction.RAISE_EXCEPTION,
                on_abort=AbortAction.RETRY,
                editing_mode=editing_mode,
                ignore_case=True)

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

            return cli
Ejemplo n.º 9
0
    def __init__(self):
        self.command_parser = BrewPiCommandParser(self)

        self.buffers = {
            DEFAULT_BUFFER:
            Buffer(completer=command_completer,
                   enable_history_search=True,
                   history=InMemoryHistory(),
                   accept_action=AcceptAction(self.command_parser.parse)),
            'MESSAGES':
            Buffer(),
            'RESULT':
            Buffer(),
            'STATE':
            Buffer(),
        }

        self.registry = load_key_bindings()
        self.registry.add_binding(Keys.ControlC,
                                  eager=True)(self._on_request_shutdown)
        self.registry.add_binding(Keys.ControlQ,
                                  eager=True)(self._on_request_shutdown)

        self.layout = HSplit([
            # One window that holds the BufferControl with the default buffer on the
            # left.
            VSplit([
                HSplit([
                    Window(content=TokenListControl(get_tokens=lambda cli: [(
                        Token.Title, 'Command Result')]),
                           height=D.exact(1)),
                    Window(content=BufferControl(buffer_name='RESULT'),
                           wrap_lines=True,
                           left_margins=[ScrollbarMargin()]),
                ]),
                Window(width=D.exact(1),
                       content=FillControl('|', token=Token.Line)),
                HSplit([
                    Window(content=TokenListControl(get_tokens=lambda cli: [(
                        Token.Title, 'Raw Protocol Messages')]),
                           height=D.exact(1)),
                    Window(
                        content=BufferControl(buffer_name='MESSAGES',
                                              lexer=PygmentsLexer(JsonLexer)),
                        wrap_lines=True,
                        left_margins=[NumberredMargin()],
                        right_margins=[ScrollbarMargin()])
                ])
            ]),
            VSplit([
                Window(content=TokenListControl(
                    get_tokens=self.get_prompt_tokens),
                       height=D.exact(1),
                       dont_extend_width=True),
                Window(content=BufferControl(buffer_name=DEFAULT_BUFFER),
                       height=D.exact(1),
                       dont_extend_height=True),
            ]),
            Window(content=BufferControl(buffer_name='STATE'),
                   height=D.exact(1),
                   dont_extend_height=True)
        ])

        super().__init__(
            layout=self.layout,
            buffers=self.buffers,
            key_bindings_registry=self.registry,
            mouse_support=True,
            style=style_from_pygments(
                get_style_by_name('emacs'),
                style_dict={
                    Token.Toolbar:
                    '#ffffff bg:#333333',
                    Token.Title:
                    '#ffffff bg:#000088',
                    # User input.
                    Token:
                    '#ff0066',

                    # Prompt.
                    Token.Name:
                    '#884444 italic',
                    Token.At:
                    '#00aa00',
                    Token.Colon:
                    '#00aa00',
                    Token.Pound:
                    '#00aa00',
                    Token.Host:
                    '#000088 bg:#aaaaff',
                    Token.Path:
                    '#884444 underline',
                    # Make a selection reverse/underlined.
                    # (Use Control-Space to select.)
                    Token.SelectedText:
                    'reverse underline',
                }),
            use_alternate_screen=True)

        # BrewPi Stuff
        self.controller_manager = BrewPiControllerManager()
        self.msg_decoder = RawMessageDecoder()

        self.controller = None
Ejemplo n.º 10
0
 def __init__(self):
     self.ui_style = style_from_pygments(style_dict=ui_style)