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
Exemple #2
0
    def Run(self, args):
        client = base_classes.ComputeApiHolder(
            self.ReleaseTrack()).client.apitools_client

        compute_interconnect_attachments = client.interconnectAttachments

        messages = client.MESSAGES_MODULE
        project = properties.VALUES.core.project.GetOrFail()
        display_info = args.GetDisplayInfo()
        defaults = resource_projection_spec.ProjectionSpec(
            symbols=display_info.transforms, aliases=display_info.aliases)
        args.filter, filter_expr = filter_rewrite.Rewriter().Rewrite(
            args.filter, defaults=defaults)

        request = messages.ComputeInterconnectAttachmentsAggregatedListRequest(
            project=project, filter=filter_expr)

        # TODO(b/34871930): Write and use helper for handling listing.
        interconnect_attachments_lists, next_page_token = self._GetListPage(
            compute_interconnect_attachments, request)
        while next_page_token:
            request.pageToken = next_page_token
            interconnect_attachments_list_page, next_page_token = self._GetListPage(
                compute_interconnect_attachments, request)
            interconnect_attachments_lists += interconnect_attachments_list_page

        return interconnect_attachments_lists
  def Run(self, args):
    client = privateca_base.GetClientInstance(api_version='v1')
    messages = privateca_base.GetMessagesModule(api_version='v1')

    display_info = args.GetDisplayInfo()
    defaults = resource_projection_spec.ProjectionSpec(
        symbols=display_info.transforms, aliases=display_info.aliases)
    client_filter, server_filter = filter_rewrite.BackendFilterRewrite(
    ).Rewrite(
        args.filter, defaults=defaults)
    log.info('original_filter=%r, client_filter=%r, server_filter=%r',
             args.filter, client_filter, server_filter)
    # Overwrite client filter used by gcloud.
    args.filter = client_filter
    parent = args.CONCEPTS.issuer_pool.Parse()
    request = messages.PrivatecaProjectsLocationsCaPoolsCertificatesListRequest(
        parent=parent.RelativeName(),
        orderBy=common_args.ParseSortByArg(args.sort_by),
        filter=server_filter)

    return list_pager.YieldFromList(
        client.projects_locations_caPools_certificates,
        request,
        field='certificates',
        limit=args.limit,
        batch_size_attribute='pageSize',
        batch_size=args.page_size,
        get_field_func=response_utils.GetFieldAndLogUnreachable)
Exemple #4
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
  def __init__(self, *args, **kwargs):
    """Creates a new TablePrinter."""
    self._rows = []
    super(TablePrinter, self).__init__(*args, by_columns=True,
                                       non_empty_projection_required=True,
                                       **kwargs)
    encoding = None
    for name in ['ascii', 'utf8', 'win']:
      if name in self.attributes:
        encoding = name
        break
    if not self._console_attr:
      self._console_attr = console_attr.GetConsoleAttr(encoding=encoding,
                                                       out=self._out)
    self._page_count = 0

    # Check for subformat columns.
    self._optional = False
    self._subformats = []
    self._has_subprinters = False
    has_subformats = False
    self._aggregate = True
    if self.column_attributes:
      for col in self.column_attributes.Columns():
        if col.attribute.subformat or col.attribute.hidden:
          has_subformats = True
        else:
          self._aggregate = False
        if col.attribute.optional:
          self._optional = True
        if col.attribute.wrap:
          self._wrap = True
      defaults = resource_projection_spec.ProjectionSpec(
          symbols=self.column_attributes.symbols)
      index = 0
      for col in self.column_attributes.Columns():
        if col.attribute.subformat:
          # This initializes a nested Printer to a string stream.
          out = self._out if self._aggregate else StringIO.StringIO()
          wrap = None
          printer = self.Printer(col.attribute.subformat, out=out,
                                 console_attr=self._console_attr,
                                 defaults=defaults)
          self._has_subprinters = True
        else:
          out = None
          printer = None
          wrap = col.attribute.wrap
        self._subformats.append(
            SubFormat(index, col.attribute.hidden, printer, out, wrap))
        index += 1
    self._visible = None
    if not has_subformats:
      self._subformats = None
      self._aggregate = False
    elif self._subformats and not self._aggregate:
      self._visible = []
      for subformat in self._subformats:
        if not subformat.hidden and not subformat.printer:
          self._visible.append(subformat.index)
  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
