def Rewrite(self, expression, defaults=None):
    """Returns (frontend_expression, backend_expression) for expression.

    There are 3 outcomes:
      (None, backend) -- only need to apply the backend expression
      (frontend, None) -- only need to apply the frontend expression
      (frontend, backend) -- must apply both frontend and backend expressions

    Args:
      expression: The expression string to rewrite.
      defaults: resource_projection_spec.ProjectionSpec defaults.

    Returns:
      Returns (frontend_expression, backend_expression) for expression.
    """
    if defaults and defaults.symbols:
      conditionals = defaults.symbols.get(
          resource_transform.GetTypeDataName('conditionals'))
      if hasattr(conditionals, 'flatten') and conditionals.flatten:
        # If --flatten flag is presented we cannot do serverside filtering.
        return expression, None
    self.partial_rewrite = False
    defaults = resource_projection_spec.ProjectionSpec(defaults=defaults)
    defaults.symbols = _BelieveMe()
    backend_expression = resource_filter.Compile(
        expression, backend=self, defaults=defaults).Rewrite()
    frontend_expression = expression if self.partial_rewrite else None
    if frontend_expression and frontend_expression.isspace():
      frontend_expression = None
    return frontend_expression, backend_expression
Exemplo n.º 2
0
    def __init__(self, command, args, resources=None):
        """Constructor.

    Args:
      command: The Command object.
      args: The argparse.Namespace given to the command.Run().
      resources: The resources to display, returned by command.Run(). May be
        omitted if only GetFormat() will be called.
    """
        self._args = args
        self._command = command
        self._default_format_used = False
        self._format = None
        self._info = command.ResourceInfo(args)
        self._printer = None
        self._printer_is_initialized = False
        self._resources = resources
        self._defaults = resource_projection_spec.ProjectionSpec(
            defaults=command.Defaults())
        self._defaults.symbols[resource_transform.GetTypeDataName(
            'conditionals')] = args
        if self._info:
            self._defaults.symbols['collection'] = (
                lambda r, undefined='': self._info.collection or undefined)
        geturi = command.GetUriFunc()
        if geturi:
            self._transform_uri = lambda r, undefined='': geturi(r
                                                                 ) or undefined
            self._defaults.symbols['uri'] = self._transform_uri
        else:
            self._transform_uri = resource_transform.TransformUri
Exemplo n.º 3
0
    def _ParseKey(self):
        """Parses a key and optional attributes from the expression.

    The parsed key is appended to the ordered list of keys via _AddKey().
    Transform functions and key attributes are also handled here.

    Raises:
      ExpressionSyntaxError: The expression has a syntax error.
    """
        key, attribute = self._lex.KeyWithAttribute()
        if self._lex.IsCharacter('(', eoi_ok=True):
            add_transform = self._lex.Transform(key.pop(),
                                                self._projection.active)
        else:
            add_transform = None
        if (not self.__key_attributes_only
                and attribute) or (self.__key_attributes_only and attribute
                                   and not key):
            # When a key is repeated in the format expression, we want to duplicate
            # the attribute and add transfrom to the key, as the previous behaviour
            # was. However _AddKey is also processed for attribute only keys; in this
            # case, we want to reference the same attribute if the attribute is
            # referenced by its label.
            attribute = copy.copy(attribute)
        else:
            attribute = self._Attribute(self._projection.PROJECT)
        if not attribute.transform:
            attribute.transform = add_transform
        elif add_transform:
            # Compose the alias attribute.transform with add_transforms.
            attribute.transform._transforms.extend(add_transform._transforms)  # pylint: disable=protected-access
        self._lex.SkipSpace()
        if self._lex.IsCharacter(':'):
            self._ParseKeyAttributes(key, attribute)
        if attribute.transform and attribute.transform.conditional:
            # Parse and evaluate if() transform conditional expression,
            conditionals = self._projection.symbols.get(
                resource_transform.GetTypeDataName('conditionals'))

            def EvalGlobalRestriction(unused_obj, restriction, unused_pattern):
                return getattr(conditionals, restriction, None)

            defaults = resource_projection_spec.ProjectionSpec(
                symbols={
                    resource_projection_spec.GLOBAL_RESTRICTION_NAME:
                    EvalGlobalRestriction
                })
            if not resource_filter.Compile(
                    attribute.transform.conditional,
                    defaults=defaults).Evaluate(conditionals):
                return
        if attribute.label is None and not key and attribute.transform:
            attribute.label = self._AngrySnakeCase(
                [attribute.transform.name] +
                attribute.transform._transforms[0].args)  # pylint: disable=protected-access
        self._AddKey(key, attribute)
