コード例 #1
0
ファイル: main.py プロジェクト: geekapk-r/temp-solution
    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(_):
            if self.dsn_alias and self.prompt_dsn_format is not None:
                prompt_format = self.prompt_dsn_format
            else:
                prompt_format = self.prompt_format

            prompt = self.get_prompt(prompt_format)

            if (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 = self.multiline_continuation_char * (width - 1) + ' '
            return [(Token.Continuation, continuation)]

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

        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 = PGBuffer(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
コード例 #2
0
def subprompt(entity, changed=False, ask_all=False, parent_prompt=None):
    global history
    if history is None:
        history = get_history(entity_name, InMemoryHistory())

    if ask_all:
        for k, v in form.items():
            if k not in entity:
                try:
                    if prompt_parameter(k, entity, entity_name, form,
                                        parent_prompt):
                        changed = True
                except KeyboardInterrupt:
                    entity[k] = None
                except EOFError:
                    exit_dshell()

    while True:
        try:
            text = prompt(
                f"{parent_prompt}{entity_name}('{entity['name']}')> ",
                history=history,
                auto_suggest=AutoSuggestFromHistory())
        except KeyboardInterrupt:
            continue
        except EOFError:
            exit_dshell(rc=1)
        try:
            namespace = parser.parse_args(shlex.split(text))
        except (ValueError, argparse.ArgumentError) as e:
            print(e)
            continue
        except SystemExit:
            continue

        if namespace.cmd == 'preview':
            dprint(entity)
        elif namespace.cmd == 'set':
            if namespace.parameter not in form.keys():
                dprint("Not a valid parameter. Available: " +
                       ', '.join(form.keys()))
            else:
                try:
                    if prompt_parameter(
                            namespace.parameter, entity, form,
                            f"{parent_prompt}{entity_name}('{entity['name']}')"
                    ):
                        changed = True
                except KeyboardInterrupt:
                    continue  # Control-C pressed. Try again.
                except EOFError:
                    exit_dshell(rc=1)
        elif namespace.cmd == 'submit':
            resp = ntwrk.post(f'api_1_0.{entity_name.replace("_", "")}list',
                              json=entity)
            dprint(resp)
            if resp.ok:
                return
        elif namespace.cmd == 'delete':
            if namespace.parameter not in form.keys():
                dprint("Not a valid parameter. Available: " +
                       ', '.join(form.keys()))
            else:
                entity.pop(namespace.parameter)
                changed = True
        elif namespace.cmd == 'dump':
            with open(namespace.file, 'w') as dumpfile:
                json.dump(entity, dumpfile, indent=4)
            changed = False
        elif namespace.cmd == 'exit':
            if changed:
                text = ''
                while text.lower().strip() not in ('y', 'n'):
                    text = prompt(
                        'If you exit you will lose the changes. Do you want to continue? (y/n): '
                    )
                if text.lower().strip() == 'y':
                    break
            else:
                break
コード例 #3
0
ファイル: PyHandler.py プロジェクト: asdfasadfasfa/Albert
def do_upload_file(user, command, randomuri):
    source = ""
    destination = ""
    if command == "upload-file":
        style = Style.from_dict({
            '': '#80d130',
        })
        session = PromptSession(history=FileHistory('%s/.upload-history' % PoshProjectDirectory), auto_suggest=AutoSuggestFromHistory(), style=style)
        try:
            source = session.prompt("Location file to upload: ", completer=FilePathCompleter(PayloadsDirectory, glob="*"))
            source = PayloadsDirectory + source
        except KeyboardInterrupt:
            return
        while not os.path.isfile(source):
            print("File does not exist: %s" % source)
            source = session.prompt("Location file to upload: ", completer=FilePathCompleter(PayloadsDirectory, glob="*"))
            source = PayloadsDirectory + source
        destination = session.prompt("Location to upload to: ")
    else:
        args = argp(command)
        source = args.source
        destination = args.destination
    try:

        destination = destination.replace("\\", "\\\\")
        print("")
        print("Uploading %s to %s" % (source, destination))
        uploadcommand = f"upload-file {source} {destination}"
        new_task(uploadcommand, user, randomuri)
    except Exception as e:
        print("Error with source file: %s" % e)
        traceback.print_exc()
コード例 #4
0
ファイル: main.py プロジェクト: sxiaoming2007/mycli
    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')

        history_file = os.path.expanduser(
            os.environ.get('MYCLI_HISTFILE', '~/.mycli-history'))
        if dir_path_exists(history_file):
            history = FileHistory(history_file)
        else:
            history = None
            self.echo(
                'Error: Unable to open the history file "{}". '
                'Your query history will not be saved.'.format(history_file),
                err=True,
                fg='red')

        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 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=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!')
コード例 #5
0
ファイル: main.py プロジェクト: migush/litecli
    def run_cli(self):
        iterations = 0
        sqlexecute = self.sqlexecute
        logger = self.logger
        self.configure_pager()
        self.refresh_completions()

        history_file = config_location() + "history"
        if dir_path_exists(history_file):
            history = FileHistory(history_file)
        else:
            history = None
            self.echo(
                'Error: Unable to open the history file "{}". '
                "Your query history will not be saved.".format(history_file),
                err=True,
                fg="red",
            )

        key_bindings = cli_bindings(self)

        if not self.less_chatty:
            print("Version:", __version__)
            print(
                "Mail: https://groups.google.com/forum/#!forum/litecli-users")
            print("Github: https://github.com/dbcli/litecli")
            # print("Home: https://litecli.com")

        def get_message():
            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 [("class:prompt", prompt)]

        def get_continuation(width, line_number, is_soft_wrap):
            continuation = " " * (width - 1) + " "
            return [("class:continuation", continuation)]

        def show_suggestion_tip():
            return iterations < 2

        def one_iteration(text=None):
            if text is None:
                try:
                    text = self.prompt_app.prompt()
                except KeyboardInterrupt:
                    return

                special.set_expanded_output(False)

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

            if not text.strip():
                return

            if self.destructive_warning:
                destroy = confirm_destructive_query(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", text)

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

                successful = False
                start = time()
                res = sqlexecute.run(text)
                self.formatter.query = 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 confirm("Do you want to continue?"):
                            self.echo("Aborted!", err=True, fg="red")
                            break

                    if self.auto_vertical_output:
                        max_width = self.prompt_app.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
                        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,
                                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(text)
                        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", 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", text, e)
                logger.error("traceback: %r", traceback.format_exc())
                self.echo(str(e), err=True, fg="red")
            else:
                if is_dropping_database(text, self.sqlexecute.dbname):
                    self.sqlexecute.dbname = None
                    self.sqlexecute.connect()

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

        get_toolbar_tokens = create_toolbar_tokens_func(
            self, show_suggestion_tip)

        if self.wider_completion_menu:
            complete_style = CompleteStyle.MULTI_COLUMN
        else:
            complete_style = CompleteStyle.COLUMN

        with self._completer_lock:

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

            self.prompt_app = PromptSession(
                lexer=PygmentsLexer(LiteCliLexer),
                reserve_space_for_menu=self.get_reserved_space(),
                message=get_message,
                prompt_continuation=get_continuation,
                bottom_toolbar=get_toolbar_tokens,
                complete_style=complete_style,
                input_processors=[
                    ConditionalProcessor(
                        processor=HighlightMatchingBracketProcessor(
                            chars="[](){}"),
                        filter=HasFocus(DEFAULT_BUFFER) & ~IsDone(),
                    )
                ],
                tempfile_suffix=".sql",
                completer=DynamicCompleter(lambda: self.completer),
                history=history,
                auto_suggest=AutoSuggestFromHistory(),
                complete_while_typing=True,
                multiline=cli_is_multiline(self),
                style=style_factory(self.syntax_style, self.cli_style),
                include_default_pygments_style=False,
                key_bindings=key_bindings,
                enable_open_in_editor=True,
                enable_system_prompt=True,
                enable_suspend=True,
                editing_mode=editing_mode,
                search_ignore_case=True,
            )

        try:
            while True:
                one_iteration()
                iterations += 1
        except EOFError:
            special.close_tee()
            if not self.less_chatty:
                self.echo("Goodbye!")
コード例 #6
0
    def _build_cli(self, history):
        """
            Builds prompt session.
            NOTE: PROMPT-SESSION USES THIS AS DEPENDENCY.
        """
        def get_message():
            prompt = self.get_prompt(self.prompt_format)
            return [(u'class:prompt', prompt)]

        def get_continuation(width, line_number, is_soft_wrap):
            """
                NOTE: updating parameters will cause prompt session to crash.
            """
            # pylint: disable=unused-argument
            continuation = self.multiline_continuation_char * (width - 1) + ' '
            return [(u'class:continuation', continuation)]

        get_toolbar_tokens = create_toolbar_tokens_func(self)

        if self.wider_completion_menu:
            complete_style = CompleteStyle.MULTI_COLUMN
        else:
            complete_style = CompleteStyle.COLUMN

        with self._completer_lock:
            self.prompt_session = PromptSession(
                message=get_message,
                style=style_factory(self.syntax_style, self.cli_style),

                # Layout options.
                lexer=PygmentsLexer(PostgresLexer),
                prompt_continuation=get_continuation,
                bottom_toolbar=get_toolbar_tokens,
                complete_style=complete_style,
                input_processors=[
                    ConditionalProcessor(
                        processor=HighlightMatchingBracketProcessor(
                            chars='[](){}'),
                        #pylint: disable=invalid-unary-operand-type
                        filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()),
                    # Render \t as 4 spaces instead of "^I"
                    TabsProcessor(char1=u' ', char2=u' ')
                ],
                reserve_space_for_menu=self.min_num_menu_lines,

                # Buffer options.
                multiline=mssql_is_multiline(self),
                completer=ThreadedCompleter(
                    DynamicCompleter(lambda: self.completer)),
                history=history,
                auto_suggest=AutoSuggestFromHistory(),
                complete_while_typing=True,

                # Key bindings.
                enable_system_prompt=True,
                enable_open_in_editor=True,

                # Other options.
                key_bindings=mssqlcli_bindings(self),
                editing_mode=EditingMode.VI
                if self.vi_mode else EditingMode.EMACS,
                search_ignore_case=True)

            return self.prompt_session
コード例 #7
0
    def __init__(self,
                 text='',
                 multiline=True,
                 password=False,
                 lexer=None,
                 completer=None,
                 accept_handler=None,
                 focusable=True,
                 wrap_lines=True,
                 read_only=False,
                 width=None,
                 height=None,
                 dont_extend_height=False,
                 dont_extend_width=False,
                 line_numbers=False,
                 scrollbar=False,
                 style='',
                 search_field=None,
                 preview_search=True,
                 history=InMemoryHistory(),
                 prompt=''):
        assert isinstance(text, six.text_type)
        assert search_field is None or isinstance(search_field, SearchToolbar)

        if search_field is None:
            search_control = None
        elif isinstance(search_field, SearchToolbar):
            search_control = search_field.control

        self.history = history

        self.buffer = Buffer(
            document=Document(text, 0),
            multiline=multiline,
            read_only=read_only,
            completer=completer,
            history=self.history,
            auto_suggest=AutoSuggestFromHistory(),
            enable_history_search=True,
            accept_handler=lambda buff: accept_handler and accept_handler())

        self.control = BufferControl(buffer=self.buffer,
                                     lexer=lexer,
                                     input_processors=[
                                         BeforeInput(
                                             prompt,
                                             style='class:text-area.prompt'),
                                     ],
                                     search_buffer_control=search_control,
                                     preview_search=preview_search,
                                     focusable=focusable)

        if multiline:
            if scrollbar:
                right_margins = [ScrollbarMargin(display_arrows=True)]
            else:
                right_margins = []
            if line_numbers:
                left_margins = [NumberedMargin()]
            else:
                left_margins = []
        else:
            wrap_lines = False  # Never wrap for single line input.
            height = D.exact(1)
            left_margins = []
            right_margins = []

        style = 'class:text-area ' + style

        self.window = Window(height=height,
                             width=width,
                             dont_extend_height=dont_extend_height,
                             dont_extend_width=dont_extend_width,
                             content=self.control,
                             style=style,
                             wrap_lines=wrap_lines,
                             left_margins=left_margins,
                             right_margins=right_margins)
コード例 #8
0
from __future__ import unicode_literals
from prompt_toolkit import prompt
from prompt_toolkit.history import FileHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.contrib.completers import WordCompleter

SQLCompleter = WordCompleter(
    ['select', 'from', 'insert', 'update', 'delete', 'drop'], ignore_case=True)

while True:
    user_input = prompt(
        'SQL>',
        history=FileHistory('history.txt'),
        auto_suggest=AutoSuggestFromHistory(),
        completer=SQLCompleter,
    )
    print(user_input)
コード例 #9
0
def implant_command_loop(implant_id, user):
    while (True):
        try:
            style = Style.from_dict({
                '': '#80d130',
            })
            session = PromptSession(history=FileHistory('%s/.implant-history' %
                                                        PoshProjectDirectory),
                                    auto_suggest=AutoSuggestFromHistory(),
                                    style=style)
            implant_id_orig = implant_id
            if ("-" in implant_id) or ("all" in implant_id) or (","
                                                                in implant_id):
                print(Colours.GREEN)
                prompt_commands = POSH_COMMANDS
                command = session.prompt("%s> " % implant_id,
                                         completer=FirstWordFuzzyWordCompleter(
                                             prompt_commands, WORD=True))
                if command == "back" or command == 'clear':
                    do_back(user, command)
                    return
            else:
                implant = get_implantbyid(implant_id)
                if not implant:
                    print_bad("Unrecognised implant id or command: %s" %
                              implant_id)
                    input("Press Enter to continue...")
                    clear()
                    return
                prompt_commands = POSH_COMMANDS
                if implant.Pivot.startswith('Python'):
                    prompt_commands = PY_COMMANDS
                if implant.Pivot.startswith('C#'):
                    prompt_commands = SHARP_COMMANDS
                if 'PB' in implant.Pivot:
                    style = Style.from_dict({
                        '': '#008ECC',
                    })
                    session = PromptSession(
                        history=FileHistory('%s/.implant-history' %
                                            PoshProjectDirectory),
                        auto_suggest=AutoSuggestFromHistory(),
                        style=style)
                    prompt_commands = SHARP_COMMANDS
                    print(Colours.BLUE)
                else:
                    print(Colours.GREEN)
                print("%s\\%s @ %s (PID:%s)" % (implant.Domain, implant.User,
                                                implant.Hostname, implant.PID))
                command = session.prompt(
                    "%s %s> " %
                    (get_implant_type_prompt_prefix(implant_id), implant_id),
                    completer=FirstWordFuzzyWordCompleter(prompt_commands,
                                                          WORD=True))
                if command == "back" or command == 'clear':
                    do_back(user, command)
                    return

            # if "all" run through all implants get_implants()
            if implant_id == "all":
                if command == "back" or command == 'clear':
                    do_back(user, command)
                    return
                allcommands = command
                if "\n" in command:
                    ri = input(
                        "Do you want to run commands separately? (Y/n) ")
                implants_split = get_implants()
                if implants_split:
                    for implant_details in implants_split:
                        # if "\n" in command run each command individually or ask the question if that's what they want to do
                        if "\n" in allcommands:
                            if ri.lower() == "y" or ri == "":
                                commands = allcommands.split('\n')
                                for command in commands:
                                    run_implant_command(
                                        command, implant_details.RandomURI,
                                        implant_id_orig, user)
                            else:
                                run_implant_command(command,
                                                    implant_details.RandomURI,
                                                    implant_id_orig, user)
                        else:
                            run_implant_command(command,
                                                implant_details.RandomURI,
                                                implant_id_orig, user)

            # if "separated list" against single uri
            elif "," in implant_id:
                allcommands = command
                if "\n" in command:
                    ri = input(
                        "Do you want to run commands separately? (Y/n) ")
                implant_split = implant_id.split(",")
                for split_implant_id in implant_split:
                    implant_randomuri = get_randomuri(split_implant_id)
                    # if "\n" in command run each command individually or ask the question if that's what they want to do
                    if "\n" in allcommands:
                        if ri.lower() == "y" or ri == "":
                            commands = allcommands.split('\n')
                            for command in commands:
                                run_implant_command(command, implant_randomuri,
                                                    implant_id_orig, user)
                        else:
                            run_implant_command(command, implant_randomuri,
                                                implant_id_orig, user)
                    else:
                        run_implant_command(command, implant_randomuri,
                                            implant_id_orig, user)

            # if "range" against single uri
            elif "-" in implant_id:
                allcommands = command
                if "\n" in command:
                    ri = input(
                        "Do you want to run commands separately? (Y/n) ")
                implant_split = implant_id.split("-")
                for range_implant_id in range(int(implant_split[0]),
                                              int(implant_split[1]) + 1):
                    try:
                        implant_randomuri = get_randomuri(range_implant_id)
                        # if "\n" in command run each command individually or ask the question if that's what they want to do
                        if "\n" in allcommands:
                            if ri.lower() == "y" or ri == "":
                                commands = allcommands.split('\n')
                                for command in commands:
                                    run_implant_command(
                                        command, implant_randomuri,
                                        implant_id_orig, user)
                            else:
                                run_implant_command(command, implant_randomuri,
                                                    implant_id_orig, user)
                        else:
                            run_implant_command(command, implant_randomuri,
                                                implant_id_orig, user)
                    except Exception:
                        print_bad("Unknown ImplantID")

            # else run against single uri
            else:
                allcommands = command
                if "\n" in command:
                    ri = input(
                        "Do you want to run commands separately? (Y/n) ")
                implant_randomuri = get_randomuri(implant_id)
                # if "\n" in command run each command individually or ask the question if that's what they want to do
                if "\n" in allcommands:
                    if ri.lower() == "y" or ri == "":
                        commands = allcommands.split('\n')
                        for command in commands:
                            run_implant_command(command, implant_randomuri,
                                                implant_id_orig, user)
                    else:
                        run_implant_command(command, implant_randomuri,
                                            implant_id_orig, user)
                else:
                    run_implant_command(command, implant_randomuri,
                                        implant_id_orig, user)

        except KeyboardInterrupt:
            continue
        except EOFError:
            new_c2_message("%s logged off." % user)
            sys.exit(0)
        except Exception as e:
            traceback.print_exc()
            print_bad(
                f"Error running against the selected implant ID, ensure you have typed the correct information: {e}"
            )
            return
コード例 #10
0
def implant_handler_command_loop(user, printhelp="", autohide=None):
    while (True):
        session = PromptSession(history=FileHistory('%s/.top-history' %
                                                    PoshProjectDirectory),
                                auto_suggest=AutoSuggestFromHistory())

        try:
            if user is not None:
                print("User: "******"%s%s" % (user, Colours.GREEN))
                print()

            C2 = get_c2server_all()
            killdate = datetime.strptime(C2.KillDate, '%Y-%m-%d').date()
            datedifference = number_of_days(date.today(), killdate)
            if datedifference < 8:
                print(Colours.RED +
                      ("\nKill Date is - %s - expires in %s days" %
                       (C2.KillDate, datedifference)))
                print(Colours.END)
                print()

            implants = get_implants()
            if implants:
                for implant in implants:
                    ID = implant.ImplantID
                    LastSeen = implant.LastSeen
                    Hostname = implant.Hostname
                    Domain = implant.Domain
                    URLID = implant.URLID
                    DomainUser = implant.User
                    Arch = implant.Arch
                    PID = implant.PID
                    Pivot = implant.Pivot
                    Sleep = implant.Sleep.strip()
                    Label = implant.Label

                    apmsuspendshut = False

                    pwrStatus = get_powerstatusbyrandomuri(implant.RandomURI)
                    if pwrStatus is not None:
                        if Label is not None:
                            Label += " "
                        else:
                            Label = ""
                        apmstatus = pwrStatus[2].lower()

                        if (apmstatus == "shutdown"):
                            Label += "SHTDWN "
                            apmsuspendshut = True
                        elif (apmstatus == "suspend"
                              or apmstatus == "querysuspend"):
                            Label += "SUSPND "
                            apmsuspendshut = True

                        if not apmsuspendshut:
                            if (pwrStatus[7]):
                                Label += "LOCKED "
                            if (not pwrStatus[8]):
                                Label += "SCRN OFF "

                            if (not pwrStatus[3]):
                                if (pwrStatus[6] is not None
                                        and pwrStatus[6].isdigit()):
                                    Label += ("DSCHRG: %s%% " % pwrStatus[6])
                                else:
                                    Label += ("DSCHRG ")

                    Pivot = get_implant_type_prompt_prefix(ID)
                    LastSeenTime = datetime.strptime(LastSeen,
                                                     "%Y-%m-%d %H:%M:%S")
                    LastSeenTimeString = datetime.strftime(
                        LastSeenTime, "%Y-%m-%d %H:%M:%S")
                    now = datetime.now()
                    if (Sleep.endswith('s')):
                        sleep_int = int(Sleep[:-1])
                    elif (Sleep.endswith('m')):
                        sleep_int = int(Sleep[:-1]) * 60
                    elif (Sleep.endswith('h')):
                        sleep_int = int(Sleep[:-1]) * 60 * 60
                    else:
                        print(Colours.RED)
                        print("Incorrect sleep format: %s" % Sleep)
                        print(Colours.GREEN)
                        continue
                    nowMinus3Beacons = now - timedelta(seconds=(sleep_int * 3))
                    nowMinus10Beacons = now - timedelta(seconds=(sleep_int *
                                                                 10))
                    nowMinus30Beacons = now - timedelta(seconds=(sleep_int *
                                                                 30))
                    sID = "[" + str(ID) + "]"
                    if not Label:
                        sLabel = ""
                    else:
                        Label = Label.strip()
                        sLabel = Colours.BLUE + "[" + Label + "]" + Colours.GREEN

                    if "C#;PB" in Pivot:
                        print(
                            Colours.BLUE +
                            "%s: Seen:%s | PID:%s | %s | PBind | %s\\%s @ %s (%s) %s %s"
                            % (sID.ljust(4), LastSeenTimeString, PID.ljust(5),
                               Sleep, Domain, DomainUser, Hostname, Arch,
                               Pivot, sLabel))
                    elif nowMinus30Beacons > LastSeenTime and autohide:
                        pass
                    elif nowMinus10Beacons > LastSeenTime:
                        print(
                            Colours.RED +
                            "%s: Seen:%s | PID:%s | %s | URLID: %s | %s\\%s @ %s (%s) %s %s"
                            % (sID.ljust(4), LastSeenTimeString, PID.ljust(5),
                               Sleep, URLID, Domain, DomainUser, Hostname,
                               Arch, Pivot, sLabel))
                    elif nowMinus3Beacons > LastSeenTime:
                        print(
                            Colours.YELLOW +
                            "%s: Seen:%s | PID:%s | %s | URLID: %s | %s\\%s @ %s (%s) %s %s"
                            % (sID.ljust(4), LastSeenTimeString, PID.ljust(5),
                               Sleep, URLID, Domain, DomainUser, Hostname,
                               Arch, Pivot, sLabel))
                    else:
                        print(
                            Colours.GREEN +
                            "%s: Seen:%s | PID:%s | %s | URLID: %s | %s\\%s @ %s (%s) %s %s"
                            % (sID.ljust(4), LastSeenTimeString, PID.ljust(5),
                               Sleep, URLID, Domain, DomainUser, Hostname,
                               Arch, Pivot, sLabel))
            else:
                now = datetime.now()
                print(Colours.RED + "No Implants as of: %s" %
                      now.strftime("%Y-%m-%d %H:%M:%S"))

            if printhelp:
                print(printhelp)

            command = session.prompt(
                "\nSelect ImplantID or ALL or Comma Separated List (Enter to refresh):: ",
                completer=FirstWordFuzzyWordCompleter(SERVER_COMMANDS,
                                                      WORD=True))
            print("")

            command = command.strip()
            if (command == "") or (command == "back") or (command == "clear"):
                do_back(user, command)
                continue
            if command.startswith("generate-reports"):
                do_generate_reports(user, command)
                continue
            if command.startswith("generate-csvs"):
                do_generate_csvs(user, command)
                continue
            if command.startswith("message "):
                do_message(user, command)
                continue
            if command.startswith("show-hosted-files"):
                do_show_hosted_files(user, command)
                continue
            if command.startswith("add-hosted-file"):
                do_add_hosted_file(user, command)
                continue
            if command.startswith("disable-hosted-file"):
                do_disable_hosted_file(user, command)
                continue
            if command.startswith("enable-hosted-file"):
                do_enable_hosted_file(user, command)
                continue
            if command.startswith("show-urls") or command.startswith(
                    "list-urls"):
                do_show_urls(user, command)
                continue
            if command.startswith("add-autorun"):
                do_add_autorun(user, command)
                continue
            if command.startswith("list-autorun"):
                do_list_autoruns(user, command)
                continue
            if command.startswith("del-autorun"):
                do_del_autorun(user, command)
                continue
            if command.startswith("nuke-autorun"):
                do_nuke_autoruns(user, command)
                continue
            if command.startswith("kill"):
                do_del_task(user, command)
                continue
            if command.startswith("show-serverinfo"):
                do_show_serverinfo(user, command)
                continue
            if command.startswith("turnoff-notifications"):
                do_turnoff_notifications(user, command)
                continue
            if command.startswith("turnon-notifications"):
                do_turnon_notifications(user, command)
                continue
            if command.startswith("set-pushover-applicationtoken"):
                do_set_pushover_applicationtoken(user, command)
                continue
            if command.startswith("set-pushover-userkeys"):
                do_set_pushover_userkeys(user, command)
                continue
            if command.startswith("get-killdate"):
                do_get_killdate(user, command)
                continue
            if command.startswith("set-killdate"):
                do_set_killdate(user, command)
                continue
            if command.startswith("set-defaultbeacon"):
                do_set_defaultbeacon(user, command)
                continue
            if command == "get-opsec-events":
                do_get_opsec_events(user, command)
                continue
            if command == "add-opsec-event":
                do_insert_opsec_events(user, command)
                continue
            if command == "del-opsec-event":
                do_del_opsec_events(user, command)
                continue
            if command.startswith("opsec"):
                do_opsec(user, command)
                continue
            if command.startswith("listmodules"):
                do_listmodules(user, command)
                continue
            if command.startswith('creds ') or command.strip() == "creds":
                do_creds(user, command)
                input("Press Enter to continue...")
                clear()
                continue
            if (command == "pwnself") or (command == "p"):
                do_pwnself(user, command)
                continue
            if command == "tasks":
                do_tasks(user, command)
                continue
            if command == "cleartasks":
                do_cleartasks(user, command)
                continue
            if command.startswith("quit"):
                do_quit(user, command)
                continue
            if command.startswith("createdaisypayload"):
                do_createdaisypayload(user, command)
                continue
            if command.startswith("createproxypayload"):
                do_createnewpayload(user, command)
                continue
            if command.startswith("createnewpayload"):
                do_createnewpayload(user, command)
                continue
            if command.startswith("createnewshellcode"):
                do_createnewpayload(user, command, shellcodeOnly=True)
                continue
            if command == "help":
                do_help(user, command)
                continue
            if command == "history":
                do_history(user, command)
                continue
            if command.startswith("use "):
                do_use(user, command)
            implant_command_loop(command, user)
        except KeyboardInterrupt:
            clear()
            continue
        except EOFError:
            new_c2_message("%s logged off." % user)
            sys.exit(0)
        except Exception as e:
            if 'unable to open database file' not in str(e):
                print_bad("Error: %s" % e)
                traceback.print_exc()
コード例 #11
0
from prompt_toolkit import prompt
from prompt_toolkit.history import InMemoryHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory

history = InMemoryHistory()
for word in ["apple", "banana", "orange", "grape", "pineapple"]:
    history.append(word)

while True:
    text = prompt('> ', history=history, auto_suggest=AutoSuggestFromHistory())
    print('You said: ', text)
コード例 #12
0
def main_loop():
    global system
    global author
    global metric
    global pre_from_unit
    global pre_to_unit
    global pre_value

    greet()

    drop_down = words + ['set', 'systems', 'authors', 'metrics', 'params', 'swap', 'from', 'to', 'exit', 'help']
    sorted(drop_down)
    droper = WordCompleter(drop_down)
    style1 = Style.from_dict({'': '#00FF00'})

    while(True):
        
        inp = session.prompt('You: ', auto_suggest=AutoSuggestFromHistory(), completer=droper, style=style1)
        print('')
        code, keyword = process_input(inp)
        print('Bot: ', end='')

        if(code == '' and keyword == ''):
            continue
        
        if(code == 'help'):
            help_rules()

        elif(code == 'systems'):
            show_systems()

        elif(code == 'metrics'):
            show_metrics()

        elif(code == 'authors'):
            show_authors()

        elif(code == 'params'):
            show_parameters()

        elif(code == 'set'):
            if(keyword == ''):
                print("Please enter the second parameter\n")
                continue
            elif(keyword in systems):
                system = keyword
            elif(keyword in metrics):
                metric = keyword
            elif(keyword in authors):
                author = keyword
                if(keyword == 'vaidyaka paribhasha pradeepa'):
                    author = 'vpp'
            else:
                print("Please check the spelling", keyword, 'not found\n')
                continue
            
            if(system == 'unani'):
                author = 'api'
                if(metric not in ['weight', 'volume']):
                    print('Unfortunately Unani system doesn\'t support', metric, '. It only supports weight and volume measures. Let me change the metric, to weight, for you.\n')
                    metric = 'weight'
            elif(system == 'siddha'):
                author = 'api'
            elif(system == 'ayurveda'):
                if (author in ['charaka', 'sharangadhara', 'rrs', 'vpp']):
                    if (metric != 'weight'):
                        metric = 'weight'
                        print(author.title(), 'has defined only weight metric. I\'ve changed the metric to weight\n')
                elif (author == 'sushruta'):
                    if (metric not in ['weight', 'time']):
                        metric = 'weight'
                        print(author.title(), 'has defined only weight and time metrics. Metric changed to weight.\n')
                elif (author == 'api'):
                    if (metric not in ['weight', 'time', 'length']):
                        metric = 'weight'
                        print(author.title(), 'has defined only weight, time and length metrics. Metric changed to weight.\n')
            
            show_parameters()

            pre_from_unit = default_unit_field[metric]['from_unit']
            pre_to_unit = default_unit_field[metric]['to_unit']

        elif(code == 'swap'):
            pre_from_unit, pre_to_unit = pre_to_unit, pre_from_unit
            print(convert())
        
        elif(code == 'from' or code == 'to'):
            if(keyword == ''):
                print("Please enter 'from / to' unit\n")
                continue
            elif(code == 'from'):
                pre_from_unit = keyword
            elif(code == 'to'):
                pre_to_unit = keyword

            try:
                unitfrom_value = data_field[system][author][metric][pre_from_unit]
            except:
                print('Oops! I couldn\'t find', pre_from_unit, 'in', system, author, metric, '.\n')
                continue

            try:
                unitto_value = data_field[system][author][metric][pre_to_unit]
            except:
                print('Oops! I couldn\'t find', pre_to_unit, 'in', system, author, metric, '.\n')
                continue
            
            if(unitfrom_value == 0):
                print('I believe', author, 'has not defined', pre_from_unit, 'unit in his metrics.\n')
                continue
            elif(unitto_value == 0):
                print('I believe', author, 'has not defined', pre_to_unit, 'unit in his metrics.\n')
                continue
            else:
                print(convert())
        
        elif(code == 'exit'):
            print("Bye, ^--^")
            sys.exit()
        
        else:
            try:
                pre_value = float(inp)
                print(convert())      
            except:
                print("Enter valid input\n")  
コード例 #13
0
 def mainLanHuntCLI():
     global balance, drone_task, drone_list
     balance = 0.0
     drone_list = False
     drone_task = "idle"
     lanhunt.initLanHuntCLI()
     lanhunt.initDrone()
     lanHuntCLI = PromptSession()
     while True:
         if battery > 10:
             lh_cmd = str(
                 lanHuntCLI.prompt(
                     lh_msg,
                     bottom_toolbar=lanhunt.bottom_toolbar,
                     refresh_interval=0.5,
                     style=lh_style,
                     auto_suggest=AutoSuggestFromHistory())).lower()
         else:
             print(
                 Fore.YELLOW +
                 "[LanHuntDroneGuard] Battery is low ! Drone is fly home..."
             )
             lh_cmd = "exit"
         if len(lh_cmd) > 16:
             lh_cmd = lh_cmd[:-(len(lh_cmd) - 16)]
         if lh_cmd == "":
             continue
         elif lh_cmd == "exit":
             print(Fore.YELLOW +
                   "All ETH is transfered to your main wallet")
             print(Fore.RED + "Closing connections...\nExiting..." + sr)
             drone_task = "exit"
             break
         elif lh_cmd == "help":
             for i in range(0, len(lanhunt.lh_cmd_list)):
                 print(Fore.YELLOW + lanhunt.lh_cmd_list[str(i)] + sr)
                 i += 1
         elif lh_cmd == "fly":
             try:
                 if drone_list == False and drone_list != "flied":
                     drone_task = "fly"
                 elif drone_list == False and drone_list == "flied":
                     print(
                         Fore.RED +
                         "\nDrone is already flied !\nPlease, perform a search to find the targets."
                         + sr)
             except Exception as e:
                 print(
                     Fore.RED +
                     "\nDrone is already flied !\nPlease, perform a search to find the targets.\n%s"
                     % str(e) + sr)
         elif lh_cmd == "hack":
             try:
                 if drone_list and drone_list != "flied":
                     drone_task = "hack"
                 else:
                     print(
                         Fore.RED +
                         "\nTarget list is empty !\nPlease, perform a search to find the targets."
                         + sr)
             except Exception as e:
                 print(
                     Fore.RED +
                     "\nTarget list is empty !\nPlease, perform a search to find the targets.\n%s"
                     % str(e) + sr)
         elif lh_cmd == "search":
             try:
                 if drone_list and drone_list != "flied":
                     print(
                         Fore.RED +
                         "\nTarget list is already exists !\nPlease, perform a hack to get their ETH."
                         + sr)
                 else:
                     drone_task = "search"
             except Exception as e:
                 drone_task = "search"
                 print("%s\n%s" % str(e))
         elif lh_cmd == "show_targets":
             try:
                 if drone_list and drone_list != "flied":
                     for i in range(0, len(drone_list)):
                         print(Style.NORMAL + Fore.GREEN +
                               "[Target: %d]" % i)
                         for param in drone_list[str(i)]:
                             print(Style.BRIGHT + str(param) + ": " +
                                   str(drone_list[str(i)][str(param)]))
                 else:
                     print(
                         Fore.RED +
                         "\nTarget list is empty !\nPlease, perform a search to find the targets."
                         + sr)
             except Exception as e:
                 print(
                     Fore.RED +
                     "\nTarget list is empty !\nPlease, perform a search to find the targets.\n%s"
                     % str(e) + sr)
         elif lh_cmd == "balance":
             print(Fore.BLUE + "Drone balance is: %s ETH" % str(balance))
         else:
             print(Fore.RED + "Command %s is not found !" % lh_cmd + sr)
     return balance
コード例 #14
0
    def __init__(self, my_app: "sqlApp") -> None:

        self.my_app = my_app
        self.search_field = SearchToolbar()
        history_file = config_location() + 'history'
        ensure_dir_exists(history_file)
        hist = ThreadedHistory(FileHistory(expanduser(history_file)))
        self.input_buffer = Buffer(
            name="defaultbuffer",
            tempfile_suffix=".py",
            multiline=MultilineFilter(self.my_app),
            history=hist,
            completer=ThreadedCompleter(self.my_app.completer),
            auto_suggest=ThreadedAutoSuggest(AutoSuggestFromHistory()),
            complete_while_typing=Condition(
                lambda: self.my_app.active_conn is not None))
        main_win_control = BufferControl(
            buffer=self.input_buffer,
            lexer=PygmentsLexer(SqlLexer),
            search_buffer_control=self.search_field.control,
            include_default_input_processors=False,
            input_processors=[AppendAutoSuggestion()],
            preview_search=True)

        self.main_win = Window(
            main_win_control,
            height=(
                lambda:
                (None if get_app().is_done else
                 (Dimension(min=self.my_app.min_num_menu_lines)
                  if not self.my_app.show_preview else Dimension(
                      min=self.my_app.min_num_menu_lines, preferred=180)))),
            get_line_prefix=partial(sql_line_prefix, my_app=self.my_app),
            scroll_offsets=ScrollOffsets(bottom=1, left=4, right=4))

        preview_element = PreviewElement(self.my_app)
        self.lprompt = login_prompt(self.my_app)
        self.preview = preview_element.create_container()
        self.disconnect_dialog = disconnect_dialog(self.my_app)
        container = HSplit([
            VSplit([
                FloatContainer(
                    content=HSplit([
                        self.main_win,
                        self.search_field,
                    ]),
                    floats=[
                        Float(
                            bottom=1,
                            left=1,
                            right=0,
                            content=sql_sidebar_help(self.my_app),
                        ),
                        Float(content=self.lprompt),
                        Float(content=self.preview, ),
                        preview_element.create_completion_float(),
                        Float(content=self.disconnect_dialog, ),
                        Float(left=2,
                              bottom=1,
                              content=exit_confirmation(self.my_app)),
                        Float(xcursor=True,
                              ycursor=True,
                              transparent=True,
                              content=CompletionsMenu(scroll_offset=1,
                                                      max_height=16,
                                                      extra_filter=has_focus(
                                                          self.input_buffer)))
                    ]),
                ConditionalContainer(
                    content=sql_sidebar(self.my_app),
                    filter=ShowSidebar(self.my_app) & ~is_done,
                )
            ]),
            VSplit([
                status_bar(self.my_app),
                show_sidebar_button_info(self.my_app)
            ])
        ])

        def accept(buff):
            app = get_app()
            app.exit(result=["non-preview", buff.text])
            app.pre_run_callables.append(buff.reset)
            return True

        self.input_buffer.accept_handler = accept
        self.layout = Layout(container, focused_element=self.main_win)
コード例 #15
0
ファイル: __main__.py プロジェクト: 3453-315h/chepy
def main():
    global fire_obj
    last_command = []

    args = parse_args(sys.argv[1:])
    args_data = args.data

    args_data.append("-")

    history_file = config.history_path
    session = PromptSession(
        history=FileHistory(history_file),
        style=get_style(),
        wrap_lines=True,
        auto_suggest=AutoSuggestFromHistory(),
    )
    try:
        while True:
            prompt = session.prompt(
                prompt_message(fire_obj=fire_obj),
                bottom_toolbar=bottom_toolbar(fire_obj),
                completer=FuzzyCompleter(
                    merge_completers(
                        [CustomCompleter(),
                         chepy_cli.CliCompleter()])),
                validator=CustomValidator(),
                rprompt=get_current_type(fire_obj),
            )

            # check and output any commands that start with cli_
            if re.match(r"^\!", prompt):
                print(subprocess.getoutput(re.sub(r"^\!\s?", "", prompt)))
            elif re.search(r"^cli_.+", prompt):
                cli_method = prompt.split()[0]
                cli_args = re.search(r"--(\w+)\s(\w+)", prompt)
                if cli_method == "cli_show_errors":
                    getattr(chepy_cli, "cli_show_errors")(errors)
                elif cli_method == "cli_go_back":
                    args_data = args_data[:-len(last_command + ["-"])]
                    print(CYAN("Go back: {}".format(last_command)))
                elif cli_method == "cli_delete_history":
                    Path(config.history_path).unlink()
                elif cli_args:
                    getattr(chepy_cli, cli_method)(fire_obj, **{
                        cli_args.group(1):
                        cli_args.group(2)
                    })
                else:
                    getattr(chepy_cli, cli_method)(fire_obj)

            else:
                for method in chepy:
                    if not method.startswith("_") and not isinstance(
                            getattr(Chepy, method), property):
                        fire.decorators._SetMetadata(
                            getattr(Chepy, method),
                            fire.decorators.ACCEPTS_POSITIONAL_ARGS,
                            False,
                        )
                args_data += prompt.split()
                if args_data[-1] != "-":
                    args_data.append("-")
                try:
                    last_command = prompt.split() + ["-"]
                    fire_obj = fire.Fire(Chepy, command=args_data)
                except:
                    # go back to last working arg
                    e_type, e_msg, e_traceback = sys.exc_info()
                    print(RED(e_type.__name__), YELLOW(e_msg.__str__()))
                    args_data = args_data[:-len(last_command)]
                    continue
    except KeyboardInterrupt:
        print("OKBye")
        sys.exit()
コード例 #16
0
ファイル: prompt_test01.py プロジェクト: baeksw/swkits
from prompt_toolkit import prompt
from prompt_toolkit.history import FileHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.contrib.completers import WordCompleter

DEFAULT_HISTORY = FileHistory('history.txt')
DEFAULT_SUGGEST = AutoSuggestFromHistory()

SQL_COMPLETER = WordCompleter(
    ['select', 'from', 'insert', 'update', 'delete', 'drop'], ignore_case=True)

while True:
    user_input = prompt('sw_kit> ',
                        history=DEFAULT_HISTORY,
                        auto_suggest=DEFAULT_SUGGEST,
                        completer=SQL_COMPLETER)
    print(user_input)
コード例 #17
0
ファイル: cli.py プロジェクト: ilius/starcal-server
    def selectPathRel(self, pathRel: str) -> True:
        # print(f"selectPathRel: {pathRel!r}")
        if pathRel.startswith("/"):
            raise RuntimeError(f"selectPathRel: invalid pathRel={pathRel!r}")

        elems = self._cwd.options.get(pathRel, [])

        if len(elems) > 1:
            pass  # FIXME

        parts = pathRel.rstrip("/").split("/")
        if not elems and len(parts) > 1:
            if self.selectPathRel(parts[0] + "/"):
                return self.selectPathRel("/".join(parts[1:]) + "/")
            return False

        part = parts[0]
        if not elems:
            elems = self._cwd.options.get(part, [])
        if not elems:
            elems = self._cwd.options.get(part + "/", [])
        if not elems:
            partName = self._urlParamByValue.get(part)
            if partName is not None:
                elems = self._cwd.options.get(partName, [])
        if not elems:
            return False

        # FIXME:
        if "{" in pathRel:
            parsedPath = parse_format(pathRel, pathRel)
            # example: parsedPath.named == {'var1': '{var1}', 'var2': '{var2}'}
            formatDict = {}
            for name in parsedPath.named:
                try:
                    value = prompt(
                        f"> URL Parameter: {name} = ",
                        history=FileHistory(self.paramHistoryPath(name)),
                        auto_suggest=AutoSuggestFromHistory(),
                        # completer=completer,
                    )
                except KeyboardInterrupt:
                    return False
                if value == "":
                    print(f"ERROR: {name} can not be empty")
                    return False
                formatDict[name] = value
                self._urlParamByValue[value] = name

            pathRelNew = pathRel.format(**formatDict)
            self._urlParamByValue[pathRelNew] = pathRel
            # print(f"pathRel={pathRel!r}, pathRelNew={pathRelNew!r}")
            pathRel = pathRelNew

        pathAbs = self._cwd.pathAbs + pathRel

        vdirElems = elems
        secondElemPath = pathGeneralizeDict.get(pathAbs.strip("/"))
        if secondElemPath:
            secondElemId = pathGeneralizeIdByPath[secondElemPath]
            tmpElems = self._resources.xpath(f"//*[@id='{secondElemId}']")
            if tmpElems:
                if len(tmpElems) > 1:
                    print(
                        f"Error: {len(tmpElems)} elements found with id='{secondElemId}'"
                    )
                vdirElems += tmpElems
            else:
                print(f"Error: No element found with id='{secondElemId}'")

        vdir = VirtualDir(vdirElems, "", pathAbs, self._cwd)
        return self.selectVirtualDir(vdir)
コード例 #18
0
 def askReadOptions(self):
     plugin = Glossary.plugins[self._inputFormat]
     options = Glossary.formatsReadOptions.get(self._inputFormat)
     if options is None:
         log.error(f"internal error: invalid format {self._inputFormat!r}")
         return
     optionsProp = Glossary.plugins[self._inputFormat].optionsProp
     history = FileHistory(
         join(histDir, f"read-options-{self._inputFormat}"))
     auto_suggest = AutoSuggestFromHistory()
     completer = WordCompleter(
         options.keys(),
         ignore_case=True,
         match_middle=True,
         sentence=True,
     )
     while True:
         try:
             optName = prompt(
                 ">> ReadOption: Name (ENTER if done): ",
                 history=history,
                 auto_suggest=auto_suggest,
                 completer=completer,
             )
         except (KeyboardInterrupt, EOFError):
             return
         if not optName:
             return
         option = optionsProp[optName]
         valueCompleter = self.getOptionValueCompleter(option)
         default = self._readOptions.get(optName)
         if default is None:
             default = options[optName]
         print(f"Comment: {option.longComment}")
         while True:
             if option.typ == "bool":
                 try:
                     valueNew = checkbox_prompt(
                         f">>> ReadOption: {optName}",
                         default=default,
                     )
                 except (KeyboardInterrupt, EOFError):
                     break
                 print(f"Set read-option: {optName} = {valueNew!r}")
                 self._readOptions[optName] = valueNew
                 break
             try:
                 value = prompt(
                     f">>> ReadOption: {optName} = ",
                     history=FileHistory(
                         join(histDir, f"option-value-{optName}")),
                     auto_suggest=AutoSuggestFromHistory(),
                     default=str(default),
                     completer=valueCompleter,
                 )
             except (KeyboardInterrupt, EOFError):
                 break
             if value == "":
                 if optName in self._readOptions:
                     print(f"Unset read-option {optName!r}")
                     del self._readOptions[optName]
                 # FIXME: set empty value?
                 break
             valueNew, ok = option.evaluate(value)
             if not ok or not option.validate(valueNew):
                 log.error(f"Invalid read option value {optName}={value!r}"
                           f" for format {self._inputFormat}")
                 continue
             print(f"Set read-option: {optName} = {valueNew!r}")
             self._readOptions[optName] = valueNew
             break
コード例 #19
0
ファイル: cli.py プロジェクト: whitten/http-prompt
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)
                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()

    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!")