Ejemplo n.º 1
0
def _GetCompleter(module_path,
                  cache=None,
                  qualify=None,
                  resource_spec=None,
                  presentation_kwargs=None,
                  attribute=None,
                  **kwargs):
    """Returns an instantiated completer for module_path."""
    presentation_kwargs = presentation_kwargs or {}
    if resource_spec:
        presentation_spec = _GetPresentationSpec(resource_spec,
                                                 **presentation_kwargs)
        completer = module_util.ImportModule(module_path)(
            presentation_spec.concept_spec, attribute)

    else:
        completer = module_util.ImportModule(module_path)
        if not isinstance(completer, type):
            return _FunctionCompleter(completer)
    try:
        return completer(cache=cache,
                         qualified_parameter_names=qualify,
                         **kwargs)
    except TypeError:
        return _FunctionCompleter(completer())
Ejemplo n.º 2
0
    def Complete(self, prefix, parameter_info):
        properties.VALUES.core.print_completion_tracebacks.Set(True)
        prop_name = parameter_info.GetValue('property')
        if not prop_name:
            # No property specified. This should have been caught by the caller.
            return None
        prop = properties.FromString(prop_name)
        if not prop:
            # Property is invalid. This should have been caught by the caller.
            return None

        if prop.choices:
            # Fixed set of possible values - easy.
            return [c for c in prop.choices if c.startswith(prefix)]

        if prop.completer:
            # prop.completer is the module path for the resource value completer.
            completer_class = module_util.ImportModule(prop.completer)
            completer = completer_class()
            if (hasattr(completer, 'GetListCommand') and not isinstance(
                    completer,
                    deprecated_completers.DeprecatedListCommandCompleter)):
                list_command = ' '.join(
                    completer.GetListCommand(parameter_info))
                completer = deprecated_completers.DeprecatedListCommandCompleter(
                    collection=completer.collection, list_command=list_command)
            return completer.Complete(prefix, parameter_info)

        # No completer for this property.
        return None
Ejemplo n.º 3
0
 def testImportNoSuchAttributePath(self):
     with self.assertRaisesRegex(
             module_util.ImportModuleError,
             r'Module path \[googlecloudsdk.core.util:FormatDateTime.UnKnOwN] '
             r'not found: .*'):
         module_util.ImportModule(
             'googlecloudsdk.core.util:FormatDateTime.UnKnOwN')
Ejemplo n.º 4
0
 def testImportBadForm(self):
     with self.assertRaisesRegex(
             module_util.ImportModuleError,
             r'Module path \[googlecloudsdk.core.util:FormatDateTime:UnKnOwN] '
             r'must be in the form: '
             r'package\(.module\)\+\(:attribute\(.attribute\)\*\)\?'):
         module_util.ImportModule(
             'googlecloudsdk.core.util:FormatDateTime:UnKnOwN')
Ejemplo n.º 5
0
def _GetCompleter(module_path, cache=None, qualify=None, **kwargs):
    """Returns an instantiated completer for module_path."""
    completer = module_util.ImportModule(module_path)
    if not isinstance(completer, type):
        return _FunctionCompleter(completer)
    try:
        return completer(cache=cache,
                         qualified_parameter_names=qualify,
                         **kwargs)
    except TypeError:
        return _FunctionCompleter(completer())
Ejemplo n.º 6
0
  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)
Ejemplo n.º 7
0
def _GetPresentationSpec(resource_spec_path, **kwargs):
  resource_spec = module_util.ImportModule(resource_spec_path)
  if callable(resource_spec):
    resource_spec = resource_spec()
  flag_name_overrides = kwargs.pop('flag_name_overrides', '')
  flag_name_overrides = {
      o.split(':')[0]: o.split(':')[1] if ':' in o else ''
      for o in flag_name_overrides.split(';')}
  prefixes = kwargs.pop('prefixes', False)
  return concept_parsers.ResourcePresentationSpec(
      kwargs.pop('name', resource_spec.name),
      resource_spec,
      'help text',
      flag_name_overrides=flag_name_overrides,
      prefixes=prefixes,
      **kwargs)
