def CaptureException(self, exc): self._records.append({ 'exception': { 'type': module_util.GetModulePath(exc), 'message': six.text_type(exc) } })
def _AddUriCacheTap(self): """Taps a resource Uri cache updater into self.resources if needed.""" from googlecloudsdk.calliope import base # pylint: disable=g-import-not-at-top, circular dependency if self._cache_updater == cache_update_ops.NoCacheUpdater: return if not self._cache_updater: # pylint: disable=protected-access if not isinstance(self._command, (base.CreateCommand, base.DeleteCommand, base.ListCommand, base.RestoreCommand)): return if 'AddCacheUpdater' in properties.VALUES.core.lint.Get(): # pylint: disable=protected-access raise CommandNeedsAddCacheUpdater( '`{}` needs a parser.display_info.AddCacheUpdater() call.'. format(' '.join(self._args._GetCommand().GetPath()))) return if self._legacy and (not self._info or self._info.bypass_cache): return if any([self._GetFlag(flag) for flag in self._CORRUPT_FLAGS]): return # pylint: disable=protected-access if isinstance(self._command, (base.CreateCommand, base.RestoreCommand)): cache_update_op = cache_update_ops.AddToCacheOp( self._cache_updater) elif isinstance(self._command, base.DeleteCommand): cache_update_op = cache_update_ops.DeleteFromCacheOp( self._cache_updater) elif isinstance(self._command, base.ListCommand): cache_update_op = cache_update_ops.ReplaceCacheOp( self._cache_updater) else: raise CommandShouldntHaveAddCacheUpdater( 'Cache updater [{}] not expected for [{}] `{}`.'.format( module_util.GetModulePath(self._cache_updater), module_util.GetModulePath(self._args._GetCommand()), ' '.join(self._args._GetCommand().GetPath()))) tap = display_taps.UriCacher(cache_update_op, self._transform_uri) self._resources = peek_iterable.Tapper(self._resources, tap)
def Visit(self, command, parent, is_group): """Visits each command in the CLI command tree to construct the module list. Args: command: group/command CommandCommon info. parent: The parent Visit() return value, None at the top level. is_group: True if command is a group, otherwise its is a command. Returns: The subtree module list. """ args = command.ai for arg in sorted(args.flag_args + args.positional_args): try: completer_class = arg.completer except AttributeError: continue collection = None api_version = None if isinstance(completer_class, parser_completer.ArgumentCompleter): completer_class = completer_class.completer_class module_path = module_util.GetModulePath(completer_class) if isinstance(completer_class, type): try: completer = completer_class() try: collection = completer.collection except AttributeError: pass try: api_version = completer.api_version except AttributeError: pass except (apis_util.UnknownAPIError, resources.InvalidCollectionException) as e: collection = u'ERROR: {}'.format(e) if arg.option_strings: name = arg.option_strings[0] else: name = arg.dest.replace('_', '-') module = self._modules_dict.get(module_path) if not module: module = _CompleterModule( module_path=module_path, collection=collection, api_version=api_version, completer_type=_GetCompleterType(completer_class), ) self._modules_dict[module_path] = module command_path = ' '.join(command.GetPath()) # pylint: disable=protected-access attachment = module._attachments_dict.get(command_path) if not attachment: attachment = _CompleterAttachment(command_path) module._attachments_dict[command_path] = attachment module.attachments.append(attachment) attachment.arguments.append(name) return self._modules_dict
def __init__(self, flag, name): super(Flag, self).__init__(flag, name) self.attr = {} self.category = flag.category or '' self.choices = [] self.group = '' self.hidden = flag.help == argparse.SUPPRESS self.is_global = flag.is_global # ArgParse does not have an explicit Boolean flag type. By # convention a flag with arg.nargs=0 and action='store_true' or # action='store_false' is a Boolean flag. arg.type gives no hint # (arg.type=bool would have been so easy) and we don't have access # to args.action here. Even then the flag can take on non-Boolean # values. If arg.default is not specified then it will be None, but # it can be set to anything. So we do a conservative 'truthiness' # test here. if flag.nargs == 0: self.type = 'bool' self.default = bool(flag.default) else: if (isinstance(flag.type, (int, long)) or isinstance(flag.default, (int, long))): self.type = 'int' elif isinstance(flag.type, float) or isinstance( flag.default, float): self.type = 'float' elif isinstance(flag.type, arg_parsers.ArgDict): self.type = 'dict' elif isinstance(flag.type, arg_parsers.ArgList): self.type = 'list' else: self.type = module_util.GetModulePath(flag.type) or 'string' if flag.choices: choices = sorted(flag.choices) if choices == ['false', 'true']: self.type = 'bool' else: self.choices = flag.choices self.required = flag.required if getattr(flag, LOOKUP_INVERTED_SYNOPSIS, False): self.attr[LOOKUP_INVERTED_SYNOPSIS] = True prop, kind, value = getattr(flag, 'store_property', (None, None, None)) if prop: # This allows actions.Store*Property() to be reconstituted. attr = {LOOKUP_NAME: str(prop)} if kind == 'bool': flag.type = 'bool' if value: attr[LOOKUP_VALUE] = value self.attr[LOOKUP_PROPERTY] = attr
def _GetTableName(self, suffix_list=None): """Returns the table name; the module path if no collection. Args: suffix_list: a list of values to attach to the end of the table name. Typically, these will be aggregator values, like project ID. Returns: a name to use for the table in the cache DB. """ if self.collection: name = [self.collection] else: name = [module_util.GetModulePath(self)] if suffix_list: name.extend(suffix_list) return '.'.join(name)
def __init__(self, arg, name): completer = getattr(arg, 'completer', None) if isinstance(completer, type): self.completer = module_util.GetModulePath(completer) or '' else: # Legacy completer. self.completer = None self.default = arg.default self.description = _NormalizeDescription(_GetDescription(arg)) self.name = name self.nargs = str(arg.nargs or 0) self.required = False if arg.metavar: self.value = arg.metavar else: self.value = name.lstrip('-').replace('-', '_').upper() self._Scrub()
def __init__(self, arg, name): completer = getattr(arg, LOOKUP_COMPLETER, None) if completer: try: # A calliope.parser_completer.ArgumentCompleter object. completer_class = completer.completer_class except AttributeError: # An argparse callable completer. completer_class = completer completer = module_util.GetModulePath(completer_class) self.completer = completer self.default = arg.default self.description = _NormalizeDescription(_GetDescription(arg)) self.name = name self.nargs = str(arg.nargs or 0) self.required = False if arg.metavar: self.value = arg.metavar else: self.value = name.lstrip('-').replace('-', '_').upper() self._Scrub()
def __init__(self, arg, name): super(FlagOrPositional, self).__init__(arg) self.category = getattr(arg, LOOKUP_CATEGORY, '') completer = getattr(arg, LOOKUP_COMPLETER, None) if completer: try: # A calliope.parser_completer.ArgumentCompleter object. completer_class = completer.completer_class except AttributeError: # An argparse callable completer. completer_class = completer completer = module_util.GetModulePath(completer_class) self.completer = completer self.default = arg.default self.description = _NormalizeDescription(_GetDescription(arg)) self.name = unicode(name) self.nargs = str(arg.nargs or 0) if arg.metavar: self.value = unicode(arg.metavar) else: self.value = self.name.lstrip('-').replace('-', '_').upper() self._Scrub()
def testGetModulePathModule(self): self.assertEqual(None, module_util.GetModulePath(files))
def testGetModulePathVariable(self): self.assertEqual(None, module_util.GetModulePath(files.NUM_RETRIES))
def _GetTableName(self): """Returns the table name [prefix], the module path if no collection.""" if self.collection: return self.collection return module_util.GetModulePath(self)
def testGetModulePathObject(self): self.assertEqual( 'googlecloudsdk.core.util.files:Error', module_util.GetModulePath(files.Error('Something happened')))
def testGetModulePathFunction(self): self.assertEqual('googlecloudsdk.core.util.files:CopyTree', module_util.GetModulePath(files.CopyTree))
def testGetModulePathNumber(self): self.assertEqual(None, module_util.GetModulePath(1))
def testGetModulePathClass(self): self.assertEqual('googlecloudsdk.core.util.files:Error', module_util.GetModulePath(files.Error))
def testGetModulePathFilesCompleter(self): self.assertEqual( 'argcomplete.completers:FilesCompleter', module_util.GetModulePath(argcomplete_completers.FilesCompleter))
def testGetModulePathNoCacheCompleter(self): self.assertEqual( 'googlecloudsdk.command_lib.util.completers:NoCacheCompleter', module_util.GetModulePath(completers.NoCacheCompleter))
def testGetModulePathResourceParamCompleter(self): self.assertEqual( 'googlecloudsdk.command_lib.util.completers:ResourceParamCompleter', module_util.GetModulePath(completers.ResourceParamCompleter))
def testGetModulePathBuiltin(self): self.assertEqual(None, module_util.GetModulePath(int))
def testGetModulePathNone(self): self.assertEqual(None, module_util.GetModulePath(None))