Exemplo n.º 4
0
    def Args(parser):
        state = {'RUNNING': 1, 'STOPPED': 0}
        transforms = {
            resource_transform.GetTypeDataName('state', 'enum'): state
        }
        parser.display_info.AddTransforms(transforms)

        parser.display_info.AddFormat("""
      table(
        a.enum(state, undefined="?"),
        b.enum(state, inverse=true, undefined="?")
      )
    """)
Exemplo n.º 5
0
    def __init__(self, command, args, resources=None, display_info=None):
        """Constructor.

    Args:
      command: The Command object.
      args: The argparse.Namespace given to the command.Run().
      resources: The resources to display, returned by command.Run(). May be
        omitted if only GetFormat() will be called.
      display_info: The DisplayInfo object reaped from parser.AddDisplayInfo()
        in the command path.
    """
        self._args = args
        self._cache_updater = None
        self._command = command
        self._defaults = None
        self._default_format_used = False
        self._format = None
        self._filter = None
        self._info = None
        self._legacy = True
        self._printer = None
        self._printer_is_initialized = False
        self._resources = resources
        if not display_info:
            # pylint: disable=protected-access
            display_info = args.GetDisplayInfo()
        if display_info:
            self._legacy = display_info.legacy
            self._cache_updater = display_info.cache_updater
            self._defaults = resource_projection_spec.ProjectionSpec(
                defaults=self._defaults,
                symbols=display_info.transforms,
                aliases=display_info.aliases)
            self._format = display_info.format
            self._filter = display_info.filter
        if self._legacy:
            self._defaults = resource_projection_spec.ProjectionSpec(
                defaults=command.Defaults(),
                symbols=display_info.transforms if display_info else None)
            self._info = command.ResourceInfo(args)
            if self._info:
                self._defaults.symbols['collection'] = (
                    lambda r, undefined='': self._info.collection or undefined)
            geturi = command.GetUriFunc()
            if geturi:
                self._defaults.symbols['uri'] = (
                    lambda r, undefined='': geturi(r) or undefined)
        self._transform_uri = self._defaults.symbols.get(
            'uri', resource_transform.TransformUri)
        self._defaults.symbols[resource_transform.GetTypeDataName(
            'conditionals')] = args
    def _ParseKey(self):
        """Parses a key and optional attributes from the expression.

    Transform functions and key attributes are also handled here.

    Raises:
      ExpressionSyntaxError: The expression has a syntax error.

    Returns:
      The parsed key.
    """
        key = self._lex.Key()
        attribute = self._Attribute(self._projection.PROJECT)
        if self._lex.IsCharacter('(', eoi_ok=True):
            func_name = key.pop()
            attribute.transform = self._lex.Transform(func_name,
                                                      self._projection.active)
            func_name = attribute.transform.name
        else:
            func_name = None
        self._lex.SkipSpace()
        if self._lex.IsCharacter(':'):
            self._ParseKeyAttributes(key, attribute)
        if attribute.transform and attribute.transform.conditional:
            # Parse and evaluate if() transform conditional expression,
            conditionals = self._projection.symbols.get(
                resource_transform.GetTypeDataName('conditionals'))

            def EvalGlobalRestriction(unused_obj, restriction, unused_pattern):
                return getattr(conditionals, restriction, None)

            defaults = resource_projection_spec.ProjectionSpec(
                symbols={
                    resource_projection_spec.GLOBAL_RESTRICTION_NAME:
                    EvalGlobalRestriction
                })
            if not resource_filter.Compile(
                    attribute.transform.conditional,
                    defaults=defaults).Evaluate(conditionals):
                return
        if func_name and attribute.label is None and not key:
            attribute.label = self._AngrySnakeCase([func_name])
        self._AddKey(key, attribute)
Exemplo n.º 7
0
def AddReadyColumnTransform(parser):
  """Adds the transformation to correctly display the 'Ready'column.

  The transformation converts the status values of True/False/Unknown into
  corresponding symbols.

  Args:
    parser: parser object to add the transformation to.
  """
  status = {
      kubernetes_consts.VAL_TRUE:
          GetReadySymbol(kubernetes_consts.VAL_TRUE),
      kubernetes_consts.VAL_FALSE:
          GetReadySymbol(kubernetes_consts.VAL_FALSE),
      kubernetes_consts.VAL_UNKNOWN:
          GetReadySymbol(kubernetes_consts.VAL_UNKNOWN)
  }
  transforms = {resource_transform.GetTypeDataName('status', 'enum'): status}
  parser.display_info.AddTransforms(transforms)