Ejemplo n.º 8
0
def _ImportPythonHook(path):
    """Imports the given python hook.

  Depending on what it is used for, a hook is a reference to a class, function,
  or attribute in Python code.

  Args:
    path: str, The path of the hook to import. It must be in the form of:
      package.module:attribute.attribute where the module path is separated from
      the class name and sub attributes by a ':'. Additionally, ":arg=value,..."
      can be appended to call the function with the given args and use the
      return value as the hook.

  Raises:
    InvalidSchemaError: If the given module or attribute cannot be loaded.

  Returns:
    Hook, the hook configuration.
  """
    parts = path.split(':')
    if len(parts) != 2 and len(parts) != 3:
        raise InvalidSchemaError(
            'Invalid Python hook: [{}]. Hooks must be in the format: '
            'package(.module)+:attribute(.attribute)*(:arg=value(,arg=value)*)?'
            .format(path))
    try:
        attr = module_util.ImportModule(parts[0] + ':' + parts[1])
    except module_util.ImportModuleError as e:
        raise InvalidSchemaError(
            'Could not import Python hook: [{}]. {}'.format(path, e))

    kwargs = None
    if len(parts) == 3:
        kwargs = {}
        for arg in parts[2].split(','):
            if not arg:
                continue
            arg_parts = arg.split('=')
            if len(arg_parts) != 2:
                raise InvalidSchemaError(
                    'Invalid Python hook: [{}]. Args must be in the form arg=value,'
                    'arg=value,...'.format(path))
            kwargs[arg_parts[0]] = arg_parts[1]

    return Hook(attr, kwargs)
Ejemplo n.º 9
0
    def Complete(self, prefix, parameter_info):
        properties.VALUES.core.print_completion_tracebacks.Set(True)
        prop_name = parameter_info.GetValue('property')
        if not prop_name:
            # No property specified. This should have been caught by the caller.
            return None
        prop = properties.FromString(prop_name)
        if not prop:
            # Property is invalid. This should have been caught by the caller.
            return None

        if prop.choices:
            # Fixed set of possible values - easy.
            return [c for c in prop.choices if c.startswith(prefix)]

        if prop.completer:
            # prop.completer is the module path for the resource value completer.
            completer_class = module_util.ImportModule(prop.completer)
            completer = completer_class(cache=self.cache)
            return completer.Complete(prefix, parameter_info)

        # No completer for this property.
        return None
Ejemplo n.º 10
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)
Ejemplo n.º 11
0
 def testImportNoSuchAttribute(self):
     with self.assertRaisesRegex(
             module_util.ImportModuleError,
             r'Module path \[googlecloudsdk.core.util.times:UnKnOwN] not found:.*'
     ):
         module_util.ImportModule('googlecloudsdk.core.util.times:UnKnOwN')
Ejemplo n.º 12
0
 def testImportNoSuchModule(self):
     with self.assertRaisesRegex(
             module_util.ImportModuleError,
             r'Module path \[googlecloudsdk.core.futile.times] not found:.*'
     ):
         module_util.ImportModule('googlecloudsdk.core.futile.times')
Ejemplo n.º 13
0
 def testImportNoSuchPackage(self):
     with self.assertRaisesRegex(
             module_util.ImportModuleError,
             r'Module path \[scrooglecloudsdk.core.util.times] not found:.*'
     ):
         module_util.ImportModule('scrooglecloudsdk.core.util.times')
Ejemplo n.º 14
0
 def testImportExistingStandardModule(self):
     files_completer = module_util.ImportModule(
         'argcomplete.completers:FilesCompleter')
     self.assertEqual(argcomplete_completers.FilesCompleter,
                      files_completer)
Ejemplo n.º 15
0
 def testImportMalformedStandardModule(self):
     with self.assertRaisesRegex(
             module_util.ImportModuleError,
             r'Module path \[argcomplete.completers.FilesCompleter] not found:.*'
     ):
         module_util.ImportModule('argcomplete.completers.FilesCompleter')
Ejemplo n.º 16
0
 def testImportExistingCloudSdkModule(self):
     times = module_util.ImportModule('googlecloudsdk.core.util.times')
     dt = times.GetDateTimeFromTimeStamp(1496293728)
     ts = times.FormatDateTime(dt, tzinfo=times.UTC)
     self.assertEqual('2017-06-01T05:08:48.000Z', ts)