Ejemplo n.º 1
0
def main():
    # Simple completion menu.
    print('(The completion menu displays colors.)')
    prompt('Type a color: ', completer=FuzzyCompleter(ColorCompleter()))

    # Multi-column menu.
    prompt('Type a color: ', completer=FuzzyCompleter(ColorCompleter()),
           complete_style=CompleteStyle.MULTI_COLUMN)

    # Readline-like
    prompt('Type a color: ', completer=FuzzyCompleter(ColorCompleter()),
           complete_style=CompleteStyle.READLINE_LIKE)
Ejemplo n.º 2
0
    def __init__(self, words, meta_dict=None, WORD=False):
        # assert callable(words) or all(isinstance(w, string_types) for w in words)

        self.words = words
        self.meta_dict = meta_dict or {}
        self.WORD = WORD

        self.word_completer = WordCompleter(
            words=lambda: self.words, WORD=self.WORD, meta_dict=self.meta_dict
        )

        self.fuzzy_completer = FuzzyCompleter(self.word_completer, WORD=self.WORD)
Ejemplo n.º 3
0
def run_cmd_shell(argv=[], prefix='cmd-> ', words=[], cmd_func=None):
    if len(argv) > 1 and cmd_func is not None:
        cmd_func(argv[1:])
        return
    from prompt_toolkit import prompt, PromptSession
    from prompt_toolkit import PromptSession
    from prompt_toolkit.completion import WordCompleter
    from prompt_toolkit.lexers import PygmentsLexer
    from prompt_toolkit.styles import Style
    from pygments.lexers.sql import SqlLexer
    from prompt_toolkit.completion import FuzzyCompleter
    from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
    _completer = FuzzyCompleter(WordCompleter(words))
    session = PromptSession(lexer=PygmentsLexer(SqlLexer),
                            completer=_completer,
                            auto_suggest=AutoSuggestFromHistory())
    while True:
        try:
            text = session.prompt(prefix)
        except KeyboardInterrupt:
            continue
        except EOFError:
            break
        else:
            args_str = text.strip()
            if args_str == '':
                continue
            args = args_str.split(' ')
            # print(args)
            if len(args) > 0 and cmd_func is not None:
                cmd_func(args)
Ejemplo n.º 4
0
    def __init__(self) -> None:
        self.cli = None
        self.prompt_tokens = []

        self.completer = FuzzyCompleter(CommandCompleter())
        self.commands_repository = COMMANDS
        self.session = self.get_prompt_session()
Ejemplo n.º 5
0
    def _exec_from_repl(self, theme=MonokaiTheme):
        self.do_repl = True
        manager_completer = FuzzyCompleter(
            CommandCompleter(self.manager, ignore_case=True))
        lexer = create_lexer(commands=self.manager.command_names)
        session = PromptSession(
            completer=manager_completer,
            lexer=PygmentsLexer(lexer),
            style=theme.pygments_style(),
        )
        while self.do_repl:
            try:
                user_input = u"{}".format(session.prompt(u">> "))
            except KeyboardInterrupt:
                continue  # Control-C pressed. Try again.
            except EOFError:
                break  # Control-D Pressed. Finish

            try:
                command = user_input.split()[0]
                arguments = " ".join(user_input.split()[1:])
                try:
                    arguments = arguments.format(**self.context)
                except KeyError:
                    pass
                args, kwargs = inline_parser(arguments)
                self._execute_command(command, *args, **kwargs)
            except Exception as error:
                print("Error executing: {}. Error: {}".format(command, error))
Ejemplo n.º 6
0
 def __init__(
     self,
     words: List[str],
     display_dict: Optional[Dict[str, str]] = None,
     meta_dict: Optional[Dict[str, str]] = None,
 ) -> None:
     self.words = words
     self.WORD = True
     self.word_completer = WordCompleter(
         words=self.words,
         WORD=self.WORD,
         display_dict=display_dict,
         meta_dict=meta_dict,
     )
     self.fuzzy_completer = FuzzyCompleter(self.word_completer,
                                           WORD=self.WORD)
Ejemplo n.º 7
0
    def _maybe_complete_http_path(
            self, document: Document, complete_event: CompleteEvent,
            state_tracker: ParserStateTracker) -> Iterable[Completion]:
        tokens = state_tracker.tokens
        method_token, path_token = tokens[-2], tokens[-1]
        method = method_token.value.upper()
        cursor_position = document.cursor_position - path_token.index
        path = path_token.value[:cursor_position]
        _logger.debug(f'Completing HTTP API url: {path!r}')
        path_tokens = list(self.url_path_lexer.get_tokens_unprocessed(path))
        _logger.debug(f'URL Path Tokens: {path_tokens}')
        if not path_tokens:  # empty, should not happen
            return []

        cursor_token = path_tokens[-1]
        _logger.debug(f'Cursor Token: {cursor_token}')
        if cursor_token.ttype is Error:
            return []
        else:
            if cursor_token.ttype in (PathPart, Slash):
                complete_func = self.api_spec.complete_url_path
            elif cursor_token.ttype in (ParamName, QuestionMark, Ampersand):
                complete_func = self.api_spec.complete_query_param_name
            else:
                complete_func = self.api_spec.complete_query_param_value
            candidates = complete_func(document, complete_event, method,
                                       path_tokens)
            return FuzzyCompleter(
                ConstantCompleter(candidates)).get_completions(
                    document, complete_event)
