def Run(self, completer, expected_command=None, expected_completions=None,
         args=None):
   completer = parser_completer.ArgumentCompleter(
       completer, core_completer_test_base.MockArgument('id'))
   completions = completer(
       '', core_completer_test_base.MockNamespace(args=args))
   self.assertEqual(expected_completions or [], completions)
   self.AssertListCommand(expected_command)
  def ArgCompleter(self, args, arg, value):
    """Returns the flag or positional completion choices for arg or [].

    Args:
      args: The CLI tree parsed command args.
      arg: The flag or positional argument.
      value: The (partial) arg value.

    Returns:
      (choices, offset):
        choices - The list of completion strings or None.
        offset - The completion prefix offset.
    """
    choices = arg.get(parser.LOOKUP_CHOICES)
    if choices:
      # static choices
      return [v for v in choices if v.startswith(value)], -len(value)

    if not value and not self.event.completion_requested:
      return [], 0

    module_path = arg.get(parser.LOOKUP_COMPLETER)
    if not module_path:
      return [], 0

    # arg with a completer
    cache = self.completer_cache.get(module_path)
    if not cache:
      cache = CompleterCache(module_util.ImportModule(module_path))
      self.completer_cache[module_path] = cache
    prefix = value
    if not isinstance(cache.completer_class, type):
      cache.choices = cache.completer_class(prefix=prefix)
    elif cache.stale < time.time():
      old_dict = self.parsed_args.__dict__
      self.parsed_args.__dict__ = {}
      self.parsed_args.__dict__.update(old_dict)
      self.parsed_args.__dict__.update(_NameSpaceDict(args))
      completer = parser_completer.ArgumentCompleter(
          cache.completer_class,
          parsed_args=self.parsed_args)
      cache.choices = completer(prefix='')
      self.parsed_args.__dict__ = old_dict
      cache.stale = time.time() + cache.timeout
    if arg.get(parser.LOOKUP_TYPE) == 'list':
      parts = value.split(',')
      prefix = parts[-1]
    if not cache.choices:
      return [], 0
    return [v for v in cache.choices if v.startswith(prefix)], -len(prefix)
示例#3
0
  def _AttachCompleter(self, arg, completer, positional):
    """Attaches a completer to arg if one is specified.

    Args:
      arg: The argument to attach the completer to.
      completer: The completer Completer class or argcomplete function object.
      positional: True if argument is a positional.
    """
    if not completer:
      return
    if isinstance(completer, type):
      # A completer class that will be instantiated at completion time.
      if positional and issubclass(completer, completion_cache.Completer):
        # The list of positional resource completers is used to determine
        # parameters that must be present in the completions.
        self.data.positional_completers.add(completer)
      arg.completer = parser_completer.ArgumentCompleter(
          completer, argument=arg)
    else:
      arg.completer = completer
示例#4
0
 def _RunPromptCompleter(self, args):
     completer_class = module_util.ImportModule(args.prompt_completer)
     choices = parser_completer.ArgumentCompleter(completer_class, args)
     response = console_io.PromptResponse('Complete this: ',
                                          choices=choices)
     print(response)
示例#5
0
  def _AttachCompleter(self, arg, name, completer, positional,
                       deprecated_collection=None,
                       deprecated_list_command=None,
                       deprecated_list_command_callback=None):
    """Attaches a completer to arg if one is specified.

    Args:
      arg: The argument to attach the completer to.
      name: The arg name for messaging.
      completer: The completer Completer class or argcomplete function object.
      positional: True if argument is a positional.
      deprecated_collection: The collection name for the resource to complete.
      deprecated_list_command: The command whose Run() method returns the
        current resource list.
      deprecated_list_command_callback: A callback function that returns the
        list command to run.
    """
    if not completer:
      if not deprecated_collection:
        if deprecated_list_command or deprecated_list_command_callback:
          raise parser_errors.ArgumentException(
              'Command [{}] argument [{}] does not have completion_resource '
              'set but has one or more of the deprecated list_command_path '
              'and list_command_callback_fn attributes.'.format(
                  ' '.join(self.data.command_name), name))
        return

      class DeprecatedCompleter(
          deprecated_completers.DeprecatedListCommandCompleter):

        def __init__(self, **kwargs):
          super(DeprecatedCompleter, self).__init__(
              collection=deprecated_collection,
              list_command=deprecated_list_command,
              list_command_callback=deprecated_list_command_callback,
              **kwargs)

      DeprecatedCompleter.__name__ = (
          resource_property.ConvertToCamelCase(
              deprecated_collection.capitalize().replace('.', '_')) +
          'DeprecatedCompleter')

      completer = DeprecatedCompleter
    elif (deprecated_collection or
          deprecated_list_command or
          deprecated_list_command_callback):
      raise parser_errors.ArgumentException(
          'Command [{}] argument [{}] has a completer set with one or more '
          'of the deprecated completion_resource, list_command_path, and '
          'list_command_callback_fn attributes.'.format(
              ' '.join(self.data.command_name), name))
    if isinstance(completer, type):
      # A completer class that will be instantiated at completion time.
      if positional and issubclass(completer, completion_cache.Completer):
        # The list of positional resource completers is used to determine
        # parameters that must be present in the completions.
        self.data.positional_completers.add(completer)
      arg.completer = parser_completer.ArgumentCompleter(
          completer, argument=arg)
    else:
      arg.completer = completer