Ejemplo n.º 1
0
    def GetValue(self, parameter_name, check_properties=True):
        """Returns the program state value for parameter_name.

    Args:
      parameter_name: The parameter name.
      check_properties: bool, whether to check the properties (unused).

    Returns:
      The program state value for parameter_name.
    """
        del check_properties  # Unused.
        attribute_name = (
            self.resource_info.resource_spec.AttributeName(parameter_name))
        current = properties.VALUES.core.disable_prompts.GetBool()
        # TODO(b/73073941): Come up with a better way to temporarily disable
        # prompts. This prevents arbitrary fallthroughs with prompting from
        # being run during completion.
        properties.VALUES.core.disable_prompts.Set(True)
        try:
            return deps.Get(
                attribute_name,
                self.resource_info.BuildFullFallthroughsMap(),
                parsed_args=self.parsed_args) if attribute_name else None
        except deps.AttributeNotFoundError:
            return None
        finally:
            properties.VALUES.core.disable_prompts.Set(current)
Ejemplo n.º 2
0
 def _GetSpecifiedAttributes(self,
                             fallthroughs_map,
                             parsed_args=None,
                             allow_inactive=False):
     """Get a list of attributes that are actively specified in runtime."""
     specified = []
     final_map = {}
     if allow_inactive:
         final_map = {
             attr: fallthroughs
             for attr, fallthroughs in six.iteritems(fallthroughs_map)
         }
     else:
         final_map = {
             attr: filter(operator.attrgetter('active'), fallthroughs)
             for attr, fallthroughs in six.iteritems(fallthroughs_map)
         }
     for attribute in self.attributes:
         try:
             value = deps_lib.Get(attribute.name,
                                  final_map,
                                  parsed_args=parsed_args)
         except deps_lib.AttributeNotFoundError:
             continue
         if value:
             specified.append(attribute)
     return specified
Ejemplo n.º 3
0
 def testGet_ArgsGiven(self):
     """Test the deps object can initialize attributes using ArgFallthrough."""
     fallthroughs_map = {
         'name': [deps.ArgFallthrough('--myresource-name')],
         'project': [
             deps.ArgFallthrough('--myresource-project'),
             deps.ArgFallthrough('--project'),
             deps.PropertyFallthrough(properties.VALUES.core.project)
         ]
     }
     parsed_args = self._GetMockNamespace(
         myresource_name='example', myresource_project='exampleproject')
     self.assertEqual(
         'example',
         deps.Get('name', fallthroughs_map, parsed_args=parsed_args))
     self.assertEqual(
         'exampleproject',
         deps.Get('project', fallthroughs_map, parsed_args=parsed_args))
Ejemplo n.º 4
0
 def _AnyAnchorIsSpecified(self, fallthroughs_map, parsed_args=None):
   """Helper function to determine if any anchor arg was given."""
   errors = []
   for attribute in self.attributes:
     if self.IsAnchor(attribute):
       try:
         deps_lib.Get(attribute.name, fallthroughs_map,
                      parsed_args=parsed_args)
         return True, []
       except deps_lib.AttributeNotFoundError as e:
         errors.append(str(e))
   return False, errors
Ejemplo n.º 5
0
 def testGet_AnotherProperty(self):
     """Test the deps object handles non-project property.
 """
     properties.VALUES.compute.zone.Set('us-east1b')
     result = deps.Get(
         'zone', {
             'zone': [
                 deps.ArgFallthrough('--myresource-zone'),
                 deps.PropertyFallthrough(properties.VALUES.compute.zone)
             ]
         },
         parsed_args=self._GetMockNamespace(myresource_zone=None))
     self.assertEqual('us-east1b', result)