Ejemplo n.º 8
0
    def add_workspace(self, initial=None, accept_all=False):
        if initial is None:
            initial = os.getcwd()
        else:
            initial = os.path.abspath(initial)
        existing_workspace = self.search_parent_in_workspaces(initial)
        if not existing_workspace:
            if accept_all:
                response = initial
            else:
                session = PromptSession(u"> ",
                                        completer=FuzzyCompleter(
                                            PathCompleter()))
                response = session.prompt(
                    "Path to find new components\n> ",
                    complete_while_typing=True,
                    default=initial,
                    pre_run=session.default_buffer.start_completion,
                    validator=dir_validator)
            # Check the final '/' characters
            if response in self.workspace_paths:
                print(f"{response} already exist in workspaces")
                return

            new_components = self.get_recursive_components_in_dir(response)

            print("%s\n%d components found in %s" %
                  (colored('\n'.join(new_components),
                           'green'), len(new_components), response))
            if len(new_components) == 0:
                print(
                    f"No component found in {response}. Workspaces not updated."
                )
                return

            if accept_all:
                answer = True
            else:
                answer = confirm(
                    f'Do you want to add {response} to workspaces?')

            if answer:
                print(f"{response} added to workspaces")
                self.components += new_components
                self.workspace_paths.append(response)
                self.save_workspace()
            else:
                print("Workspaces not updated.")
        else:
            print(
                f"{initial} is already part of an existing workspace ({existing_workspace})"
            )
            self.update_components_in_workspaces(existing_workspace)
Ejemplo n.º 9
0
def main(args):
    if len(args) != 2:
        sys.stderr.write(f"Usage: {args[0]} <sqlite3 db>\n")
        sys.exit(1)

    base_completer = DirsCompleter(args[1])
    completer = FuzzyCompleter(base_completer)
    session = PromptSession(HTML("<yellow>cd </yellow>"), completer=completer, complete_while_typing=True)
    try:
        answer = session.prompt(pre_run=session.default_buffer.start_completion)
    except KeyboardInterrupt:
        sys.exit(2)
    sys.stdout.write(answer)
Ejemplo n.º 10
0
 def delete_workspace(self, keyword):
     session = PromptSession(u"> ", completer=FuzzyCompleter(WordCompleter(self.workspace_paths)))
     if not keyword:
         keyword = os.getcwd()
     else:
         keyword = os.path.abspath(keyword)
     response = session.prompt("Path to delete\n> ",
                               complete_while_typing=True,
                               default=keyword,
                               pre_run=session.default_buffer.start_completion)
     if response in self.workspace_paths:
         self._delete_components_in_workspace(response)
         self.workspace_paths.remove(response)
         self.save_workspace()
Ejemplo n.º 11
0
def wait_command() -> None:
    global cmd_completer
    global prefix

    session = PromptSession(prefix,
                            completer=FuzzyCompleter(cmd_completer),
                            complete_while_typing=True,
                            complete_in_thread=True,
                            lexer=cmd_lexer,
                            mouse_support=True,
                            enable_history_search=True,
                            auto_suggest=cmd_auto_suggest,
                            history=cmd_history)

    while True:
        try:
            ipt = session.prompt()
        except KeyboardInterrupt:
            print(f"{Fore.LIGHTGREEN_EX}Bye.")

            break

        if any(ipt.startswith(match) for match in ["#", "//", '"', ";"]):
            continue
        elif ipt.startswith("/*") and not ipt.endswith("*/"):
            error("This comment block must be enclosed in */")
        elif ipt.startswith("/*") and ipt.endswith("*/"):
            continue

        start = time.perf_counter()

        try:
            cmd_completer.run_action(ipt)
        except ValueError:
            error("Command not found.")

            continue
        except TypeError:
            error("Argument(s) missing or invalid.")

            continue

        end = time.perf_counter()

        ok(end - start)
Ejemplo n.º 12
0
    def _exec_from_repl(self,
                        prompt=u'>> ',
                        theme=MonokaiTheme,
                        history_file=None):
        session_extra_options = {}
        if history_file:
            session_extra_options['history'] = FileHistory(
                os.path.expanduser(str(history_file)))
        self.do_repl = True
        manager_completer = FuzzyCompleter(
            CommandCompleter(self.manager, ignore_case=True))
        lexer = create_lexer(commands=self.manager.command_names)
        session = PromptSession(completer=manager_completer,
                                lexer=PygmentsLexer(lexer),
                                style=theme.pygments_style(),
                                **session_extra_options)
        while self.do_repl:
            try:
                user_input = u"{}".format(session.prompt(prompt))
            except KeyboardInterrupt:
                continue  # Control-C pressed. Try again.
            except EOFError:
                break  # Control-D Pressed. Finish

            try:
                command_list = user_input.split()
                if not command_list:
                    continue
                command = command_list[0]
                arguments = " ".join(command_list[1:])
                try:
                    arguments = arguments.format(**self.context)
                except KeyError:
                    pass
                args, kwargs = inline_parser(arguments)
                self._execute_command(command, *args, **kwargs)
            except CommandNotFound:
                print('Command {} not found'.format(command))
                if self.suggestions:
                    possible_command = self.suggestions(
                        command, self.manager.command_names)
                    if possible_command:
                        print('Did you mean: "{}"?'.format(possible_command))
            except Exception as error:
                print("Error executing: {}. Error: {}".format(command, error))