Exemple #7
0
 def __init__(self, backend=None, defaults=None):
     self._backend = backend or resource_expr.Backend()
     self._defaults = defaults or resource_projection_spec.ProjectionSpec()
     self._operator_char_1 = ''
     self._operator_char_2 = ''
     self._operator = {
         ':': self._backend.ExprHAS,
         '=': self._backend.ExprEQ,
         '!=': self._backend.ExprNE,
         '<': self._backend.ExprLT,
         '<=': self._backend.ExprLE,
         '>=': self._backend.ExprGE,
         '>': self._backend.ExprGT,
         '~': self._backend.ExprRE,
         '!~': self._backend.ExprNotRE
     }
     # Operator names are length 1 or 2. This loop precomputes _operator_char_1
     # and _operator_char_2 for _ParseOperator to determine both valid and
     # invalid operator names.
     for operator in self._operator:
         c = operator[0]
         if c not in self._operator_char_1:
             self._operator_char_1 += c
         if len(operator) < 2:
             continue
         c = operator[1]
         if c not in self._operator_char_2:
             self._operator_char_2 += c
     self._lex = None
     self._parenthesize = [set()]
    def Run(self, args):
        client = base_classes.ComputeApiHolder(
            self.ReleaseTrack()).client.apitools_client

        network_edge_security_services = client.networkEdgeSecurityServices

        messages = client.MESSAGES_MODULE
        project = properties.VALUES.core.project.GetOrFail()

        display_info = args.GetDisplayInfo()
        defaults = resource_projection_spec.ProjectionSpec(
            symbols=display_info.transforms, aliases=display_info.aliases)
        args.filter, filter_expr = filter_rewrite.Rewriter().Rewrite(
            args.filter, defaults=defaults)

        request = messages.ComputeNetworkEdgeSecurityServicesAggregatedListRequest(
            project=project, filter=filter_expr)

        # TODO(b/34871930): Write and use helper for handling listing.
        resource_lists, next_page_token = (self._GetListPage(
            network_edge_security_services, request))
        while next_page_token:
            request.pageToken = next_page_token
            resource_list_page, next_page_token = (self._GetListPage(
                network_edge_security_services, request))
            resource_lists += resource_list_page

        return resource_lists
  def Run(self, args):
    holder = base_classes.ComputeApiHolder(self.ReleaseTrack())

    client = holder.client.apitools_client
    messages = client.MESSAGES_MODULE

    project = properties.VALUES.core.project.GetOrFail()
    display_info = args.GetDisplayInfo()
    defaults = resource_projection_spec.ProjectionSpec(
        symbols=display_info.transforms, aliases=display_info.aliases)
    args.filter, filter_expr = filter_rewrite.Rewriter().Rewrite(
        args.filter, defaults=defaults)
    request = messages.ComputeNetworksListRequest(
        project=project, filter=filter_expr)

    for network in list_pager.YieldFromList(
        client.networks,
        request,
        field='items',
        limit=args.limit,
        batch_size=None):
      if network.peerings and (args.network is None or
                               args.network == network.name):
        # Network is synthesized for legacy reasons to maintain prior format.
        # In general, synthesized output should not be done.
        synthesized_network = resource_projector.MakeSerializable(network)
        for peering in synthesized_network['peerings']:
          peering['source_network'] = network.selfLink
        yield synthesized_network
Exemple #10
0
def RewriteFilter(args, message=None, frontend_fields=None):
    """Rewrites args.filter into client and server filter expression strings.

  Usage:

    args.filter, request_filter = flags.RewriteFilter(args)

  Args:
    args: The parsed args namespace containing the filter expression args.filter
      and display_info.
    message: The response resource message proto for the request.
    frontend_fields: A set of dotted key names supported client side only.

  Returns:
    A (client_filter, server_filter) tuple of filter expression strings.
    None means the filter does not need to applied on the respective
    client/server side.
  """
    if not args.filter:
        return None, None
    display_info = args.GetDisplayInfo()
    defaults = resource_projection_spec.ProjectionSpec(
        symbols=display_info.transforms, aliases=display_info.aliases)
    client_filter, server_filter = filter_rewrite.Rewriter(
        message=message,
        frontend_fields=frontend_fields).Rewrite(args.filter,
                                                 defaults=defaults)
    log.info('client_filter=%r server_filter=%r', client_filter, server_filter)
    return client_filter, server_filter
