コード例 #1
0
    def _create_buffer(self) -> Buffer:
        """
        Create the `Buffer` for the Python input.
        """
        python_buffer = Buffer(
            name=DEFAULT_BUFFER,
            complete_while_typing=Condition(
                lambda: self.complete_while_typing),
            enable_history_search=Condition(
                lambda: self.enable_history_search),
            tempfile_suffix=".py",
            history=self.history,
            completer=ThreadedCompleter(self._completer),
            validator=ConditionalValidator(
                self._validator,
                Condition(lambda: self.enable_input_validation)),
            auto_suggest=ConditionalAutoSuggest(
                ThreadedAutoSuggest(AutoSuggestFromHistory()),
                Condition(lambda: self.enable_auto_suggest),
            ),
            accept_handler=self._accept_handler,
            on_text_changed=self._on_input_timeout,
        )

        return python_buffer
コード例 #2
0
def prompt(session):
    '''
    mec prompt
    '''
    cmd_list = readline_init(session)

    # cook our completions
    completion_dict = dict.fromkeys(cmd_list)
    completion_dict["target"] = dict.fromkeys(os.listdir("./data"))
    completion_dict["set"] = dict.fromkeys(["auto-update", "proxy-pool"])
    completion_dict["set"]["auto-update"] = dict.fromkeys(["True", "False"])

    mec_completer = NestedCompleter.from_nested_dict(completion_dict)
    mec_ps = ANSI(colors.CYAN + colors.BOLD + "\nmec > " + colors.END)

    cmd_autosuggest = ThreadedAutoSuggest(MecAutoSuggest(completions=cmd_list))

    try:
        mecprompt = PromptSession(message=mec_ps,
                                  mouse_support=True,
                                  history=FileHistory(HISTFILE),
                                  completer=mec_completer,
                                  complete_while_typing=True,
                                  reserve_space_for_menu=2,
                                  auto_suggest=cmd_autosuggest).prompt()
    except termios.error as err:
        colors.colored_print(f"[-] Fatal error: {err}", color_code=colors.RED)
        os.system("mec stop")

    return mecprompt
コード例 #3
0
def main(ctx, verbose, script):
	'''Runs SCRIPT as a Dish shell script, or runs an interactive shell if it is
	not specified.

	GitHub repository: https://github.com/dullbananas/dish
	'''
	interactive = script.isatty()
	interpreter = Interpreter(
		ctx=ctx,
		verbose=verbose,
	)

	if interactive:
		from prompt_toolkit import PromptSession, ANSI
		from prompt_toolkit.history import FileHistory
		from prompt_toolkit.lexers import PygmentsLexer
		from prompt_toolkit.auto_suggest import ThreadedAutoSuggest
		from .autosuggest import DishSuggest, CombinedSuggest, FileSuggest
		from .syntax_highlighting import DishHighlight
		from pygments.lexers.shell import BashLexer

		history_path = os.path.expanduser('~/.dish-history')
		open(history_path, 'a').close()
		psession = PromptSession(
			auto_suggest=ThreadedAutoSuggest(CombinedSuggest(objects=[
				DishSuggest(ctx=ctx),
				FileSuggest(ctx=ctx),
			])),
			history=FileHistory(history_path),
			lexer=DishHighlight(interpreter=interpreter),
			mouse_support=True,
		)

		gprompt = ctx.obj.generate_prompt

		while True:
			prompt1 = ANSI(gprompt('PS1'))
			prompt2 = ANSI(gprompt('PS2'))
			line = psession.prompt(prompt1)
			needs_more = interpreter.feed(line)
			while needs_more:
				line = psession.prompt(prompt2)
				needs_more = interpreter.feed(line)

	else:
		while True:
			line = script.readline()
			if line == '':
				break
			else:
				interpreter.feed(line[:-1])
コード例 #4
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=DynamicCompleter(
                lambda: ThreadedCompleter(self.my_app.completer)),
            #                    lambda: 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))

        self.lprompt = login_prompt(self.my_app)
        self.preview = preview_element(self.my_app)
        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, ),
                        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)
コード例 #5
0
    print(
        f"{Back.LIGHTGREEN_EX + Fore.BLACK}  OK  {Back.RESET + Fore.LIGHTWHITE_EX} "
        f"The command finished in {Decimal(str(execution_time)).quantize(Decimal('0.0001'), rounding=ROUND_HALF_UP)}ms."
    )


def quote_check(args: str) -> bool:
    return " ".join(args).replace("\\\"", "").count("\"") % 2 != 0 or \
           " ".join(args).count("'") % 2 != 0 or \
           " ".join(args).count("`") % 2 != 0


pre_casts = pychromecast.get_chromecasts()
casts = []
cmd_completer: ActionCompleter = ActionCompleter()
cmd_auto_suggest: ThreadedAutoSuggest = ThreadedAutoSuggest(
    AutoSuggestFromHistory())