Ejemplo n.º 13
0
 def _maybe_complete_payload_value(
         self, document: Document, complete_event: CompleteEvent,
         state_tracker: ParserStateTracker) -> Iterable[Completion]:
     tokens = state_tracker.tokens
     _logger.debug(f'Completing for payload value with tokens: {tokens}')
     path_event = state_tracker.events[1]
     if path_event.token.ttype is not Literal:  # No completion for non-literal URL
         return []
     method_token, path_token = tokens[0], tokens[1]
     path_tokens = list(
         self.url_path_lexer.get_tokens_unprocessed(path_token.value))
     last_event = state_tracker.last_event
     candidates, rules = self.api_spec.complete_payload_value(
         document, complete_event, method_token.value.upper(), path_tokens,
         tokens[tokens.index(last_event.token):],
         state_tracker.payload_events)
     if not candidates:
         return []
     constant_completer = ConstantCompleter(candidates)
     return FuzzyCompleter(constant_completer).get_completions(
         document, complete_event)
Ejemplo n.º 14
0
def getTag(result):
    myComplete = {}
    myCompleteL = []
    for r in result:
        if "tags" in path_entry_name_content[r]:
            if type(path_entry_name_content[r]["tags"]) == list:
                for i in path_entry_name_content[r]["tags"]:
                    myComplete[i] = {}
    for i in myComplete:
        myCompleteL.append(i)
    #promptT = getPromptText()

    completer = FuzzyCompleter(WordCompleter(myCompleteL, ignore_case=True))

    print(myCompleteL)
    icon = "search > tag >"
    if detectNerdFont: icon = "   "
    session = PromptSession(icon + " ", style=style, key_bindings=bindings)
    #prompt= session.prompt(pre_run=session.default_buffer.start_completion,default="",completer=completer)
    prompt = session.prompt(pre_run=session.default_buffer.start_completion,
                            default="",
                            completer=completer)
Ejemplo n.º 15
0
class FuzzyWordCompleter(Completer):
    def __init__(
        self,
        words: List[str],
        display_dict: Optional[Dict[str, str]] = None,
        meta_dict: Optional[Dict[str, str]] = None,
    ) -> None:
        self.words = words
        self.WORD = True
        self.word_completer = WordCompleter(
            words=self.words,
            WORD=self.WORD,
            display_dict=display_dict,
            meta_dict=meta_dict,
        )
        self.fuzzy_completer = FuzzyCompleter(self.word_completer,
                                              WORD=self.WORD)

    def get_completions(self, document: Document,
                        complete_event: CompleteEvent) -> Iterable[Completion]:
        return self.fuzzy_completer.get_completions(document, complete_event)

    def get_completions_filtered(
        self,
        document: Document,
        complete_event: CompleteEvent,
        predicate: Callable[[Completion], bool],
    ) -> Iterable[Completion]:
        for v in self.get_completions(document, complete_event):
            if predicate(v):
                yield v

    def get_completions_without(self, document: Document,
                                complete_event: CompleteEvent,
                                **filter_values: bool) -> Iterable[Completion]:
        return self.get_completions_filtered(
            document, complete_event,
            lambda v: not filter_values.get(v.text, False))
Ejemplo n.º 16
0
class FuzzyWordCompleter(Completer):
    """
    Fuzzy completion on a list of words.
    (This is basically a `WordCompleter` wrapped in a `FuzzyCompleter`.)
    :param words: List of words or callable that returns a list of words.
    :param meta_dict: Optional dict mapping words to their meta-information.
    :param WORD: When True, use WORD characters.
    """

    def __init__(self, words, meta_dict=None, WORD=False):
        # assert callable(words) or all(isinstance(w, string_types) for w in words)

        self.words = words
        self.meta_dict = meta_dict or {}
        self.WORD = WORD

        self.word_completer = WordCompleter(
            words=lambda: self.words, WORD=self.WORD, meta_dict=self.meta_dict
        )

        self.fuzzy_completer = FuzzyCompleter(self.word_completer, WORD=self.WORD)

    def get_completions(self, document, complete_event):
        return self.fuzzy_completer.get_completions(document, complete_event)
