def TransformUri(r, projection, undefined='.'): """Gets the resource URI. Args: r: A JSON-serializable object. projection: The parent ProjectionSpec. undefined: Returns this if a the URI for r cannot be determined. Returns: The URI for r or undefined if not defined. """ names = ('selfLink', 'SelfLink') def _GetAttr(attr): """Returns the string value for attr or None if the value is not a string. Args: attr: The attribute object to get the value from. Returns: The string value for attr or None if the value is not a string. """ try: attr = attr() except TypeError: pass return attr if isinstance(attr, (basestring, buffer)) else None if isinstance(r, (basestring, buffer)): if r.startswith('https://'): return r elif r: # Low hanging fruit first. for name in names: uri = _GetAttr(resource_property.Get(r, [name], None)) if uri: return uri if projection: collection_func = projection.symbols.get('collection', None) collection = collection_func(r) if collection_func else None if collection: # Generate the URI from the collection and a few params. instance = _GetAttr( resource_property.Get(r, ['instance'], None)) project = _GetAttr(resource_property.Get(r, ['project'], None)) try: uri = resources.Create(collection, project=project, instance=instance).SelfLink() except (resources.InvalidCollectionException, core_apis.UnknownAPIError, resources.UnknownCollectionException): uri = None if uri: return uri return undefined
def JobReferenceToResource(reference): """Converts a JobReference message to a Resource for a job. Args: reference: the JobReference message Returns: the resource """ return resources.Create( 'bigquery.jobs', projectId=reference.projectId, jobId=reference.projectId)
def MessageToResource(message, collection): """Convert a protorpclite Message to a gcloud Resource. Args: message: a protorpclite message collection: a collection from the resource_registry Returns: a resource of type Collection """ return resources.Create( collection, **dict([(field.name, message.get_assigned_value(field.name)) for field in message.__class__.all_fields()]))
def RemoteCompleter(parsed_args, **unused_kwargs): """Run list command on resource to generates completion options.""" resource = ro_resource command_line = ro_command_line options = [] try: if hasattr(parsed_args, 'property'): if parsed_args.property == 'compute/region': resource = 'compute.regions' command_line = resource elif parsed_args.property == 'compute/zone': resource = 'compute.zones' command_line = resource elif parsed_args.property != 'project': return options line = os.getenv('COMP_LINE') prefix = '' if line: for i in range(len(line)-1, -1, -1): c = line[i] if c == ' ' or c == '\t': break prefix = c + prefix command = command_line.split('.') + ['list'] project = properties.VALUES.core.project.Get(required=True) parms = {} if command[0] in _OPTIONAL_PARMS: for arg in _OPTIONAL_PARMS[command[0]]: for attrib in dict(arg): if hasattr(parsed_args, attrib): fun = arg[attrib] value = fun(parsed_args) if value: parms[attrib] = value command.append('--' + attrib) command.append(value) parms['project'] = project resource_link = resources.Parse('+', parms, resource, resolve=False) resource_link = resource_link.WeakSelfLink() lst = resource_link.split('*') resource_missing = len(lst) > 1 ccache = RemoteCompletion() options = ccache.GetFromCache(resource_link, prefix) if options is None: properties.VALUES.core.user_output_enabled.Set(False) ofile = RemoteCompletion.GetTickerStream() with CompletionProgressTracker(ofile): items = list(cli().Execute(command, call_arg_complete=False)) options = [] self_links = [] for item in items: # Get a selflink for the item if command[0] == 'compute': if 'selfLink' in item: instance_ref = resources.Parse(item['selfLink']) selflink = instance_ref.SelfLink() elif resource_link: selflink = resource_link.rstrip('+') + item['name'] elif _GETINSTANCEFUN: # List command provides a function to get the selflink selflink = _GETINSTANCEFUN(item) else: instance_ref = resources.Create(resource, project=item.project, instance=item.instance) selflink = instance_ref.SelfLink() self_links.append(selflink) lst = selflink.split('/') name = lst[-1] if not prefix or name.startswith(prefix): options.append(name) if self_links: ccache.StoreInCache(self_links) if resource_missing: options = ccache.GetFromCache(resource_link, prefix) if options: RemoteCompletion.CACHE_HITS -= 1 else: options = [] except Exception: # pylint:disable=broad-except logging.error(resource + 'completion command failed', exc_info=True) return [] return options
def GetRef(item): instance_ref = resources.Create('dns.managedZones', managedZone=item.name) return instance_ref.SelfLink()
def RemoteCompleter(parsed_args, **unused_kwargs): """Run list command on resource to generates completion options.""" options = [] try: line = os.getenv('COMP_LINE') prefix = '' if line: for i in range(len(line) - 1, -1, -1): c = line[i] if c == ' ' or c == '\t': break prefix = c + prefix command = command_line.split('.') + ['list'] project = properties.VALUES.core.project.Get(required=True) parms = {} if command[0] in _OPTIONAL_PARMS: for arg in _OPTIONAL_PARMS[command[0]]: for attrib in dict(arg): if hasattr(parsed_args, attrib): fun = arg[attrib] value = fun(parsed_args) if value: parms[attrib] = value command.append('--' + attrib) command.append(value) parms['project'] = project resource_link = resources.Parse('+', parms, resource, resolve=False) resource_link = resource_link.WeakSelfLink() lst = resource_link.split('*') resource_missing = len(lst) > 1 ccache = RemoteCompletion() options = ccache.GetFromCache(resource_link, prefix) pid = os.getpid() if options is None: properties.VALUES.core.user_output_enabled.Set(False) ofile = RemoteCompletion.GetTickerStream() tracker = CompletionProgressTracker(ofile) with tracker: items = RemoteCompletion.RunListCommand(cli, command) options = [] # the following is true if tracker forked and this is the parent if tracker.has_forked and os.getpid() == pid: return options self_links = [] for item in items: # Get a selflink for the item if command[0] == 'compute': if 'selfLink' in item: instance_ref = resources.Parse( item['selfLink']) selflink = instance_ref.SelfLink() elif resource_link: selflink = resource_link.rstrip( '+') + item['name'] elif _GETINSTANCEFUN: # List command provides a function to get the selflink selflink = _GETINSTANCEFUN(item) else: instance_ref = resources.Create( resource, project=item.project, instance=item.instance) selflink = instance_ref.SelfLink() self_links.append(selflink) lst = selflink.split('/') name = lst[-1] if not prefix or name.startswith(prefix): options.append(name) if self_links: ccache.StoreInCache(self_links) if tracker.has_forked: # the parent already exited, so exit the child sys.exit(0) if resource_missing: options = ccache.GetFromCache( resource_link, prefix, increment_counters=False) or [] except Exception: # pylint:disable=broad-except logging.error(resource + 'completion command failed', exc_info=True) return [] return options
def RemoteCompleter(parsed_args, **unused_kwargs): """Runs list command on resource to generate completion data.""" resource = ro_resource command_line = ro_command_line list_command_callback_fn = ro_list_command_callback_fn list_command_updates_cache = False info = resource_registry.Get(resource) if info.cache_command: command = info.cache_command.split(' ') elif list_command_callback_fn: command = list_command_callback_fn(parsed_args) else: command = command_line.split('.') + ['list'] if info.bypass_cache: # Don't cache - use the cache_command results directly. return RemoteCompletion.RunListCommand( cli, command, parse_output=True) list_command_updates_cache = True options = [] try: if hasattr(parsed_args, 'property'): if parsed_args.property == 'compute/region': resource = 'compute.regions' command = resource.split('.') + ['list'] elif parsed_args.property == 'compute/zone': resource = 'compute.zones' command = resource.split('.') + ['list'] elif parsed_args.property != 'project': return options line = os.getenv('COMP_LINE') prefix = '' if line: for i in range(len(line)-1, -1, -1): c = line[i] if c == ' ' or c == '\t': break prefix = c + prefix project = properties.VALUES.core.project.Get(required=True) parms = {} if command[0] in _OPTIONAL_PARMS: for arg in _OPTIONAL_PARMS[command[0]]: for attrib in dict(arg): if hasattr(parsed_args, attrib): fun = arg[attrib] value = fun(parsed_args) if value: parms[attrib] = value command.append('--' + attrib) command.append(value) parms['project'] = project resource_link = resources.Parse('+', parms, resource, resolve=False) resource_link = resource_link.WeakSelfLink() lst = resource_link.split('*') resource_missing = len(lst) > 1 ccache = RemoteCompletion() options = ccache.GetFromCache(resource_link, prefix) if options is not None: return options items = RemoteCompletion.RunListCommand( cli, command, list_command_updates_cache=list_command_updates_cache) if list_command_updates_cache: options = ccache.GetFromCache(resource_link, prefix) or [] if options: RemoteCompletion.CACHE_HITS -= 1 return options # This part can be dropped when all commands are subclassed. options = [] self_links = [] for item in items: # Get a selflink for the item if command[0] == 'compute': if 'selfLink' in item: instance_ref = resources.Parse(item['selfLink']) selflink = instance_ref.SelfLink() elif resource_link: selflink = resource_link.rstrip('+') + item['name'] else: instance_ref = resources.Create(resource, project=item.project, instance=item.instance) selflink = instance_ref.SelfLink() self_links.append(selflink) lst = selflink.split('/') name = lst[-1] if not prefix or name.startswith(prefix): options.append(name) if self_links: ccache.StoreInCache(self_links) if resource_missing: options = ccache.GetFromCache(resource_link, prefix, increment_counters=False) or [] except Exception: # pylint:disable=broad-except log.error(resource + 'completion command failed', exc_info=True) return [] return options
def GetRef(item): instance_ref = resources.Create('sql.instances', project=item.project, instance=item.name) return instance_ref.SelfLink()
def _GetUri(resource): return resources.Create(self.Collection(), managedZone=resource.name).SelfLink()
def _GetUri(resource): return resources.Create('sql.instances', project=resource.project, instance=resource.name).SelfLink()
def _GetUri(resource): return resources.Create(self.Collection(), project=resource.project, instance=resource.instance).SelfLink()