cmd_history: ThreadedHistory = ThreadedHistory(InMemoryHistory())
cmd_lexer: PygmentsLexer = PygmentsLexer(CommandLexer)
now_cast = None
now_id = 0
prefix = "> "


@cmd_completer.action("echo",
                      capture_all=True,
                      display_meta="Prints characters to the console")
@cmd_completer.param(None)
def _echo_action(*args) -> None:
    if " ".join(args) == "":
        print()
        return
コード例 #6
0
ファイル: preview.py プロジェクト: stjordanis/odbc-cli
    def __init__(self, my_app: "sqlApp"):
        self.my_app = my_app
        help_text = """
        Press Enter in the input box to page through the table.
        Alternatively, enter a filtering SQL statement and then press Enter
        to page through the results.
        """
        self.formatter = TabularOutputFormatter()
        self.completer = PreviewCompleter(
            my_app=self.my_app,
            completer=MssqlCompleter(
                smart_completion=True,
                get_conn=lambda: self.my_app.selected_object.conn))

        history_file = config_location() + 'preview_history'
        ensure_dir_exists(history_file)
        hist = PreviewHistory(my_app=self.my_app,
                              filename=expanduser(history_file))

        self.input_buffer = PreviewBuffer(
            name="previewbuffer",
            tempfile_suffix=".sql",
            history=ThreadedHistory(hist),
            auto_suggest=ThreadedAutoSuggest(
                PreviewSuggestFromHistory(my_app)),
            completer=ThreadedCompleter(self.completer),
            #                history = hist,
            #                auto_suggest = PreviewSuggestFromHistory(my_app),
            #                completer = self.completer,
            complete_while_typing=Condition(
                lambda: self.my_app.selected_object is not None and self.my_app
                .selected_object.conn.connected()),
            multiline=False)

        input_control = BufferControl(
            buffer=self.input_buffer,
            include_default_input_processors=False,
            input_processors=[AppendAutoSuggestion()],
            preview_search=False)

        self.input_window = Window(input_control)

        search_buffer = Buffer(name="previewsearchbuffer")
        self.search_field = SearchToolbar(search_buffer)
        self.output_field = TextArea(
            style="class:preview-output-field",
            text=help_text,
            height=D(preferred=50),
            search_field=self.search_field,
            wrap_lines=False,
            focusable=True,
            read_only=True,
            preview_search=True,
            input_processors=[
                ConditionalProcessor(
                    processor=HighlightIncrementalSearchProcessor(),
                    filter=has_focus("previewsearchbuffer")
                    | has_focus(self.search_field.control),
                ),
                HighlightSelectionProcessor(),
            ])

        def refresh_results(window_height) -> bool:
            """ This method gets called when the app restarts after
                exiting for execution of preview query.  It populates
                the output buffer with results from the fetch/query.
            """
            sql_conn = self.my_app.selected_object.conn
            if sql_conn.execution_status == executionStatus.FAIL:
                # Let's display the error message to the user
                output = sql_conn.execution_err
            else:
                crsr = sql_conn.cursor
                if crsr.description:
                    cols = [col.name for col in crsr.description]
                else:
                    cols = []
                if len(cols):
                    res = sql_conn.fetch_from_cache(size=window_height - 4,
                                                    wait=True)
                    output = self.formatter.format_output(res,
                                                          cols,
                                                          format_name="psql")
                    output = "\n".join(output)
                else:
                    output = "No rows returned\n"

            # Add text to output buffer.
            self.output_field.buffer.set_document(
                Document(text=output, cursor_position=0), True)

            return True

        def accept(buff: Buffer) -> bool:
            """ This method gets called when the user presses enter/return
                in the filter box.  It is interpreted as either 'execute query'
                or 'fetch next page of results' if filter query hasn't changed.
            """
            obj = self.my_app.selected_object
            sql_conn = obj.conn
            identifier = object_to_identifier(obj)
            query = sql_conn.preview_query(
                name=identifier,
                obj_type=obj.otype,
                filter_query=buff.text,
                limit=self.my_app.preview_limit_rows)
            if query is None:
                return True

            func = partial(refresh_results,
                           window_height=self.output_field.window.render_info.
                           window_height)
            if sql_conn.query != query:
                # Exit the app to execute the query
                self.my_app.application.exit(result=["preview", query])
                self.my_app.application.pre_run_callables.append(func)
            else:
                # No need to exit let's just go and fetch
                func()
            return True  # Keep filter text

        def cancel_handler() -> None:
            sql_conn = self.my_app.selected_object.conn
            sql_conn.close_cursor()
            self.input_buffer.text = ""
            self.output_field.buffer.set_document(
                Document(text=help_text, cursor_position=0), True)
            self.my_app.show_preview = False
            self.my_app.show_sidebar = True
            self.my_app.application.layout.focus(self.input_buffer)
            self.my_app.application.layout.focus("sidebarbuffer")
            return None

        self.input_buffer.accept_handler = accept
        self.cancel_button = Button(text="Done", handler=cancel_handler)