Ejemplo n.º 17
0
 def _maybe_complete_payload(
         self, document: Document, complete_event: CompleteEvent,
         state_tracker: ParserStateTracker) -> Iterable[Completion]:
     tokens = state_tracker.tokens
     _logger.debug(f'Completing for payload with tokens: {tokens}')
     path_event = state_tracker.events[1]
     if path_event.token.ttype is not Literal:  # No completion for non-literal URL
         return []
     method_token, path_token = tokens[0], tokens[1]
     path_tokens = list(
         self.url_path_lexer.get_tokens_unprocessed(path_token.value))
     last_event = state_tracker.last_event
     payload_tokens = tokens[tokens.index(last_event.token):]
     candidates, rules = self.api_spec.complete_payload(
         document, complete_event, method_token.value.upper(), path_tokens,
         payload_tokens)
     if not candidates:
         return []
     constant_completer = ConstantCompleter(candidates)
     for c in FuzzyCompleter(constant_completer).get_completions(
             document, complete_event):
         yield PayloadKeyCompletion(c.text, rules[c.text], c.start_position,
                                    c.display, c.display_meta, c.style,
                                    c.selected_style)
Ejemplo n.º 18
0
    def interactive_workspace_init(self, initial_path):
        def common_prefix(path_list):
            result = {}
            to_ignore = ""

            for path in sorted(path_list, reverse=True):
                path_parts = path.split('/')
                previous_counter = 0
                previous_path = ""
                for part_index in range(len(path_parts)):
                    counter = 0
                    last_path = '/'.join(path_parts[:len(path_parts) -
                                                    part_index])
                    last_path = last_path[len(to_ignore):]
                    if last_path and to_ignore + last_path not in result:
                        for second_path in path_list:
                            if last_path in second_path:
                                counter += 1
                        if counter == previous_counter:
                            del result[to_ignore + previous_path]
                        previous_counter = counter
                        previous_path = last_path
                        if counter == len(path_list):
                            to_ignore = to_ignore + last_path
                        elif last_path and counter < len(path_list):
                            result[to_ignore + last_path] = counter

            return result

        components_parents_dirs = self.get_recursive_components_in_dir(
            initial_path)

        #
        best_guess = common_prefix(list(components_parents_dirs.keys()))
        new_workspaces = []
        print(
            f"Found {len(best_guess)} possibles components in {colored(initial_path, 'green')}"
        )
        print(f"======")
        ignored = []
        for path in sorted(
                best_guess,
                key=lambda x: calculate_path_value(x, best_guess[x]),
                reverse=True):
            print(len(path.split('/')) * best_guess[path])
            end = False
            next = False
            for parent in new_workspaces:
                if path.startswith(parent):
                    print(
                        f"{colored(path, 'green')} ignored because you already selected parent {colored(parent, 'green')}"
                    )
                    next = True
                    break
            for parent in ignored:
                if path.startswith(parent):
                    print(
                        f"{colored(path, 'red')} ignored because you decided to ignore subdirs of {colored(parent, 'red')}"
                    )
                    next = True
                    break
            if next:
                continue
            while not end:
                print(
                    f"Found {best_guess[path]} components in {colored(path, 'green')}"
                )
                response = input(
                    f"Do you wanna add to workspace? {colored('Yes/No/Ignore/End', 'cyan')} "
                )
                if "yes" in response.lower() or "y" in response.lower():
                    new_workspaces.append(path)
                    break
                if "ignore" in response.lower() or "i" in response.lower():
                    to_ignore = prompt('> ',
                                       completer=FuzzyCompleter(
                                           PathCompleter()),
                                       complete_while_typing=True,
                                       default=path)
                    to_ignore = to_ignore.rstrip('/')
                    if not to_ignore:
                        to_ignore = path
                    ignored.append(to_ignore)
                    break
                elif "no" in response.lower() or "n" in response.lower():
                    break
                elif "end" in response.lower() or "e" in response.lower():
                    print("Finishing initialization of workspaces")
                    end = True
                else:
                    print('Invalid response (y/n/i/e)')
            if end:
                break
        self.workspace_paths = new_workspaces
        self.components = list(
            filter(
                lambda x: any(
                    x.startswith(workspace)
                    for workspace in self.workspace_paths),
                components_parents_dirs))

        self.save_workspace()
Ejemplo n.º 19
0
        cmd_unit = ctx.get_from_buffer('<complete>', doc)
        n = cmd_unit.root.lookup(lkql.Sloc(1, len(cmd_unit.text)))

        if n is None:
            return

        for sym in n.p_interp_complete:
            yield Completion(sym)


if __name__ == '__main__':
    our_history = FileHistory(".example-history-file")
    session = PromptSession(history=our_history,
                            lexer=PygmentsLexer(LKQLPygmentsLexer),
                            completer=FuzzyCompleter(LKQLCompleter()))

    dummy_unit = ctx.get_from_buffer('<dummy>', '12')
    dummy_unit.root.p_interp_init_from_project(
        'testsuite/ada_projects/deep_library/prj.gpr')

    while True:
        try:
            with patch_stdout():
                cmd = session.prompt('> ')
            if cmd == 'exit':
                break

            cmd_unit = ctx.get_from_buffer('<repl_input>', cmd)
            print(cmd_unit.root.p_interp_eval)