Exemple #11
0
 def Defaults(self):
     importances = {
         'JOB_MESSAGE_DETAILED': 'd',
         'JOB_MESSAGE_DEBUG': 'D',
         'JOB_MESSAGE_WARNING': 'W',
         'JOB_MESSAGE_ERROR': 'E',
     }
     symbols = {'dataflow.JobMessage::enum': importances}
     return resource_projection_spec.ProjectionSpec(symbols=symbols)
Exemple #12
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)
Exemple #13
0
  def __init__(self, expression, defaults=None):
    """Initializes a resource lexer.

    Args:
      expression: The expression string.
      defaults: ProjectionSpec object for aliases and symbols defaults.
    """
    self._expr = expression or ''
    self._position = 0
    self._defaults = defaults or resource_projection_spec.ProjectionSpec()
Exemple #14
0
 def _GetResourceInfoDefaults(self):
     """Returns the default symbols for --filter and --format."""
     if not self._info:
         return self._defaults
     symbols = self._info.GetTransforms()
     if not symbols and not self._info.defaults:
         return self._defaults
     return resource_projection_spec.ProjectionSpec(
         defaults=resource_projection_spec.CombineDefaults(
             [self._info.defaults, self._defaults]),
         symbols=symbols)
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        helper = vpn_tunnels_utils.VpnTunnelHelper(holder)

        project = properties.VALUES.core.project.GetOrFail()
        display_info = args.GetDisplayInfo()
        defaults = resource_projection_spec.ProjectionSpec(
            symbols=display_info.transforms, aliases=display_info.aliases)
        args.filter, filter_expr = filter_rewrite.Rewriter().Rewrite(
            args.filter, defaults=defaults)
        return helper.List(project=project, filter_expr=filter_expr)
 def RunSubTest(self, fun, expression, aliases=None, annotate=None, **kwargs):
   if aliases:
     defaults = resource_projection_spec.ProjectionSpec(None, aliases=aliases)
   else:
     defaults = None
   lex = resource_lex.Lexer(expression, defaults=defaults)
   try:
     actual = getattr(lex, fun)(**kwargs)
   finally:
     if annotate is not None:
       self.AddFollowOnTest('annotate', annotate, lex.Annotate)
   return actual
  def Run(self, args):
    secret_ref = args.CONCEPTS.secret.Parse()
    server_filter = None
    if args.filter:
      rewriter = resource_expr_rewrite.Backend()
      display_info = args.GetDisplayInfo()
      defaults = resource_projection_spec.ProjectionSpec(
          symbols=display_info.transforms, aliases=display_info.aliases)
      _, server_filter = rewriter.Rewrite(args.filter, defaults=defaults)

    return secrets_api.Versions().ListWithPager(
        secret_ref=secret_ref, limit=args.limit, request_filter=server_filter)
Exemple #18
0
    def __init__(self, defaults=None, symbols=None):
        """Constructor.

    Args:
      defaults: resource_projection_spec.ProjectionSpec defaults.
      symbols: Transform function symbol table dict indexed by function name.
    """
        self.__key_attributes_only = False
        self._ordinal = 0
        self._projection = resource_projection_spec.ProjectionSpec(
            defaults=defaults, symbols=symbols)
        self._snake_headings = {}
        self._snake_re = None
 def Run(self, args):
     """Run the list command."""
     display_info = args.GetDisplayInfo()
     defaults = resource_projection_spec.ProjectionSpec(
         symbols=display_info.transforms, aliases=display_info.aliases)
     args.filter, server_filter = filter_rewrite.ListRewriter().Rewrite(
         args.filter, defaults=defaults)
     log.info('client_filter="%s" server_filter="%s"', args.filter,
              server_filter)
     server_limit = args.limit
     if args.filter:
         # We must use client-side limiting if we are using client-side filtering.
         server_limit = None
     return projects_api.List(limit=server_limit, filter=server_filter)
