def testParse(self): self.assertEqual(properties.VALUES.core.account, properties.FromString('account')) self.assertEqual(properties.VALUES.core.account, properties.FromString('core/account')) self.assertEqual(None, properties.FromString('')) with self.assertRaises(properties.NoSuchPropertyError): properties.FromString('asdf')
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
def Run(self, args): scope = (properties.Scope.INSTALLATION if args.installation else properties.Scope.USER) prop = properties.FromString(args.property) if not prop: raise c_exc.InvalidArgumentException( 'property', 'Must be in the form: [SECTION/]PROPERTY') properties.PersistProperty(prop, args.value, scope=scope) scope_msg = '' if args.installation: scope_msg = 'installation ' log.status.Print('Updated {0}property [{1}].'.format(scope_msg, prop)) if prop == properties.VALUES.core.project: config_validators.WarnIfSettingProjectWithNoAccess( scope, prop.Get()) if prop == properties.VALUES.context_aware.use_client_certificate: config_validators.WarnIfActivateUseClientCertificate(prop) if prop == properties.VALUES.compute.zone: config_validators.WarnIfSettingNonExistentRegionZone(prop.Get(), zonal=True) if prop == properties.VALUES.compute.region: config_validators.WarnIfSettingNonExistentRegionZone(prop.Get(), zonal=False)
def Run(self, args): scope = (properties.Scope.INSTALLATION if args.installation else properties.Scope.USER) prop = properties.FromString(args.property) if not prop: raise c_exc.InvalidArgumentException( 'property', 'Must be in the form: [SECTION/]PROPERTY') scope_msg = '' if args.installation: scope_msg = 'installation ' if prop == properties.VALUES.context_aware.use_client_certificate: config_validators.WarnIfActivateUseClientCertificate(args.value) showed_warning = False if prop == properties.VALUES.core.project: showed_warning = config_validators.WarnIfSettingProjectWithNoAccess( scope, args.value) if prop == properties.VALUES.compute.zone: showed_warning = config_validators.WarnIfSettingNonExistentRegionZone( args.value, zonal=True) if prop == properties.VALUES.compute.region: showed_warning = config_validators.WarnIfSettingNonExistentRegionZone( args.value, zonal=False) if showed_warning and not args.quiet and console_io.CanPrompt(): if not console_io.PromptContinue( 'Are you sure you wish to set {0}property [{1}] to {2}?'.format( scope_msg, prop, args.value)): return properties.PersistProperty(prop, args.value, scope=scope) log.status.Print('Updated {0}property [{1}].'.format(scope_msg, prop))
def _Inner(command): expected_command, props, error = data.pop(0) self.assertEqual(expected_command, command) for p, v in six.iteritems(props): self.assertEqual(v, properties.FromString(p).Get()) if error: calliope_exceptions._Exit(error)
def _CreateAttribute(data): """Creates a single resource attribute from YAML data. Args: data: {}, The dict of data from the YAML file for this single attribute. Returns: ResourceParameterAttributeConfig, the generated attribute. """ attribute_name = data['attribute_name'] help_text = data['help'] fallthrough_paths = data.get('fallthroughs', []) fallthroughs = [ deps.Fallthrough(util.Hook.FromPath(p), hint='') for p in fallthrough_paths ] prop_string = data.get('property') prop = properties.FromString(prop_string) if prop_string else None prop = prop or _DEFAULT_PROPS.get(attribute_name) if prop: fallthroughs.insert(0, deps.PropertyFallthrough(prop)) completer = data.get('completer') attribute = concepts.ResourceParameterAttributeConfig( name=attribute_name, help_text=help_text, completer=completer, fallthroughs=fallthroughs) return (data['parameter_name'], attribute)
def LocationAttributeConfig(): return concepts.ResourceParameterAttributeConfig( name='location', fallthroughs=[ deps.PropertyFallthrough( properties.FromString('dataplex/location')) ], help_text='The location of the Dataplex resource.')
def _prepareEmptyConfigAndExpectProjectCreation(self): self.StartPropertyPatch(config.Paths, 'sdk_root', return_value=self.temp_path) prop = properties.FromString('core/project') self.assertEqual(prop.Get(), None) test_project = util.GetTestActiveProjectWithSameNameAndId() self._expectCreationCall(test_project) self._expectServiceEnableCall(test_project.projectId) return prop, test_project.projectId
def Run(self, args): scope = (properties.Scope.INSTALLATION if args.installation else properties.Scope.USER) prop = properties.FromString(args.property) if not prop: raise c_exc.InvalidArgumentException( 'property', 'Must be in the form: [SECTION/]PROPERTY') properties.PersistProperty(prop, args.value, scope=scope)
def RunUnset(cmd, args): """Unsets a property.""" prop = properties.FromString(args.property) if not prop: raise c_exc.InvalidArgumentException( 'property', 'Must be in the form: [SECTION/]PROPERTY') properties.PersistProperty(prop, None, scope=cmd.group.RequestedScope(args))
def Run(self, args): """Default Run method implementation.""" flags.CheckParentFlags(args, parent_required=False) project_id = args.id if not project_id and args.name: candidate = command_lib_util.IdFromName(args.name) if candidate and console_io.PromptContinue( 'No project id provided.', 'Use [{}] as project id'.format(candidate), throw_if_unattended=True): project_id = candidate if not project_id: raise exceptions.RequiredArgumentException( 'PROJECT_ID', 'an id must be provided for the new project') project_ref = command_lib_util.ParseProject(project_id) labels = labels_util.ParseCreateArgs( args, projects_util.GetMessages().Project.LabelsValue) try: create_op = projects_api.Create( project_ref, display_name=args.name, parent=projects_api.ParentNameToResourceId( flags.GetParentFromFlags(args)), labels=labels) except apitools_exceptions.HttpConflictError: msg = ( 'Project creation failed. The project ID you specified is ' 'already in use by another project. Please try an alternative ' 'ID.') core_exceptions.reraise(exceptions.HttpException(msg)) log.CreatedResource(project_ref, is_async=True) create_op = operations.WaitForOperation(create_op) # Enable cloudapis.googleapis.com if args.enable_cloud_apis: log.debug('Enabling cloudapis.googleapis.com') services_client = apis.GetClientInstance('servicemanagement', 'v1') enable_operation = services_enable_api.EnableServiceApiCall( project_ref.Name(), 'cloudapis.googleapis.com') enable_operation_ref = resources.REGISTRY.Parse( enable_operation.name, collection='servicemanagement.operations') services_util.WaitForOperation(enable_operation_ref, services_client) if args.set_as_default: project_property = properties.FromString('core/project') properties.PersistProperty(project_property, project_id) log.status.Print( 'Updated property [core/project] to [{0}].'.format(project_id)) return operations.ExtractOperationResponse( create_op, apis.GetMessagesModule('cloudresourcemanager', 'v1').Project)
def DeliveryPipelineAttributeConfig(): """Creates the delivery pipeline resource attribute.""" return concepts.ResourceParameterAttributeConfig( name='delivery-pipeline', fallthroughs=[ deps.PropertyFallthrough( properties.FromString('deploy/delivery_pipeline')) ], help_text='The delivery pipeline associated with the {resource}. ' ' Alternatively, set the property [deploy/delivery-pipeline].')
def LocationAttributeConfig(): """Builds an AttributeConfig for the location resource.""" return concepts.ResourceParameterAttributeConfig( name='location', fallthroughs=[ deps.PropertyFallthrough( properties.FromString('workflows/location')) ], help_text='Cloud location for the {resource}. ' ' Alternatively, set the property [workflows/location].')
def LocationAttributeConfig(): """Creates the location resource attribute.""" return concepts.ResourceParameterAttributeConfig( name='region', parameter_name='locationsId', fallthroughs=[ deps.PropertyFallthrough(properties.FromString('deploy/region')) ], help_text='The Cloud region for the {resource}. ' ' Alternatively, set the property [deploy/region].')
def LocationAttributeConfig(): """Builds an AttributeConfig for the location resource.""" return concepts.ResourceParameterAttributeConfig( name='location', fallthroughs=[ deps.PropertyFallthrough( properties.FromString('eventarc/location')) ], help_text="The location for the Eventarc {resource}, which should be " "either ``global'' or one of the supported regions. Alternatively, set " "the [eventarc/location] property.")
def RunSet(cmd, args): """Runs a config set command.""" requested_scope = cmd.group.RequestedScope(args) if not requested_scope: named_configs.TryEnsureWriteableNamedConfig() prop = properties.FromString(args.property) if not prop: raise c_exc.InvalidArgumentException( 'property', 'Must be in the form: [SECTION/]PROPERTY') properties.PersistProperty(prop, args.value, scope=requested_scope)
def testProjectChangedWithSetDefaultAndName(self): prop = properties.FromString('core/project') self.assertEqual(prop.Get(), None) test_project = util.GetTestProjectWithLongNameAndMatchingId() self._expectCreationCall(test_project) self._expectServiceEnableCall(test_project.projectId) self.RunProjects('create', '--quiet', '--set-as-default', '--name', test_project.name) self.assertEqual(prop.Get(), test_project.projectId) self.AssertOutputEquals('')
def Run(self, args): scope = (properties.Scope.INSTALLATION if args.installation else properties.Scope.USER) prop = properties.FromString(args.property) if not prop: raise c_exc.InvalidArgumentException( 'property', 'Must be in the form: [SECTION/]PROPERTY') properties.PersistProperty(prop, args.value, scope=scope) scope_msg = '' if args.installation: scope_msg = 'installation ' log.status.Print('Updated {0}property [{1}].'.format(scope_msg, prop))
def Run(self, args): """Runs this command.""" if args.scope: log.err.Print( 'The `--scope` flag is deprecated. Please run `gcloud ' 'help topic configurations` and `gcloud help config ' 'unset` for more information.') prop = properties.FromString(args.property) if not prop: raise c_exc.InvalidArgumentException( 'property', 'Must be in the form: [SECTION/]PROPERTY') properties.PersistProperty(prop, None, scope=flags.RequestedScope(args))
def testNoProject(self): self.mockConnection(user="******", host="my-host", port=123) prop = properties.FromString("project") properties.PersistProperty(prop, None, scope=properties.Scope.USER) self.Run("alpha cloud-shell ssh") self.ssh_init.assert_called_once_with( mock.ANY, remote=ssh.Remote(host="my-host", user="******"), port="123", identity_file=None, remote_command=["bash -l"], extra_flags=None, tty=True, options={"StrictHostKeyChecking": "no"}) self.authorize.assert_called()
def FromData(cls, data): """Constructs an attribute config from data defined in the yaml file. Args: data: {}, the dict of data from the YAML file for this single attribute. Returns: ResourceParameterAttributeConfig """ if not data: return None attribute_name = data['attribute_name'] parameter_name = data['parameter_name'] help_text = data['help'] completer = util.Hook.FromData(data, 'completer') completion_id_field = data.get('completion_id_field', None) completion_request_params_list = data.get('completion_request_params', []) completion_request_params = { param.get('fieldName'): param.get('value') for param in completion_request_params_list } # Add property fallthroughs. fallthroughs = [] prop = properties.FromString(data.get('property', '')) if prop: fallthroughs.append(deps_lib.PropertyFallthrough(prop)) default_config = DEFAULT_RESOURCE_ATTRIBUTE_CONFIGS.get(attribute_name) if default_config: fallthroughs += [ f for f in default_config.fallthroughs if f not in fallthroughs ] # Add fallthroughs from python hooks. fallthrough_data = data.get('fallthroughs', []) fallthroughs_from_hook = [ deps_lib.Fallthrough(util.Hook.FromPath(f['hook']), hint=f['hint']) for f in fallthrough_data ] fallthroughs += fallthroughs_from_hook return cls(name=attribute_name, help_text=help_text, fallthroughs=fallthroughs, completer=completer, completion_id_field=completion_id_field, completion_request_params=completion_request_params, parameter_name=parameter_name)
def Run(self, args): if args.scope: log.err.Print( 'The `--scope` flag is deprecated. Please run `gcloud ' 'help topic configurations` and `gcloud help config set` ' 'for more information.') requested_scope = flags.RequestedScope(args) if not requested_scope: named_configs.TryEnsureWriteableNamedConfig() prop = properties.FromString(args.property) if not prop: raise c_exc.InvalidArgumentException( 'property', 'Must be in the form: [SECTION/]PROPERTY') properties.PersistProperty(prop, args.value, scope=requested_scope)
def _CreateAttribute(data): """Creates a single resource attribute from YAML data. Args: data: {}, The dict of data from the YAML file for this single attribute. Returns: ResourceParameterAttributeConfig, the generated attribute. """ attribute_name = data['attribute_name'] help_text = data['help'] fallthrough_data = data.get('fallthroughs', []) fallthroughs = [ deps.Fallthrough(util.Hook.FromPath(f['hook']), hint=f['hint']) for f in fallthrough_data ] prop_string = data.get('property') prop = properties.FromString(prop_string) if prop_string else None if prop: fallthroughs.insert(0, deps.PropertyFallthrough(prop)) default_config = _DEFAULT_CONFIGS.get(attribute_name) if default_config: fallthroughs += [ fallthrough for fallthrough in default_config.fallthroughs if fallthrough not in fallthroughs ] completion_id_field = data.get('completion_id_field') completion_request_params = data.get('completion_request_params', []) final_params = { param.get('fieldName'): param.get('value') for param in completion_request_params } completer = data.get('completer') attribute = concepts.ResourceParameterAttributeConfig( name=attribute_name, help_text=help_text, completer=completer, fallthroughs=fallthroughs, completion_id_field=completion_id_field, completion_request_params=final_params) return (data['parameter_name'], attribute)
def testDeploy_regionProperty(self): workflow = self.messages.Workflow(sourceContents=NEW_SOURCE) source_path = self.Touch(self.temp_path, name='workflow.yaml', contents=NEW_SOURCE) region = 'europe-west1' workflow_name = self.GetWorkflowName(WORKFLOW_ID, region) self.ExpectGet(workflow_name, exception=http_error.MakeHttpError(code=404)) self.ExpectCreate(self.GetLocationName(region), WORKFLOW_ID, workflow) self.MockOperationWait() self.ExpectGet(workflow_name, result=workflow) prop = properties.FromString('workflows/location') prop.Set(region) result = self.Run('workflows deploy {id} --source={source} '.format( id=WORKFLOW_ID, source=source_path)) self.assertEqual(result, workflow)
def ValueCompleter(prefix, parsed_args, **unused_kwargs): prop = properties.FromString(getattr(parsed_args, 'property')) if not prop: # No property was given, or it was invalid. return if prop.choices: return [c for c in prop.choices if c.startswith(prefix)] if not prop.resource: # No collection associated with the property. return cli_generator = Set.GetCLIGenerator() if not cli_generator: return completer = remote_completion.RemoteCompletion.GetCompleterForResource( prop.resource, cli_generator, command_line=prop.resource_command_path) return completer(prefix=prefix, parsed_args=parsed_args, **unused_kwargs)
def _GetPropertyValue(self, dest): """Returns the property value for dest. Args: dest: The resource argument dest. Returns: The property value for dest. """ props = [] if self._api: props.append(self._api + '/' + dest) props.append(dest) for prop in props: try: return properties.FromString(prop).Get() except properties.NoSuchPropertyError: pass return None
def Flag(d): """Returns a flag object suitable for the calliope.markdown module.""" flag = type('flag', (object, ), d) flag.is_group = False flag.is_hidden = d.get(cli_tree.LOOKUP_IS_HIDDEN, d.get('hidden', False)) flag.hidden = flag.is_hidden flag.is_positional = False flag.is_required = d.get(cli_tree.LOOKUP_IS_REQUIRED, d.get(cli_tree.LOOKUP_REQUIRED, False)) flag.required = flag.is_required flag.help = flag.description flag.dest = flag.name.lower().replace('-', '_') flag.metavar = flag.value flag.option_strings = [flag.name] if not hasattr(flag, 'default'): flag.default = None if flag.type == 'bool': flag.nargs = 0 elif flag.nargs not in ('?', '*', '+'): flag.nargs = 1 if flag.type == 'dict': flag.type = arg_parsers.ArgDict() elif flag.type == 'list': flag.type = arg_parsers.ArgList() elif flag.type == 'string': flag.type = None if flag.attr.get(cli_tree.LOOKUP_INVERTED_SYNOPSIS): flag.inverted_synopsis = True prop = flag.attr.get('property') if prop: if cli_tree.LOOKUP_VALUE in prop: kind = 'value' value = prop[cli_tree.LOOKUP_VALUE] else: value = None kind = 'bool' if flag.type == 'bool' else None flag.store_property = (properties.FromString( prop[cli_tree.LOOKUP_NAME]), kind, value) return flag
def LocationAttributeConfig(required=True): """Builds an AttributeConfig for the location resource.""" fallthroughs_list = [ deps.PropertyFallthrough(properties.FromString('eventarc/location')) ] help_text = ('The location for the Eventarc {resource}, which should be ' "either ``global'' or one of the supported regions. " 'Alternatively, set the [eventarc/location] property.') if not required: fallthroughs_list.append( deps.Fallthrough( googlecloudsdk.command_lib.eventarc.flags.SetLocation, 'use \'-\' location to aggregate results for all Eventarc locations' )) help_text = ( 'The location for the Eventarc {resource}, which should be ' "either ``global'' or one of the supported regions. " "Use ``-'' to aggregate results for all Eventarc locations. " 'Alternatively, set the [eventarc/location] property.') return concepts.ResourceParameterAttributeConfig( name='location', fallthroughs=fallthroughs_list, help_text=help_text)
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
def Flag(d, is_global=False): """Returns a flag object suitable for the calliope.markdown module.""" flag = type('flag', (object, ), d) flag.help = argparse.SUPPRESS if flag.hidden else flag.description flag.is_global = is_global flag.dest = flag.value.lower().replace('-', '_') flag.metavar = flag.value flag.option_strings = [flag.name] if flag.type == 'bool': flag.nargs = 0 else: flag.nargs = 1 if flag.type == 'dict': flag.type = arg_parsers.ArgDict() elif flag.type == 'list': flag.type = arg_parsers.ArgList() elif flag.type == 'string': flag.type = None if not flag.group: flag.group = flag.name if flag.attr.get('inverted_synopsis'): flag.inverted_synopsis = True prop = flag.attr.get('property') if prop: if 'value' in prop: kind = 'value' value = prop['value'] else: value = None kind = 'bool' if flag.type == 'bool' else None flag.store_property = (properties.FromString(prop['name']), kind, value) return flag