Ejemplo n.º 20
0
    def __init__(
        self,
        get_globals: Optional[_GetNamespace] = None,
        get_locals: Optional[_GetNamespace] = None,
        history_filename: Optional[str] = None,
        vi_mode: bool = False,
        color_depth: Optional[ColorDepth] = None,
        # Input/output.
        input: Optional[Input] = None,
        output: Optional[Output] = None,
        # For internal use.
        extra_key_bindings: Optional[KeyBindings] = None,
        _completer: Optional[Completer] = None,
        _validator: Optional[Validator] = None,
        _lexer: Optional[Lexer] = None,
        _extra_buffer_processors=None,
        _extra_layout_body=None,
        _extra_toolbars=None,
        _input_buffer_height=None,
    ) -> None:

        self.get_globals: _GetNamespace = get_globals or (lambda: {})
        self.get_locals: _GetNamespace = get_locals or self.get_globals

        self._completer = _completer or FuzzyCompleter(
            PythonCompleter(
                self.get_globals,
                self.get_locals,
                lambda: self.enable_dictionary_completion,
            ),
            enable_fuzzy=Condition(lambda: self.enable_fuzzy_completion),
        )
        self._validator = _validator or PythonValidator(
            self.get_compiler_flags)
        self._lexer = _lexer or PygmentsLexer(PythonLexer)

        self.history: History
        if history_filename:
            self.history = ThreadedHistory(FileHistory(history_filename))
        else:
            self.history = InMemoryHistory()

        self._input_buffer_height = _input_buffer_height
        self._extra_layout_body = _extra_layout_body or []
        self._extra_toolbars = _extra_toolbars or []
        self._extra_buffer_processors = _extra_buffer_processors or []

        self.extra_key_bindings = extra_key_bindings or KeyBindings()

        # Settings.
        self.title: AnyFormattedText = ""
        self.show_signature: bool = False
        self.show_docstring: bool = False
        self.show_meta_enter_message: bool = True
        self.completion_visualisation: CompletionVisualisation = CompletionVisualisation.MULTI_COLUMN
        self.completion_menu_scroll_offset: int = 1

        self.show_line_numbers: bool = False
        self.show_status_bar: bool = True
        self.wrap_lines: bool = True
        self.complete_while_typing: bool = True
        self.paste_mode: bool = False  # When True, don't insert whitespace after newline.
        self.confirm_exit: bool = True  # Ask for confirmation when Control-D is pressed.
        self.accept_input_on_enter: int = 2  # Accept when pressing Enter 'n' times.
        # 'None' means that meta-enter is always required.
        self.enable_open_in_editor: bool = True
        self.enable_system_bindings: bool = True
        self.enable_input_validation: bool = True
        self.enable_auto_suggest: bool = False
        self.enable_mouse_support: bool = False
        self.enable_history_search: bool = False  # When True, like readline, going
        # back in history will filter the
        # history on the records starting
        # with the current input.

        self.enable_syntax_highlighting: bool = True
        self.enable_fuzzy_completion: bool = False
        self.enable_dictionary_completion: bool = False
        self.swap_light_and_dark: bool = False
        self.highlight_matching_parenthesis: bool = False
        self.show_sidebar: bool = False  # Currently show the sidebar.

        # When the sidebar is visible, also show the help text.
        self.show_sidebar_help: bool = True

        # Currently show 'Do you really want to exit?'
        self.show_exit_confirmation: bool = False

        # The title to be displayed in the terminal. (None or string.)
        self.terminal_title: Optional[str] = None

        self.exit_message: str = "Do you really want to exit?"
        self.insert_blank_line_after_output: bool = True  # (For the REPL.)

        # The buffers.
        self.default_buffer = self._create_buffer()
        self.search_buffer: Buffer = Buffer()
        self.docstring_buffer: Buffer = Buffer(read_only=True)

        # Tokens to be shown at the prompt.
        self.prompt_style: str = "classic"  # The currently active style.

        # Styles selectable from the menu.
        self.all_prompt_styles: Dict[str, PromptStyle] = {
            "ipython": IPythonPrompt(self),
            "classic": ClassicPrompt(),
        }

        self.get_input_prompt = lambda: self.all_prompt_styles[
            self.prompt_style].in_prompt()

        self.get_output_prompt = lambda: self.all_prompt_styles[
            self.prompt_style].out_prompt()

        #: Load styles.
        self.code_styles: Dict[str, BaseStyle] = get_all_code_styles()
        self.ui_styles = get_all_ui_styles()
        self._current_code_style_name: str = "default"
        self._current_ui_style_name: str = "default"

        if is_windows():
            self._current_code_style_name = "win32"

        self._current_style = self._generate_style()
        self.color_depth: ColorDepth = color_depth or ColorDepth.default()

        self.max_brightness: float = 1.0
        self.min_brightness: float = 0.0

        # Options to be configurable from the sidebar.
        self.options = self._create_options()
        self.selected_option_index: int = 0

        #: Incremeting integer counting the current statement.
        self.current_statement_index: int = 1

        # Code signatures. (This is set asynchronously after a timeout.)
        self.signatures: List[Any] = []

        # Boolean indicating whether we have a signatures thread running.
        # (Never run more than one at the same time.)
        self._get_signatures_thread_running: bool = False

        self.style_transformation = merge_style_transformations([
            ConditionalStyleTransformation(
                SwapLightAndDarkStyleTransformation(),
                filter=Condition(lambda: self.swap_light_and_dark),
            ),
            AdjustBrightnessStyleTransformation(lambda: self.min_brightness,
                                                lambda: self.max_brightness),
        ])
        self.ptpython_layout = PtPythonLayout(
            self,
            lexer=DynamicLexer(lambda: self._lexer if self.
                               enable_syntax_highlighting else SimpleLexer()),
            input_buffer_height=self._input_buffer_height,
            extra_buffer_processors=self._extra_buffer_processors,
            extra_body=self._extra_layout_body,
            extra_toolbars=self._extra_toolbars,
        )

        self.app = self._create_application(input, output)

        if vi_mode:
            self.app.editing_mode = EditingMode.VI