Exemple #20
0
  def __init__(self, defaults=None, symbols=None, aliases=None, compiler=None):
    """Constructor.

    Args:
      defaults: resource_projection_spec.ProjectionSpec defaults.
      symbols: Transform function symbol table dict indexed by function name.
      aliases: Resource key alias dictionary.
      compiler: The projection compiler method for nested projections.
    """
    self.__key_attributes_only = False
    self._projection = resource_projection_spec.ProjectionSpec(
        defaults=defaults, symbols=symbols, aliases=aliases, compiler=compiler)
    self._snake_headings = {}
    self._snake_re = None
Exemple #21
0
    def _ConvertFilter(self, expression, args):
        """Translates user-provided filter spec into one our backend understands.

    Args:
      expression: a filter spec to translate
      args: the args namespace object
    Returns:
      A tuple of string filter specs. The first is the frontend spec for post
      filtering, the second is a spec that the Datastore Admin API understands.
    """
        operation_rewrite_backend = rewrite_backend.OperationsRewriteBackend()
        display_info = args.GetDisplayInfo()
        defaults = resource_projection_spec.ProjectionSpec(
            symbols=display_info.transforms, aliases=display_info.aliases)
        return operation_rewrite_backend.Rewrite(expression, defaults=defaults)
Exemple #22
0
  def Run(self, args):
    project_ref = args.CONCEPTS.project.Parse()
    if not project_ref:
      raise exceptions.RequiredArgumentException(
          'project',
          'Please set a project with "--project" flag or "gcloud config set project <project_id>".'
      )
    server_filter = None
    if args.filter:
      rewriter = resource_expr_rewrite.Backend()
      display_info = args.GetDisplayInfo()
      defaults = resource_projection_spec.ProjectionSpec(
          symbols=display_info.transforms, aliases=display_info.aliases)
      _, server_filter = rewriter.Rewrite(args.filter, defaults=defaults)

    return secrets_api.Secrets().ListWithPager(
        project_ref=project_ref, limit=args.limit, request_filter=server_filter)
  def RunSubTest(self, expression, deprecated=False):

    def _Error(resource=None):
      """Always raises ValueError for testing.

      Args:
        resource: The resource object.

      Raises:
        ValueError: Always for testing.
      """
      _ = resource
      raise ValueError('Transform function value error.')

    default_symbols = {
        'date': resource_transform.TransformDate,
        'len': lambda r, x=None: resource_transform.TransformLen(x or r),
    }
    defaults = resource_projection_parser.Parse(
        '(compound.string:alias=s, floating:alias=f)',
        symbols=default_symbols,
        aliases=self._ALIASES)
    symbols = {
        'error': _Error,  # 'error' not a magic name.
    }
    defaults = resource_projection_spec.ProjectionSpec(
        defaults=defaults, symbols=symbols)
    evaluate = resource_filter.Compile(expression, defaults=defaults).Evaluate
    if isinstance(self.resource, list):
      results = []
      for r in self.resource:
        results.append(evaluate(r))
      return results
    actual = evaluate(self.resource)
    err = self.GetErr()
    self.ClearErr()
    warning = ('WARNING: --filter : operator evaluation is changing for '
               'consistency across Google APIs.')
    if err and not deprecated:
      self.fail('Error [%s] not expected.' % err)
    elif not err and deprecated:
      self.fail('Warning [%s] expected.' % warning)
    elif err and deprecated and warning not in err:
      self.fail('Warning [%s] expected but got [%s].' % (warning, err))
    return actual
    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)
Exemple #25
0
def RewriteFilter(args):
    """Rewrites args.filter into client and server filter expression strings.

  Usage:

    args.filter, request_filter = flags.RewriteFilter(args)

  Args:
    args: The parsed args namespace containing the filter expression args.filter
      and display_info.

  Returns:
    A (client_expression, server_expression) tuple of expression strings. None
    means the expression does not need to applied on the respective
    client/server side.
  """
    display_info = args.GetDisplayInfo()
    defaults = resource_projection_spec.ProjectionSpec(
        symbols=display_info.transforms, aliases=display_info.aliases)
    return filter_rewrite.Rewriter().Rewrite(args.filter, defaults=defaults)
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())

        client = holder.client.apitools_client
        messages = client.MESSAGES_MODULE

        project = properties.VALUES.core.project.Get(required=True)

        display_info = args.GetDisplayInfo()
        defaults = resource_projection_spec.ProjectionSpec(
            symbols=display_info.transforms, aliases=display_info.aliases)
        args.filter, filter_expr = filter_rewrite.Rewriter().Rewrite(
            args.filter, defaults=defaults)
        request = messages.ComputeSecurityPoliciesListRequest(
            project=project, filter=filter_expr)

        return list_pager.YieldFromList(client.securityPolicies,
                                        request,
                                        field='items',
                                        limit=args.limit,
                                        batch_size=None)