Ejemplo n.º 6
0
 def testGet_UseProperty(self):
     """Test the deps object can initialize attributes using PropertyFallthrough.
 """
     result = deps.Get(
         'project', {
             'project': [
                 deps.ArgFallthrough('--myresource-project'),
                 deps.ArgFallthrough('--project'),
                 deps.PropertyFallthrough(properties.VALUES.core.project)
             ]
         },
         parsed_args=self._GetMockNamespace(myresource_project=None))
     self.assertEqual(self.Project(), result)
    def Initialize(self, fallthroughs_map, parsed_args=None):
        """Initializes a resource given its fallthroughs.

    If the attributes have a property or arg fallthrough but the full
    resource name is provided to the anchor attribute flag, the information
    from the resource name is used over the properties and args. This
    preserves typical resource parsing behavior in existing surfaces.

    Args:
      fallthroughs_map: {str: [deps_lib._FallthroughBase]}, a dict of finalized
        fallthroughs for the resource.
      parsed_args: the argparse namespace.

    Returns:
      (googlecloudsdk.core.resources.Resource) the fully initialized resource.

    Raises:
      googlecloudsdk.calliope.concepts.concepts.InitializationError, if the
        concept can't be initialized.
    """
        params = {}

        # Returns a function that can be used to parse each attribute, which will be
        # used only if the resource parser does not receive a fully qualified
        # resource name.
        def LazyGet(name):
            f = lambda: deps_lib.Get(
                name, fallthroughs_map, parsed_args=parsed_args)
            return f

        for attribute in self.attributes:
            params[self.ParamName(attribute.name)] = LazyGet(attribute.name)
        self._resources.RegisterApiByName(self._collection_info.api_name,
                                          self._collection_info.api_version)
        try:
            return self._resources.Parse(deps_lib.Get(self.anchor.name,
                                                      fallthroughs_map,
                                                      parsed_args=parsed_args),
                                         collection=self.collection,
                                         params=params)
        except deps_lib.AttributeNotFoundError as e:
            raise InitializationError(
                'The [{}] resource is not properly specified.\n'
                '{}'.format(self.name, six.text_type(e)))
        except resources.UserError as e:
            raise InitializationError(six.text_type(e))
Ejemplo n.º 8
0
 def testGet_BothFail(self):
     """Test the deps object raises an error if an attribute can't be found."""
     self.UnsetProject()
     fallthroughs_map = {
         'project': [
             deps.ArgFallthrough('--myresource-project'),
             deps.ArgFallthrough('--project'),
             deps.PropertyFallthrough(properties.VALUES.core.project)
         ]
     }
     parsed_args = self._GetMockNamespace(myresource_project=None)
     regex = re.escape(
         'Failed to find attribute [project]. The attribute can be set in the '
         'following ways: \n'
         '- provide the argument [--myresource-project] on the command line\n'
         '- provide the argument [--project] on the command line\n'
         '- set the property [core/project]')
     with self.assertRaisesRegex(deps.AttributeNotFoundError, regex):
         deps.Get('project', fallthroughs_map, parsed_args=parsed_args)
Ejemplo n.º 9
0
 def testGet_BothFail_AnotherProperty(self):
     """Test the deps error has the correct message for non-project properties.
 """
     properties.VALUES.compute.zone.Set(None)
     fallthroughs_map = {
         'zone': [
             deps.ArgFallthrough('--myresource-zone'),
             deps.PropertyFallthrough(properties.VALUES.compute.zone),
             deps.Fallthrough(lambda: None, 'custom hint')
         ]
     }
     parsed_args = self._GetMockNamespace(myresource_zone=None)
     regex = re.escape(
         'Failed to find attribute [zone]. The attribute can be set in the '
         'following ways: \n'
         '- provide the argument [--myresource-zone] on the command line\n'
         '- set the property [compute/zone]\n'
         '- custom hint')
     with self.assertRaisesRegex(deps.AttributeNotFoundError, regex):
         deps.Get('zone', fallthroughs_map, parsed_args=parsed_args)
Ejemplo n.º 10
0
 def LazyGet(name):
     f = lambda: deps_lib.Get(
         name, fallthroughs_map, parsed_args=parsed_args)
     return f
Ejemplo n.º 11
0
 def testGet_Plural(self, fallthroughs, val, expected):
     properties.VALUES.compute.zone.Set(val)
     result = deps.Get('resource', {'resource': fallthroughs},
                       parsed_args=self._GetMockNamespace(resources=val))
     self.assertEqual(expected, result)