Ejemplo n.º 1
0
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)
    complete = completer.ShellCompleter(core.cli)

    while True:
        try:
            line = p_shortcuts.prompt(
                completer=complete,
                complete_while_typing=True,
                auto_suggest=p_auto_suggest.AutoSuggestFromHistory(),
            )

            # 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
Ejemplo n.º 2
0
def CreateCli(gcloud_py_dir):
  """Creates the CLI application.

  Args:
    gcloud_py_dir: str, path to completion lookup table

  Returns:
    cli, a cli instance
  """
  completer = ShellCliCompleter(gcloud_py_dir)
  in_memory_history = history.InMemoryHistory()
  auto_suggest_from_history = auto_suggest.AutoSuggestFromHistory()
  key_manager = _KeyBindings()

  layout = shortcuts.create_prompt_layout(
      lexer=shell.BashLexer,
      get_bottom_toolbar_tokens=GetBottomToolbarTokens,
      message=u'Cloud SDK {0}> '.format(config.CLOUD_SDK_VERSION))

  cli_buffer = ptkbuffer.Buffer(
      history=in_memory_history,
      auto_suggest=auto_suggest_from_history,
      complete_while_typing=True,
      completer=completer,
      accept_action=interface.AcceptAction.RETURN_DOCUMENT)

  application = Application(
      style=GetDocumentStyle(),
      buffer=cli_buffer,
      layout=layout,
      key_bindings_registry=key_manager.registry,
      mouse_support=True)

  cli = interface.CommandLineInterface(
      application=application,
      eventloop=shortcuts.create_eventloop())

  return cli
Ejemplo n.º 3
0
    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)
Ejemplo n.º 4
0
  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)
Ejemplo n.º 5
0
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
Ejemplo n.º 6
0
  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)