def Run(self, args): self.ref = self.CreateReference(args) get_request = self.GetGetRequest(args) errors = [] objects = list(request_helper.MakeRequests( requests=[get_request], http=self.http, batch_url=self.batch_url, errors=errors, custom_get_requests=None)) if errors: utils.RaiseToolException( errors, error_message='There was a problem fetching the resource:') new_object = self.Modify(args, objects[0]) # If existing object is equal to the proposed object or if # Modify() returns None, then there is no work to be done, so we # print the resource and return. if not new_object or objects[0] == new_object: for resource in lister.ProcessResults( resources=[objects[0]], field_selector=property_selector.PropertySelector( properties=None, transformations=self.transformations)): yield resource return resources = request_helper.MakeRequests( requests=[self.GetSetRequest(args, new_object, objects[0])], http=self.http, batch_url=self.batch_url, errors=errors, custom_get_requests=None) resources = lister.ProcessResults( resources=resources, field_selector=property_selector.PropertySelector( properties=None, transformations=self.transformations)) for resource in resources: yield resource if errors: utils.RaiseToolException( errors, error_message='There was a problem modifying the resource:')
def Run(self, args): sort_key_fn = None descending = False errors = [] if args.uri: field_selector = None else: field_selector = property_selector.PropertySelector( properties=None, transformations=self._FIELD_TRANSFORMS) sort_key_fn, descending = GetSortKey(args.sort_by, self._LIST_TABS) responses, errors = self.GetResources(args) if errors: utils.RaiseToolException(errors) items = lister.ProcessResults( resources=list(_UnwrapResponse(responses, self.list_field)), field_selector=field_selector, sort_key_fn=sort_key_fn, reverse_sort=descending, limit=args.limit) for item in items: if args.uri: yield item['instance'] else: yield item
def Run(self, args): """Yields JSON-serializable dicts of resources.""" # The field selector should be constructed before any resources # are fetched, so if there are any syntactic errors with the # fields, we can fail fast. field_selector = property_selector.PropertySelector(properties=args.fields) ref = self.CreateReference(args) get_request_class = self.service.GetRequestType(self.method) request = get_request_class(project=self.project) self.SetNameField(ref, request) self.ScopeRequest(ref, request) get_request = (self.service, self.method, request) errors = [] objects = request_helper.MakeRequests( requests=[get_request], http=self.http, batch_url=self.batch_url, errors=errors, custom_get_requests=None) resources = lister.ProcessResults(objects, field_selector) resources = list(self.ComputeDynamicProperties(args, resources)) if errors: utils.RaiseToolException( errors, error_message='Could not fetch resource:') return resources[0]
def ProcessEditedResource(self, file_contents, args): """Returns an updated resource that was edited by the user.""" # It's very important that we replace the characters of comment # lines with spaces instead of removing the comment lines # entirely. JSON and YAML deserialization give error messages # containing line, column, and the character offset of where the # error occurred. If the deserialization fails; we want to make # sure those numbers map back to what the user actually had in # front of him or her otherwise the errors will not be very # useful. non_comment_lines = '\n'.join( ' ' * len(line) if line.startswith('#') else line for line in file_contents.splitlines()) modified_record = _DeserializeValue(non_comment_lines, args.format or BaseEdit.DEFAULT_FORMAT) # Normalizes all of the fields that refer to other # resource. (i.e., translates short names to URIs) reference_normalizer = property_selector.PropertySelector( transformations=self.reference_normalizers) modified_record = reference_normalizer.Apply(modified_record) if self.modifiable_record == modified_record: new_object = None else: modified_record['name'] = self.original_record['name'] fingerprint = self.original_record.get('fingerprint') if fingerprint: modified_record['fingerprint'] = fingerprint new_object = encoding.DictToMessage( modified_record, self._resource_spec.message_class) # If existing object is equal to the proposed object or if # there is no new object, then there is no work to be done, so we # return the original object. if not new_object or self.original_object == new_object: return [self.original_object] errors = [] resources = list(request_helper.MakeRequests( requests=[self.GetSetRequest(args, new_object, self.original_object)], http=self.http, batch_url=self.batch_url, errors=errors, custom_get_requests=None)) if errors: utils.RaiseToolException( errors, error_message='Could not update resource:') return resources
def Run(self, args): field_selector = property_selector.PropertySelector( properties=None, transformations=[]) sort_key_fn, descending = GetSortKey(args.sort_by, self._COLUMNS) responses, errors = self._GetResources(args) if errors: utils.RaiseToolException(errors) return lister.ProcessResults( resources=list(_UnwrapResponse(responses, 'namedPorts')), field_selector=field_selector, sort_key_fn=sort_key_fn, reverse_sort=descending, limit=args.limit)
def Run(self, args, request_protobufs=None, service=None): if request_protobufs is None: request_protobufs = self.CreateRequests(args) if service is None: service = self.service requests = [] # If a method is not passed as part of a tuple then use the self.method # default for request in request_protobufs: if isinstance(request, tuple): method = request[0] proto = request[1] else: method = self.method proto = request requests.append((service, method, proto)) errors = [] # We want to run through the generator that MakeRequests returns in order to # actually make the requests, since these requests mutate resources. resources = list(request_helper.MakeRequests( requests=requests, http=self.http, batch_url=self.batch_url, errors=errors, custom_get_requests=self.custom_get_requests)) resources = lister.ProcessResults( resources=resources, field_selector=property_selector.PropertySelector( properties=None, transformations=self.transformations)) if errors: utils.RaiseToolException(errors) return resources
def Run(self, args): """Yields JSON-serializable dicts of resources or self links.""" # Data structures used to perform client-side filtering of # resources by their names and/or URIs. self.self_links = set() self.names = set() self.resource_refs = [] if args.uri: field_selector = None else: # The field selector should be constructed before any resources # are fetched, so if there are any syntactic errors with the # fields, we can fail fast. field_selector = property_selector.PropertySelector( properties=None, transformations=self.transformations) if args.sort_by: if args.sort_by.startswith('~'): sort_by = args.sort_by[1:] descending = True else: sort_by = args.sort_by descending = False for col_name, path in self._resource_spec.table_cols: if sort_by == col_name: sort_by = path break if isinstance(sort_by, property_selector.PropertyGetter): property_getter = sort_by else: property_getter = property_selector.PropertyGetter(sort_by) sort_key_fn = property_getter.Get else: sort_key_fn = None descending = False errors = [] self.PopulateResourceFilteringStructures(args) items = self.FilterResults(args, self.GetResources(args, errors)) items = lister.ProcessResults( resources=items, field_selector=field_selector, sort_key_fn=sort_key_fn, reverse_sort=descending, limit=args.limit) items = self.ComputeDynamicProperties(args, items) for item in items: if args.uri: yield item['selfLink'] else: yield item if errors: utils.RaiseToolException(errors)
def Run(self, args): self.ref = self.CreateReference(args) get_request = self.GetGetRequest(args) errors = [] objects = list(request_helper.MakeRequests( requests=[get_request], http=self.http, batch_url=self.batch_url, errors=errors, custom_get_requests=None)) if errors: utils.RaiseToolException( errors, error_message='Could not fetch resource:') self.original_object = objects[0] self.original_record = encoding.MessageToDict(self.original_object) # Selects only the fields that can be modified. field_selector = property_selector.PropertySelector( properties=self._resource_spec.editables) self.modifiable_record = field_selector.Apply(self.original_record) buf = cStringIO.StringIO() for line in _HELP.splitlines(): buf.write('#') if line: buf.write(' ') buf.write(line) buf.write('\n') buf.write('\n') buf.write(_SerializeDict(self.modifiable_record, args.format or BaseEdit.DEFAULT_FORMAT)) buf.write('\n') example = _SerializeDict( encoding.MessageToDict(self.example_resource), args.format or BaseEdit.DEFAULT_FORMAT) _WriteResourceInCommentBlock(example, 'Example resource:', buf) buf.write('#\n') original = _SerializeDict(self.original_record, args.format or BaseEdit.DEFAULT_FORMAT) _WriteResourceInCommentBlock(original, 'Original resource:', buf) file_contents = buf.getvalue() while True: try: file_contents = edit.OnlineEdit(file_contents) except edit.NoSaveException: raise calliope_exceptions.ToolException('Edit aborted by user.') try: resources = self.ProcessEditedResource(file_contents, args) break except (ValueError, yaml.error.YAMLError, protorpc.messages.ValidationError, calliope_exceptions.ToolException) as e: if isinstance(e, ValueError): message = e.message else: message = str(e) if isinstance(e, calliope_exceptions.ToolException): problem_type = 'applying' else: problem_type = 'parsing' message = ('There was a problem {0} your changes: {1}' .format(problem_type, message)) if not console_io.PromptContinue( message=message, prompt_string='Would you like to edit the resource again?'): raise calliope_exceptions.ToolException('Edit aborted by user.') resources = lister.ProcessResults( resources=resources, field_selector=property_selector.PropertySelector( properties=None, transformations=self.transformations)) for resource in resources: yield resource