Ejemplo n.º 21
0
    return result


output_field = TextArea(style="class:output-field", text=help_text)

output_field_2 = TextArea(style="class:output-field", text=help_text)

search_field = SearchToolbar()

input_field = TextArea(height=2,
                       prompt=">>> ",
                       style="class:input-field",
                       multiline=False,
                       wrap_lines=False,
                       search_field=search_field,
                       completer=FuzzyCompleter(ColorCompleter(),
                                                enable_fuzzy=False))


def accept(buff):
    # Evaluate "calculator" expression.
    try:
        #output = "\n\nIn:  {}\nOut: {}".format(
        #    input_field.text, eval(input_field.text)
        #)  # Don't do 'eval' in real code!
        output = "You're typing " + input_field.text + "\n"
        if input_field.text == "info":
            do_about()
        if input_field.text == "exit":
            do_exit()
    except BaseException as e:
        output = "\n\n{}".format(e)
Ejemplo n.º 22
0
#    dataDemo = {**dataDemo , **dataDemoModules }

for m in plugins.Plugin.pluginsActivated:
    print(m)
    dataDemoModules = {}
    dataDemoModules = yaml.load(
        plugins.Plugin.pluginsActivated[m].getDemoDataYaml(),
        Loader=yaml.SafeLoader)
    dataDemo = {**dataDemo, **dataDemoModules}

if os.getenv("ST_DEMO") == '1':
    my_fun(dataDemo, menu_completion, "", "")
else:
    my_fun(jinjaFile2yaml(file_main), menu_completion, "", "")

completer = FuzzyCompleter(NestedCompleter.from_nested_dict(menu_completion))


def getIcon(icon, defaultIcon=""):
    if detectNerdFont:
        return icon
    return defaultIcon


bindings = KeyBindings()


@bindings.add('c-c')
def _(event):
    #" Exit when `c-x` is pressed. "
    event.app.exit()
Ejemplo n.º 23
0
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()
Ejemplo n.º 24
0
def loop(stub, modules, module, netif, hostif):

    session = PromptSession()

    while True:
        p = "> "
        if module:
            loc = module.location
            p = "module({})> ".format(loc)
            if netif:
                p = "module({})/netif({})> ".format(loc, netif.index)
            elif hostif:
                p = "module({})/hostif({})> ".format(loc, hostif.index)

        c = FuzzyCompleter(
            TAIShellCompleter(stub, modules, module, netif, hostif))
        line = session.prompt(p, completer=c).strip()
        cmds = [e.strip() for e in line.split()]
        if len(cmds) == 0:
            continue

        cmd = cmds[0]
        try:
            if cmd == 'module':
                if len(cmds) != 2:
                    print('invalid input: module <location>')
                    continue
                loc = cmds[1]
                if loc not in modules:
                    print('no module whose location is {}'.format(loc))
                    continue
                module = modules[loc]
                netif = None
                hostif = None
            elif cmd == 'netif' or cmd == 'hostif':
                if not module:
                    print('no module selected.')
                    continue
                if len(cmds) != 2:
                    print('invalid input: {} <index>'.format(cmd))
                    continue

                index = int(cmds[1])

                l = module.netifs
                if cmd == 'hostif':
                    l = module.hostifs

                if len(l) < index:
                    print('invalid index: len: {}'.format(len(l)))
                    continue

                if cmd == 'netif':
                    netif = l[index]
                    hostif = None
                else:
                    hostif = l[index]
                    netif = None

            elif cmd == 'list':
                show_modules(modules)
            elif cmd == 'list-attr':
                list_attr(stub, module, netif, hostif)
            elif cmd == 'get':
                print(get_attr(stub, module, netif, hostif, cmds))
            elif cmd == 'set':
                set_attr(stub, module, netif, hostif, cmds)
            elif cmd == 'monitor':
                monitor(stub, module, netif, hostif, cmds)
            elif cmd == 'log-level':
                set_log_level(stub, cmds)
            elif cmd in ['exit', 'quit', 'q']:
                if netif:
                    netif = None
                elif hostif:
                    hostif = None
                elif module:
                    module = None
                else:
                    sys.exit(0)
            elif cmd in ['help', 'h', '?']:
                show_help()
            else:
                print('unknown cmd: {}'.format(cmd))
                show_help()
        except Exception as e:
            print(e)
