Ejemplo n.º 1
0
    def GetTransforms(self):
        """Returns the combined transform symbols dict.

    Returns:
      The builtin transforms combined with the collection specific transforms
      if any.
    """
        if self._transforms:
            # Return the memoized transforms.
            return self._transforms

        all_transforms = []

        # The builtin transforms are always available.
        all_transforms.append(resource_transform.GetTransforms())

        # Check if there are any collection specific transforms.
        if self.collection:
            transforms = resource_transform.GetTransforms(self.collection)
            if transforms:
                all_transforms.append(transforms)

        # Check is there are explicit ResourceInfo transforms.
        if self.transforms:
            all_transforms.append(self.transforms)

        # Combine the transform dicts in order.
        if len(all_transforms) == 1:
            self._transforms = all_transforms[0]
        else:
            self._transforms = {}
            for transforms in all_transforms:
                self._transforms.update(transforms)

        return self._transforms
Ejemplo n.º 2
0
def TransformRegistryDescriptions():
  """Returns help markdown for all registered resource transforms."""
  if not resource_registry.RESOURCE_REGISTRY:
    raise ValueError('The resource_registry refactor is complete. '
                     'Delete this if-else and celebrate.')
  else:
    for api in set([x.split('.')[0]
                    for x in resource_registry.RESOURCE_REGISTRY.keys()]):
      if api in _TRANSFORMS:
        raise ValueError('The {api} api has new and legacy transforms '
                         'registered -- pick one or the other.', api=api)
      transforms = resource_transform.GetTransforms(api)
      if transforms:
        _TRANSFORMS[api] = transforms

  descriptions = []

  def _AddDescription(api, transforms):
    descriptions.append(
        '\nThe {api} transform functions are:\n{desc}\n'.format(
            api=api, desc=_TransformsDescriptions(transforms)))

  _AddDescription('builtin', resource_transform.GetTransforms())
  for api, transforms in sorted(_TRANSFORMS.iteritems()):
    _AddDescription(api, transforms)

  return ''.join(descriptions)
Ejemplo n.º 3
0
def Printer(print_format, out=None, defaults=None):
    """Returns a resource printer given a format string.

  Args:
    print_format: The _FORMATTERS name with optional attributes and projection.
    out: Output stream, log.out if None.
    defaults: Optional resource_projection_spec.ProjectionSpec defaults.

  Raises:
    UnknownFormatError: The print_format is invalid.

  Returns:
    An initialized ResourcePrinter class or None if printing is disabled.
  """

    projector = resource_projector.Compile(
        expression=print_format,
        defaults=defaults,
        symbols=resource_transform.GetTransforms())
    projection = projector.Projection()
    printer_name = projection.Name()
    try:
        printer_class = _FORMATTERS[printer_name]
    except KeyError:
        raise UnknownFormatError(
            'Format must be one of {0}; received [{1}]'.format(
                ', '.join(SupportedFormats()), printer_name))
    printer = printer_class(out=out,
                            name=printer_name,
                            attributes=projection.Attributes(),
                            column_attributes=projection,
                            process_record=projector.Evaluate)
    projector.SetByColumns(printer.ByColumns())
    return printer
Ejemplo n.º 4
0
def TransformRegistryDescriptions():
  """Returns help markdown for all registered resource transforms."""
  apis = set([x.split('.')[0]
              for x in resource_registry.RESOURCE_REGISTRY.keys()])
  descriptions = []
  for api in ['builtin'] + sorted(apis):
    transforms = resource_transform.GetTransforms(api)
    if transforms:
      descriptions.append(
          '\nThe {api} transform functions are:\n{desc}\n'.format(
              api=api, desc=_TransformsDescriptions(transforms)))
  return ''.join(descriptions)
Ejemplo n.º 5
0
def _GetApiTransforms(api):
    """Returns the transforms for api if it has a transforms module."""
    if api == 'builtin':
        return resource_transform.GetTransforms()
    # Include all api_lib.*.transforms modules that have GetTransforms().
    method_name = 'GetTransforms'
    module_path = 'googlecloudsdk.api_lib.{api}.transforms'.format(api=api)
    try:
        module = __import__(module_path, fromlist=[method_name])
        method = getattr(module, method_name)
        return method()
    except ImportError:
        return None
    def GetTransforms(self):
        """Returns the combined transform symbols dict.

    Returns:
      The builtin transforms combined with the collection specific transforms
      if any.
    """
        if self.transforms:
            return self.transforms

        # The builtin transforms are always available.
        self.transforms = resource_transform.GetTransforms()

        # Check if there are any collection specific transforms.
        specific_transforms = resource_transform.GetTransforms(self.collection)
        if not specific_transforms:
            return self.transforms
        builtin_transforms = self.transforms
        self.transforms = {}
        self.transforms.update(builtin_transforms)
        self.transforms.update(specific_transforms)
        return self.transforms
Ejemplo n.º 7
0
def Printer(print_format, out=None, defaults=None, console_attr=None):
    """Returns a resource printer given a format string.

  Args:
    print_format: The _FORMATTERS name with optional attributes and projection.
    out: Output stream, log.out if None.
    defaults: Optional resource_projection_spec.ProjectionSpec defaults.
    console_attr: The console attributes for the output stream. Ignored by some
      printers. If None then printers that require it will initialize it to
      match out.

  Raises:
    UnknownFormatError: The print_format is invalid.

  Returns:
    An initialized ResourcePrinter class or None if printing is disabled.
  """
    projector = resource_projector.Compile(
        expression=print_format,
        defaults=resource_projection_spec.ProjectionSpec(
            defaults=defaults, symbols=resource_transform.GetTransforms()))
    printer_name = projector.Projection().Name()
    if not printer_name:
        return None
    try:
        printer_class = _FORMATTERS[printer_name]
    except KeyError:
        raise UnknownFormatError("""\
Format must be one of {0}; received [{1}].

For information on output formats:
  $ gcloud topic formats
""".format(', '.join(SupportedFormats()), printer_name))
    # TODO(user): move to top-level gcloud exception handler
    printer = printer_class(out=out,
                            name=printer_name,
                            printer=Printer,
                            projector=projector,
                            console_attr=console_attr)
    return printer
Ejemplo n.º 8
0
 def GetDisplayInfo(self):
   symbols = {}
   symbols.update(compute_transforms.GetTransforms())
   symbols.update(core_transforms.GetTransforms())
   return MockDisplayInfo(transforms=symbols)
 def _MockGetApiTransforms(api):
     if api == 'builtin':
         return resource_transform.GetTransforms()
     return None