def build_propmpt(self) -> pt_shortcuts.PromptSession: history = pt_history.FileHistory( os.path.expanduser('~/.edgedbhistory')) bindings = pt_key_binding.KeyBindings() handle = bindings.add @handle('f3') # type: ignore def _mode_toggle(event: Any) -> None: self.context.toggle_query_mode() @handle('f4') # type: ignore def _implicit_toggle(event: Any) -> None: self.context.toggle_implicit() @handle('f5') # type: ignore def _introspect_toggle(event: Any) -> None: self.context.toggle_introspect_types() if self.context.introspect_types: self.ensure_connection() self.introspect_db(self.connection) else: self.context.typenames = None @handle('tab') # type: ignore def _tab(event: Any) -> None: b = prompt.app.current_buffer before_cursor = b.document.current_line_before_cursor if b.text and (not before_cursor or before_cursor.isspace()): b.insert_text(' ') prompt = pt_shortcuts.PromptSession( lexer=pt_lexers.PygmentsLexer(eql_pygments.EdgeQLLexer), include_default_pygments_style=False, completer=pt_complete.DummyCompleter(), reserve_space_for_menu=6, message=self.get_prompt_tokens, prompt_continuation=self.get_continuation_tokens, bottom_toolbar=self.get_toolbar_tokens, multiline=is_multiline, history=history, complete_while_typing=pt_filters.Always(), key_bindings=bindings, style=self.style, editing_mode=pt_enums.EditingMode.VI, search_ignore_case=True, ) return prompt
def cli(ctx, env): """Enters a shell for slcli.""" # Set up the environment env = copy.deepcopy(env) env.load_modules_from_python(routes.ALL_ROUTES) env.aliases.update(routes.ALL_ALIASES) env.vars['global_args'] = ctx.parent.params env.vars['is_shell'] = True env.vars['last_exit_code'] = 0 # Set up prompt_toolkit settings app_path = click.get_app_dir('softlayer') if not os.path.exists(app_path): os.makedirs(app_path) history = p_history.FileHistory(os.path.join(app_path, 'history')) complete = completer.ShellCompleter() while True: try: line = p_shortcuts.get_input( u"(%s)> " % env.vars['last_exit_code'], completer=complete, history=history, ) try: args = shlex.split(line) except ValueError as ex: print("Invalid Command: %s" % ex) continue if not args: continue # Reset client so that the client gets refreshed env.client = None core.main(args=list(get_env_args(env)) + args, obj=env, prog_name="", reraise_exceptions=True) except SystemExit as ex: env.vars['last_exit_code'] = ex.code except KeyboardInterrupt: env.vars['last_exit_code'] = 1 except EOFError: return except ShellExit: return except Exception as ex: env.vars['last_exit_code'] = 1 traceback.print_exc(file=sys.stderr)
def run(self): self.running = True while self.running: try: text = prompt(self._prompt_generator, completer=cmd_completer, history=history.FileHistory('.reptyle.hist'), complete_style=CompleteStyle.READLINE_LIKE) context.exec(text) except exception.ParserException as e: print(f"ERROR {e}") except KeyboardInterrupt: self.stop()
def build_cli(self): history = pt_history.FileHistory( os.path.expanduser('~/.edgedbhistory')) key_binding_manager = pt_keymanager.KeyBindingManager( enable_system_bindings=True, enable_search=True, enable_abort_and_exit_bindings=True) @key_binding_manager.registry.add_binding(pt_keys.Keys.F3) def _graphql_toggle(event): self.graphql = not self.graphql @key_binding_manager.registry.add_binding(pt_keys.Keys.Tab) def _tab(event): b = cli.current_buffer before_cursor = b.document.current_line_before_cursor if b.text and (not before_cursor or before_cursor.isspace()): b.insert_text(' ') layout = pt_shortcuts.create_prompt_layout( lexer=pt_lexers.PygmentsLexer(eql_pygments.EdgeQLLexer), reserve_space_for_menu=4, get_prompt_tokens=self.get_prompt_tokens, get_continuation_tokens=self.get_continuation_tokens, get_bottom_toolbar_tokens=self.get_toolbar_tokens, multiline=True) buf = InputBuffer( history=history, # to make reserve_space_for_menu work: complete_while_typing=pt_filters.Always(), accept_action=pt_app.AcceptAction.RETURN_DOCUMENT) app = pt_app.Application( style=self.style, layout=layout, buffer=buf, ignore_case=True, key_bindings_registry=key_binding_manager.registry, on_exit=pt_app.AbortAction.RAISE_EXCEPTION, on_abort=pt_app.AbortAction.RETRY) cli = pt_interface.CommandLineInterface( application=app, eventloop=self.eventloop) return cli
def run(): history = pthistory.FileHistory( os.path.join(os.path.expanduser('~'), '.gcloudstorageclihistory')) try: client = ClientWrapper(storage.Client()) except EnvironmentError: exit_client_error() except Exception as ex: exit_client_error(ex) while True: try: text = pt.prompt(get_prompt(client.cwd.get_path()), lexer=PygmentsLexer(GCSShellLexer), style=style, history=history, get_rprompt_tokens=get_rprompt(client.project)) execute_command(text, client) except EOFError: break except KeyboardInterrupt: continue print("Bye!")
def __init__(self, cosh=None, args=None, config=None): self.args = args self.coshell = cosh self.config = config self.key_bindings = bindings.KeyBindings( edit_mode=self.coshell.edit_mode == 'emacs') # Load the default CLI trees. On startup we ignore out of date trees. The # alternative is to regenerate them before the first prompt. This could be # a noticeable delay for users that accrue a lot of trees. Although ignored # at startup, the regen will happen on demand as the individual commands # are typed. self.root = generate_cli_trees.LoadAll(ignore_out_of_date=True, warn_on_exceptions=True) # Add the exit command completer node to the CLI tree. self.root[parser.LOOKUP_COMMANDS]['exit'] = cli_tree.Node( command='exit', description='Exit the interactive shell.', positionals=[ { 'default': '0', 'description': 'The exit status.', 'name': 'status', 'nargs': '?', 'required': False, 'value': 'STATUS', }, ], ) # Create the parser and completer. interactive_parser = parser.Parser(self.root, context=config.context, hidden=config.hidden) interactive_completer = completer.InteractiveCliCompleter( interactive_parser=interactive_parser, args=args, cosh=self.coshell, hidden=config.hidden, manpage_generator=config.manpage_generator) # Make sure that complete_while_typing is disabled when # enable_history_search is enabled. (First convert to SimpleFilter, to # avoid doing bitwise operations on bool objects.) complete_while_typing = shortcuts.to_simple_filter(True) enable_history_search = shortcuts.to_simple_filter(False) complete_while_typing &= ~enable_history_search history_file = os.path.join(core_config.Paths().global_config_dir, 'shell_history') multiline = shortcuts.to_simple_filter(False) # Create the default buffer. self.default_buffer = pt_buffer.Buffer( enable_history_search=enable_history_search, complete_while_typing=complete_while_typing, is_multiline=multiline, history=pt_history.FileHistory(history_file), validator=None, completer=interactive_completer, auto_suggest=(auto_suggest.AutoSuggestFromHistory() if config.suggest else None), accept_action=pt_buffer.AcceptAction.RETURN_DOCUMENT, ) # Create the CLI. self.cli = CLI( config=config, cosh=cosh, root=self.root, interactive_parser=interactive_parser, application=self._CreatePromptApplication(config=config, multiline=multiline), eventloop=shortcuts.create_eventloop(), output=shortcuts.create_output(), ) self.key_bindings.Initialize(self.cli)
def __init__(self, coshell=None, args=None, config=None, debug=None): self.args = args self.coshell = coshell self.config = config self.debug = debug self.key_bindings = bindings.KeyBindings() self.key_bindings_registry = self.key_bindings.MakeRegistry() # Load the default CLI trees. On startup we ignore out of date trees. The # alternative is to regenerate them before the first prompt. This could be # a noticeable delay for users that accrue a lot of trees. Although ignored # at startup, the regen will happen on demand as the individual commands # are typed. self.root = generate_cli_trees.LoadAll( ignore_out_of_date=True, warn_on_exceptions=True) # Add the interactive default CLI tree nodes. _AddCliTreeKeywordsAndBuiltins(self.root) # Make sure that complete_while_typing is disabled when # enable_history_search is enabled. (First convert to SimpleFilter, to # avoid doing bitwise operations on bool objects.) complete_while_typing = shortcuts.to_simple_filter(True) enable_history_search = shortcuts.to_simple_filter(False) complete_while_typing &= ~enable_history_search history_file = os.path.join(core_config.Paths().global_config_dir, 'shell_history') multiline = shortcuts.to_simple_filter(False) # Create the parser. interactive_parser = parser.Parser( self.root, context=config.context, hidden=config.hidden) # Create the completer. interactive_completer = completer.InteractiveCliCompleter( coshell=coshell, debug=debug, interactive_parser=interactive_parser, args=args, hidden=config.hidden, manpage_generator=config.manpage_generator) # Create the default buffer. self.default_buffer = pt_buffer.Buffer( enable_history_search=enable_history_search, complete_while_typing=complete_while_typing, is_multiline=multiline, history=pt_history.FileHistory(history_file), validator=None, completer=interactive_completer, auto_suggest=(auto_suggest.AutoSuggestFromHistory() if config.suggest else None), accept_action=pt_buffer.AcceptAction.RETURN_DOCUMENT, ) # Create the CLI. self.cli = CLI( config=config, coshell=coshell, debug=debug, root=self.root, interactive_parser=interactive_parser, interactive_completer=interactive_completer, application=self._CreatePromptApplication(config=config, multiline=multiline), eventloop=shortcuts.create_eventloop(), output=shortcuts.create_output(), ) # The interactive completer is friends with the CLI. interactive_completer.cli = self.cli # Initialize the bindings. self.key_bindings.Initialize(self.cli) bindings_vi.LoadViBindings(self.key_bindings_registry)
def cli(ctx, env): """Enters a shell for slcli.""" # Set up the environment env = copy.deepcopy(env) env.load_modules_from_python(routes.ALL_ROUTES) env.aliases.update(routes.ALL_ALIASES) env.vars['global_args'] = ctx.parent.params env.vars['is_shell'] = True env.vars['last_exit_code'] = 0 # Set up prompt_toolkit settings app_path = click.get_app_dir('softlayer_shell') if not os.path.exists(app_path): os.makedirs(app_path) history = p_history.FileHistory(os.path.join(app_path, 'history')) complete = completer.ShellCompleter(core.cli) while True: def get_prompt_tokens(_): """Returns tokens for the command prompt""" tokens = [] try: tokens.append((token.Token.Username, env.client.auth.username)) tokens.append((token.Token.At, "@")) except AttributeError: pass tokens.append((token.Token.Host, "slcli-shell")) if env.vars['last_exit_code']: tokens.append((token.Token.ErrorPrompt, '> ')) else: tokens.append((token.Token.Prompt, '> ')) return tokens try: line = p_shortcuts.prompt( completer=complete, history=history, auto_suggest=p_auto_suggest.AutoSuggestFromHistory(), get_prompt_tokens=get_prompt_tokens, ) # Parse arguments try: args = shlex.split(line) except ValueError as ex: print("Invalid Command: %s" % ex) continue if not args: continue # Run Command try: # Reset client so that the client gets refreshed env.client = None core.main(args=list(get_env_args(env)) + args, obj=env, prog_name="", reraise_exceptions=True) except SystemExit as ex: env.vars['last_exit_code'] = ex.code except EOFError: return except ShellExit: return except Exception as ex: env.vars['last_exit_code'] = 1 traceback.print_exc(file=sys.stderr) except KeyboardInterrupt: env.vars['last_exit_code'] = 130
def __init__(self, cli=None, cosh=None, args=None, config=None): self.args = args self.coshell = cosh self.config = config self.key_bindings = bindings.KeyBindings( edit_mode=self.coshell.edit_mode == 'emacs') # Load the default CLI trees. self.root = cli_tree.LoadAll(cli=cli) # Add the exit command completer node to the CLI tree. self.root[parser.LOOKUP_COMMANDS]['exit'] = cli_tree.Node( command='exit', description='Exit the interactive shell.', positionals=[ { 'default': '0', 'description': 'The exit status.', 'name': 'status', 'nargs': '?', 'required': False, 'value': 'STATUS', }, ], ) # Create the parser and completer. shell_parser = parser.Parser( self.root, context=config.context, hidden=config.hidden) shell_completer = completer.ShellCliCompleter(shell_parser=shell_parser, args=args, cosh=self.coshell, hidden=config.hidden) # Make sure that complete_while_typing is disabled when # enable_history_search is enabled. (First convert to SimpleFilter, to # avoid doing bitwise operations on bool objects.) complete_while_typing = shortcuts.to_simple_filter(True) enable_history_search = shortcuts.to_simple_filter(False) complete_while_typing &= ~enable_history_search history_file = os.path.join(core_config.Paths().global_config_dir, 'shell_history') multiline = shortcuts.to_simple_filter(False) # Create the default buffer. self.default_buffer = pt_buffer.Buffer( enable_history_search=enable_history_search, complete_while_typing=complete_while_typing, is_multiline=multiline, history=pt_history.FileHistory(history_file), validator=None, completer=shell_completer, auto_suggest=(auto_suggest.AutoSuggestFromHistory() if config.suggest else None), accept_action=pt_buffer.AcceptAction.RETURN_DOCUMENT, ) # Create the CLI. self.cli = CLI( config=config, cosh=cosh, root=self.root, shell_parser=shell_parser, application=self._CreatePromptApplication(config=config, multiline=multiline), eventloop=shortcuts.create_eventloop(), output=shortcuts.create_output(), ) self.key_bindings.Initialize(self.cli)