Ejemplo n.º 25
0
def make_prompt_session():
    commands = focus.commands

    class CustomComplete(Completer):
        def get_completions(self, document, complete_event):
            word = document.get_word_before_cursor()
            words = document.text.split()
            complete_words = (words
                              if document.text.endswith(' ') else words[:-1])
            if words and words[0] in ['subtask-by-id', 'switch-task']:
                if len(complete_words) >= 2:
                    return
                for task in the_tree.root_nodes_iter():
                    if str(task.id).startswith(word):
                        yield Completion(str(task.id),
                                         display=f'{task.id} : {task.text}',
                                         start_position=-len(word))
            else:
                if len(complete_words) >= 1:
                    return
                for command in list(commands):
                    if command.startswith(word):
                        yield Completion(command,
                                         display=command + ' : ' +
                                         commands[command]['help'],
                                         start_position=-len(word))

    ft_completer = FuzzyCompleter(CustomComplete())
    # This if I want the help to be displayed
    ft_completer = CustomComplete()
    ####################################################################################
    # commands = focus.commands
    # meta_dict = {c : commands[c]['help'] for c in commands}
    # #print(meta_dict)
    # ft_completer = WordCompleter(focus.commands, meta_dict=meta_dict)
    prompt_style = Style.from_dict({'prompt': '#00aa00'})
    prompt_string = [('class:username', 'FocusTree> ')]
    bindings = KeyBindings()

    @bindings.add('c-j')
    def _(event):
        event.current_buffer.complete_next()

    @bindings.add('c-k')
    def _(event):
        event.current_buffer.complete_previous()

    # @bindings.add('tab')
    # def _(event):
    #     # THIS IS THE GETTO-EST THING EVER, DON'T JUDGE ME!
    #     # I just want it to select the currently highlighted
    #     # completion.  It could continue completing after.
    #     current_buffer = event.app.current_buffer
    #     compl = current_buffer.text
    #     current_buffer.cancel_completion()
    #     current_buffer.text = ''
    #     current_buffer.insert_text(compl + ' ')

    prompt_sesh = PromptSession(history=FileHistory(
        os.path.expanduser('~/.focus_tree_history')),
                                auto_suggest=AutoSuggestFromHistory(),
                                completer=ft_completer,
                                reserve_space_for_menu=8,
                                lexer=PygmentsLexer(BashLexer),
                                key_bindings=bindings,
                                style=prompt_style,
                                complete_style=CompleteStyle.COLUMN)

    def prompt():
        return prompt_sesh.prompt([('class:username', 'FocusTree> ')])

    return prompt
Ejemplo n.º 26
0
    def __init__(self, session, parent, name, type_):
        self.type_ = type_
        self.name = name
        self._get_hook = {}
        self._set_hook = {}
        self.session = session
        super(TAIObject, self).__init__(parent)

        d = self.session.get_context().get_searchdirs()
        repo = repository.FileRepository(d[0])
        ctx = context.Context(repo)

        m = self.session.get_context().get_module('goldstone-tai')
        v = m.print_mem(ly.LYS_IN_YANG, 0)

        ctx.add_module(None, v)
        mod = ctx.get_module('goldstone-tai')
        self.config = mod.search_one('grouping', 'tai-{}-config'.format(type_))
        self.state = mod.search_one('grouping', 'tai-{}-state'.format(type_))

        @self.command(FuzzyCompleter(TAICompleter(self.config, self.state)))
        def get(args):
            if len(args) != 1:
                raise InvalidInput('usage: get <name>')
            self.session.session_switch_ds(sr.SR_DS_OPERATIONAL)
            try:
                items = self.session.get_items('{}/state/{}'.format(
                    self.xpath(), args[0]))
                for i in range(items.val_cnt()):
                    item = items.val(i)
                    if args[0] in self._get_hook:
                        print(self._get_hook[args[0]](item))
                    else:
                        print(item.val_to_string())
            except RuntimeError:
                err = self.session.get_error()
                if err.error_cnt() > 0:
                    idx = err.error_cnt() - 1
                    print('err: {}, xpath: {}'.format(err.message(idx),
                                                      err.xpath(idx)))
            self.session.session_switch_ds(sr.SR_DS_RUNNING)

        @self.command(TAICompleter(self.config))
        def set(args):
            if len(args) != 2:
                raise InvalidInput('usage: set <name> <value>')
            if args[0] in self._set_hook:
                v = self._set_hook[args[0]](args[1])
            else:
                v = args[1]
            self.session.set_item_str(
                '{}/config/{}'.format(self.xpath(), args[0]), v)
            self.session.apply_changes()

        @self.command()
        def show(args):
            if len(args) != 0:
                raise InvalidInput('usage: show[cr]')
            self.session.session_switch_ds(sr.SR_DS_OPERATIONAL)
            tree = self.session.get_subtree(self.xpath(), TIMEOUT_MS)
            d = json.loads(tree.print_mem(ly.LYD_JSON, 0))
            print(d)
            self.session.session_switch_ds(sr.SR_DS_RUNNING)