Exemple #27
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
    def Run(self, args):
        """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Some value that we want to have printed later.
    """
        build_region = args.region or cloudbuild_util.DEFAULT_REGION

        client = cloudbuild_util.GetClientInstance()
        messages = cloudbuild_util.GetMessagesModule()

        project_id = properties.VALUES.core.project.GetOrFail()
        parent_resource = resources.REGISTRY.Create(
            collection='cloudbuild.projects.locations',
            projectsId=project_id,
            locationsId=build_region)

        display_info = args.GetDisplayInfo()
        defaults = resource_projection_spec.ProjectionSpec(
            symbols=display_info.transforms, aliases=display_info.aliases)
        args.filter, server_filter = filter_rewrite.Backend(
            args.ongoing).Rewrite(args.filter, defaults=defaults)

        return list_pager.YieldFromList(
            client.projects_locations_builds,
            messages.CloudbuildProjectsLocationsBuildsListRequest(
                parent=parent_resource.RelativeName(),
                pageSize=args.page_size,
                filter=server_filter),
            field='builds',
            batch_size=args.page_size,
            limit=args.limit,
            batch_size_attribute='pageSize')
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client.apitools_client

        project = properties.VALUES.core.project.Get(required=True)

        display_info = args.GetDisplayInfo()
        defaults = resource_projection_spec.ProjectionSpec(
            symbols=display_info.transforms, aliases=display_info.aliases)
        args.filter, filter_expr = filter_rewrite.Rewriter().Rewrite(
            args.filter, defaults=defaults)

        if not self._enable_region_target_tcp_proxy:
            return self._ListGlobal(client, project, args, filter_expr)

        # TODO(b/229835962): switch to lister.MultiScopeLister
        #   until then emulate AggregatedList behaviour similar to
        #   third_party/py/googlecloudsdk/surface/compute/\
        #     network_firewall_policies/list.py
        global_items = []
        regional_items = []

        if args.regions:
            regional_items = (self._ListRegional(client, project, args,
                                                 filter_expr, args.regions))
        elif getattr(args, 'global', None):
            global_items = self._ListGlobal(client, project, args, filter_expr)
        else:
            global_items = self._ListGlobal(client, project, args, filter_expr)
            all_regions = self._GetRegions(client, project)
            regional_items = (self._ListRegional(client, project, args,
                                                 filter_expr, all_regions))

        all_items = itertools.chain(global_items, regional_items)
        if args.limit:
            all_items = itertools.islice(all_items, args.limit)
        return all_items
Exemple #30
0
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client
        messages = client.messages

        neg_ref = flags.MakeNetworkEndpointGroupsArg(
            support_global_scope=self.support_global_scope).ResolveAsResource(
                args,
                holder.resources,
                scope_lister=compute_flags.GetDefaultScopeLister(client))

        display_info = args.GetDisplayInfo()
        defaults = resource_projection_spec.ProjectionSpec(
            symbols=display_info.transforms, aliases=display_info.aliases)
        args.filter, filter_expr = filter_rewrite.Rewriter().Rewrite(
            args.filter, defaults=defaults)

        if hasattr(neg_ref, 'zone'):
            request = messages.ComputeNetworkEndpointGroupsListNetworkEndpointsRequest(
                networkEndpointGroup=neg_ref.Name(),
                project=neg_ref.project,
                zone=neg_ref.zone,
                filter=filter_expr)
            service = client.apitools_client.networkEndpointGroups
        else:
            request = messages.ComputeGlobalNetworkEndpointGroupsListNetworkEndpointsRequest(
                networkEndpointGroup=neg_ref.Name(),
                project=neg_ref.project,
                filter=filter_expr)
            service = client.apitools_client.globalNetworkEndpointGroups

        return list_pager.YieldFromList(service,
                                        request,
                                        method='ListNetworkEndpoints',
                                        field='items',
                                        limit=args.limit,
                                        batch_size=None)