Ejemplo n.º 27
0
def get_completer():
    csv_files = [s for s in listdir() if s.endswith('.csv')]
    completions['load'] = WordCompleter(csv_files)
    completer = NestedCompleter.from_nested_dict(completions)
    return FuzzyCompleter(completer)
Ejemplo n.º 28
0
def main():
    global fire_obj
    last_command = []

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

    if args.recipe:
        print(Chepy(*args_data).load_recipe(args.recipe).o)
    else:
        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(magenta(subprocess.getoutput(re.sub(r"^\!\s?", "", prompt))))
                # check if line is a comment
                elif re.match(r"^#", prompt):
                    print(cyan(prompt))
                # get help for a method
                elif re.match(r"^\?", prompt):
                    _method_name = re.match(r"^\?(\s?)+([\w_]+)", prompt).group(2)
                    chepy_cli.get_doc(_method_name)
                # check if method called is a cli method
                elif re.search(r"^cli_.+", prompt):
                    cli_method = prompt.split()[0]
                    cli_args = re.search(r"--(\w+)\s([\w\W]+)", prompt)
                    # Show errors encountered
                    if cli_method == "cli_show_errors":
                        getattr(chepy_cli, "cli_show_errors")(errors)
                    # show the current plugin path
                    elif cli_method == "cli_plugin_path":
                        getattr(chepy_cli, "cli_plugin_path")(config)
                    # Edit the current state
                    elif cli_method == "cli_edit_state":
                        try:
                            getattr(chepy_cli, "cli_edit_state")(fire_obj, args_data)
                            args_data = args_data[0 : args_data.index("-")] + ["-"]
                        except:
                            e_type, e_msg, e_traceback = sys.exc_info()
                            print(red(e_type.__name__), yellow("Could not edit state"))
                    # Go back one step
                    elif cli_method == "cli_go_back":
                        args_data = args_data[: -len(last_command + ["-"])]
                        print(cyan("Go back: {}".format(last_command)))
                    # Delete the cli history file
                    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)
                    # handle required args for methods
                    except fire.core.FireExit:
                        args_data = args_data[: -len(last_command)]
                    except TypeError as e:
                        print(red(e.message))
                    except SystemExit:
                        sys.exit()
                    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(green("\nOKBye"))
            sys.exit()
Ejemplo n.º 29
0
    def __init__(self, conn, parent, name, type_):
        self.type_ = type_
        self.name = name
        self._get_hook = {}
        self._set_hook = {}
        self.session = conn.start_session()
        super(TAIObject, self).__init__(parent)

        d = self.session.get_ly_ctx().get_searchdirs()
        repo = repository.FileRepository(d[0])
        ctx = context.Context(repo)

        m = self.session.get_ly_ctx().get_module('goldstone-tai')
        v = m.print_mem("yang")

        ctx.add_module(None, v)
        mod = ctx.get_module('goldstone-tai')
        self.config = mod.search_one('grouping', 'tai-{}-config'.format(type_))
        self.state = mod.search_one('grouping', 'tai-{}-state'.format(type_))

        @self.command(FuzzyCompleter(TAICompleter(self.config, self.state)))
        def get(args):
            if len(args) != 1:
                raise InvalidInput('usage: get <name>')
            self.session.switch_datastore('operational')
            try:
                items = self.session.get_items('{}/state/{}'.format(
                    self.xpath(), args[0]))
                for item in items:
                    if args[0] in self._get_hook:
                        print(self._get_hook[args[0]](item.value))
                    else:
                        print(item.value)
            except sr.errors.SysrepoCallbackFailedError as e:
                print(e)

        @self.command(TAICompleter(self.config))
        def set(args):
            if len(args) != 2:
                raise InvalidInput('usage: set <name> <value>')
            if args[0] in self._set_hook:
                v = self._set_hook[args[0]](args[1])
            else:
                v = args[1]
            self.session.switch_datastore('running')

            if type(self) != Module:
                try:
                    self.session.get_data(self.parent.xpath())
                except sr.SysrepoNotFoundError:
                    self.session.set_item(f'{self.parent.xpath()}/config/name',
                                          self.parent.name)

            try:
                self.session.get_data(self.xpath())
            except sr.SysrepoNotFoundError:
                self.session.set_item(f'{self.xpath()}/config/name', self.name)

            self.session.set_item(f'{self.xpath()}/config/{args[0]}', v)

            self.session.apply_changes()

        @self.command()
        def show(args):
            if len(args) != 0:
                raise InvalidInput('usage: show[cr]')
            self.session.switch_datastore('operational')
            print(self.session.get_data(self.xpath()))
            self.session.switch_datastore('running')