示例#1
0
class Formats(base.Command):
  """Resource formats supplementary help."""

  def Run(self, args):
    self.cli.Execute(args.command_path[1:] + ['--document=style=topic'])
    return None

  detailed_help = {

      'DESCRIPTION': textwrap.dedent("""\
          {description}

          ### Formats

          A format expression has 3 parts:

          _NAME_:: _name_
          _ATTRIBUTES_:: *[* [no-]_attribute-name_[=_value_] [, ... ] *]*
          _PROJECTION_:: *(* _resource-key_ [, ...] *)*

          _NAME_ is required, _ATTRIBUTES_ are optional, and _PROJECTIONS_
          may be required for some formats. Unknown attribute names are
          silently ignored.

          Each *gcloud* *list* command has a default format expression. The
          *--format* flag can alter or replace the default. For example,

              --format='[box]'

          adds box decorations to a default table, and

              --format=json

          lists the resource in *json* format.

          {format_registry}
          """).format(
              description=resource_topics.ResourceDescription('format'),
              format_registry=resource_topics.FormatRegistryDescriptions()),

      'EXAMPLES': """\
          List a table of compute instance resources sorted by *name* with
          box decorations and title *Instances*:

            $ gcloud compute instances list --format='table[box,title=Instances](name:sort=1, zone:title=zone, status)'

          List the disk interfaces for all compute instances as a compact
          comma separated list:

            $ gcloud compute instances list --format='value(disks[].interface.list())'

          List the URIs for all compute instances:

            $ gcloud compute instances list --format='value(uri())'

          List the project authenticated user email address:

            $ gcloud info --format='value(config.account)'
          """,
      }
    def testResourceDescriptionProjection(self):
        expected = """\
Most *gcloud* commands return a list of resources on success. By default they
are pretty-printed on the standard output. The
*--format=*_NAME_[_ATTRIBUTES_]*(*_PROJECTION_*)* and
*--filter=*_EXPRESSION_ flags along with projections can be used to format and
change the default output to a more meaningful result.

Use the `--format` flag to change the default output format of a command.   For details run $ gcloud topic formats.

Use the `--filter` flag to select resources to be listed. For details run $ gcloud topic filters.

Use resource-keys to reach resource items through a unique path of names from the root. For details run $ gcloud topic resource-keys.

Use projections to list a subset of resource keys in a resource.   Resource projections are described in detail below.

Note: To refer to a list of fields you can sort, filter, and format by for
each resource, you can run a list command with the format set to `text` or
`json`. For
example, $ gcloud compute instances list --limit=1 --format=text.

To work through an interactive tutorial about using the filter and format
flags instead, see: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/cloud-shell-tutorials&page=editor&tutorial=cloudsdk/tutorial.md
"""
        actual = resource_topics.ResourceDescription('projection')
        self.assertEqual(expected, actual)
class Projections(base.TopicCommand):
    """Resource projections supplementary help.

  {projection_description}

  ### Projections

  A projection is a list of keys that selects resource data values.
  Projections are used in *--format* flag expressions. For example, the
  *table* format requires a projection that describes the table columns:

    table(name, network.ip.internal, network.ip.external, uri())

  ### Transforms

  A *transform* formats resource data values. Each projection key may
  have zero or more transform calls:

    _key_._transform_([arg...])...

  This example applies the *foo*() and then the *bar*() transform to the
  *status.time* resource value:

    (name, status.time.foo().bar())

  {transform_registry}

  ### Key Attributes

  Key attributes control formatted output. Each projection key may have
  zero or more attributes:

    _key_:_attribute_=_value_...

  where =_value_ is omitted for Boolean attributes and no-_attribute_
  sets the attribute to false. Attribute values may appear in any order,
  but must be specified after any transform calls. The attributes are:

  *alias*=_ALIAS-NAME_::
  Sets _ALIAS-NAME_ as an alias for the projection key.

  *align*=_ALIGNMENT_::
  Specifies the output column data alignment. Used by the *table*
  format. The alignment values are:

  *left*:::
  Left (default).

  *center*:::
  Center.

  *right*:::
  Right.

  *label*=_LABEL_::
  A string value used to label output. Use :label="" or :label=''
  for no label. The *table* format uses _LABEL_ values as column
  headings. Also sets _LABEL_ as an alias for the projection key.
  The default label is the disambiguated right hand parts of the
  column key name in ANGRY_SNAKE_CASE.

  [no-]*reverse*::
  Sets the key sort order to descending. *no-reverse* resets to the
  default ascending order.

  *sort*=_SORT-ORDER_::
  An integer counting from 1. Keys with lower sort-order are sorted
  first. Keys with same sort order are sorted left to right. Columns are
  sorted based on displayed value alone, irrespective of the type of
  value(date, time, etc.).

  *wrap*[=_MIN-WIDTH_]::
  Enables the column text to be wrapped if the table would otherwise
  be too wide for the display. The column will be wrapped in the available space
  with a minimum width of either the default or of _MIN-WIDTH_ if specified. The
  default is 10 characters.

  ## EXAMPLES

  List a table of instance *zone* (sorted in descending order) and
  *name* (sorted by *name* and centered with column heading *INSTANCE*)
  and *creationTimestamp* (listed using the *strftime*(3) year-month-day
  format with column heading *START*):

    $ gcloud compute instances list --format="table(name:sort=2:align=center:label=INSTANCE, zone:sort=1:reverse, creationTimestamp.date("%Y-%m-%d"):label=START)"

  List only the *name*, *status* and *zone* instance resource keys in
  YAML format:

    $ gcloud compute instances list --format="yaml(name, status, zone)"

  List only the *config.account* key value(s) in the *info* resource:

    $ gcloud info --format="value(config.account)"

  List the *name*, *id*, and *description* of an imaginary *foo* resource,
  wrapping the *id* column with the default minimum width and the *description*
  column with a minimum width of 20 characters:

    $ gcloud example foo list --format="table(name, id:wrap, description:wrap=20)"
  """

    detailed_help = {
        'projection_description':
        lambda: resource_topics.ResourceDescription('projection'),
        'transform_registry':
        resource_topics.TransformRegistryDescriptions,
    }
示例#4
0
class Filters(base.TopicCommand):
  """Resource filters supplementary help."""

  detailed_help = {
      'DESCRIPTION':
          textwrap.dedent("""\
          {description}

          === Filter Expressions ===

          A filter expression is a Boolean function that selects the resources
          to print from a list of resources. Expressions are composed
          of terms connected by logic operators.

          *LogicOperator*::

          Expressions containing both *AND* and *OR* must be parenthesized to
          disambiguate precedence.

          *NOT* _term-1_:::

          True if _term-1_ is False, otherwise False.

          _term-1_ *AND* _term-2_:::

          True if both _term-1_ and _term-2_ are true.

          _term-1_ *OR* _term-2_:::

          True if at least one of _term-1_ or _term-2_ is true.

          _term-1_ _term-2_:::

          Term conjunction (implicit *AND*) is True if both _term-1_
          and _term-2_ are true.  Conjunction has lower precedence than *OR*.

          *Terms*::

          A term is a _key_ _operator_ _value_ tuple, where _key_ is a dotted
          name that evaluates to the value of a resource attribute, and _value_
          may be:

          *number*::: integer or floating point numeric constant

          *unquoted literal*::: character sequence terminated by space, ( or )

          *quoted literal*::: _"..."_ or _'...'_

          Most filter expressions need to be quoted in shell commands. If you
          use _'...'_ shell quotes then use _"..."_ filter string literal quotes
          and vice versa.

          *Operator Terms*::

          _key_ *:* _simple-pattern_:::

          *:* operator evaluation is changing for consistency across Google
          APIs.  The current default is deprecated and will be dropped shortly.
          A warning will be displayed when a --filter expression would return
          different matches using both the deprecated and new implementations.
          +
          The current deprecated default is True if _key_ contains
          _simple-pattern_.  The match is case insensitive.  It allows one
          ```*``` that matches any sequence of 0 or more characters.
          If ```*``` is specified then the match is anchored, meaning all
          characters from the beginning and end of the value must match.
          +
          The new implementation is True if _simple-pattern_ matches any
          _word_ in _key_.  Words are locale specific but typically consist of
          alpha-numeric characters.  Non-word characters that do not appear in
          _simple-pattern_ are ignored.  The matching is anchored and case
          insensitive.  An optional trailing ```*``` does a word prefix match.
          +
          Use _key_```:*``` to test if _key_ is defined and
          ```-```_key_```:*``` to test if _key_ is undefined.

          _key_ *:(* _simple-pattern_ ... *)*:::

          True if _key_ matches any _simple-pattern_ in the
          (space, tab, newline, comma) separated list.

          _key_ *=* _value_:::

          True if _key_ is equal to _value_.  Equivalent to *:*, with the
          exception that the trailing ```*``` prefix match is not supported.

          _key_ *=(* _value_ ... *)*:::

          True if _key_ is equal to any _value_ in the
          (space, tab, newline, *,*) separated list.

          _key_ *!=* _value_:::

          True if _key_ is not _value_. Equivalent to
          -_key_=_value_ and NOT _key_=_value_.

          _key_ *<* _value_:::

          True if _key_ is less than _value_. If both _key_ and
          _value_ are numeric then numeric comparison is used, otherwise
          lexicographic string comparison is used.

          _key_ *<=* _value_:::

          True if _key_ is less than or equal to _value_. If both
          _key_ and _value_ are numeric then numeric comparison is used,
          otherwise lexicographic string comparison is used.

          _key_ *>=* _value_:::

          True if _key_ is greater than or equal to _value_. If
          both _key_ and _value_ are numeric then numeric comparison is used,
          otherwise lexicographic string comparison is used.

          _key_ *>* _value_:::

          True if _key_ is greater than _value_. If both _key_ and
          _value_ are numeric then numeric comparison is used, otherwise
          lexicographic string comparison is used.

          _key_ *~* _value_:::

          True if _key_ matches the RE (regular expression) pattern _value_.

          _key_ *!*~ _value_:::

          True if _key_ does not match the RE (regular expression)
          pattern _value_.

          """)
          .format(description=resource_topics.ResourceDescription('filter')),
      'EXAMPLES':
          textwrap.dedent("""\
          List all Google Compute Engine instance resources:

            $ gcloud compute instances list

          List Compute Engine instance resources that have machineType
          *f1-micro*:

            $ gcloud compute instances list --filter="machineType:f1-micro"

          List Compute Engine instance resources with zone prefix *us* and not
          MachineType *f1-micro*:

            $ gcloud compute instances list --filter="zone ~ ^us AND -machineType:f1-micro"

          List Compute Engine instance resources with tag *my-tag*:

            $ gcloud compute instances list --filter="tags.items=my-tag"

          List Compute Engine instance resources with tag *my-tag* or
          *my-other-tag*:

            $ gcloud compute instances list --filter="tags.items=(my-tag,my-other-tag)"

          List Compute Engine instance resources with tag *my-tag* and
          *my-other-tag*:

            $ gcloud compute instances list --filter="tags.items=my-tag AND tags.items=my-other-tag"

          List Compute Engine instance resources which either have tag *my-tag*
          but not *my-other-tag* or have tag *alternative-tag*:

            $ gcloud compute instances list --filter="(tags.items=my-tag AND -tags.items=my-other-tag) OR tags.items=alternative-tag"

          List Compute Engine instance resources with label *my-label* with any
          value:

            $ gcloud compute instances list --filter="labels.my-label:*"

          List in JSON format those projects where the labels match specific
          values (e.g. label.env is 'test' and label.version is alpha):

            $ gcloud projects list --format="json" --filter="labels.env=test AND labels.version=alpha"

          List projects that were created on and after a specific date:

            $ gcloud projects list --format="table(projectNumber,projectId,createTime)" --filter="createTime>=2018-01-15"

          List projects that were created on and after a specific date and time
          and sort from oldest to newest (with dates and times listed according
          to the local timezone):

            $ gcloud projects list --format="table(projectNumber,projectId,createTime.date(tz=LOCAL))" --filter="createTime>=2018-01-15T12:00:00" --sort-by=createTime

          List projects that were created within the last two weeks, using
          ISO8601 durations:

            $ gcloud projects list --format="table(projectNumber,projectId,createTime)" --filter="createTime>-P2W"

          For more about ISO8601 durations, see:
          https://en.wikipedia.org/wiki/ISO_8601


          This table shows : operator pattern matching:

          [format="csv",options="header"]
          |========
          PATTERN,VALUE,MATCHES,DEPRECATED_MATCHES
          abc```*```,abcpdqxyz,True,True
          abc,abcpdqxyz,False,True
          pdq```*```,abcpdqxyz,False,False
          pdq,abcpdqxyz,False,True
          xyz```*```,abcpdqxyz,False,False
          xyz,abcpdqxyz,False,True
          ```*```,abcpdqxyz,True,True
          ```*```,<None>,False,False
          ```*```,<''>,False,False
          ```*```,<otherwise>,True,True
          abc```*```,abc.pdq.xyz,True,True
          abc,abc.pdq.xyz,True,True
          abc.pdq,abc.pdq.xyz,True,True
          pdq```*```,abc.pdq.xyz,True,False
          pdq,abc.pdq.xyz,True,True
          pdq.xyz,abc.pdq.xyz,True,True
          xyz```*```,abc.pdq.xyz,True,False
          xyz,abc.pdq.xyz,True,True
          |========
          """),
  }
示例#5
0
class Formats(base.TopicCommand):
    """Resource formats supplementary help."""

    detailed_help = {
        'DESCRIPTION':
        textwrap.dedent("""\
          {description}

          ### Formats

          A format expression is used to change the default output format of a
          command.
          Many output formats are available; some for pretty printing
          human-readable output and others for returning machine-readable
          output.

          A format expression has 3 parts:

          _NAME_:: _name_
          _ATTRIBUTES_:: *[* [no-]_attribute-name_[=_value_] [, ... ] *]*
          _PROJECTION_:: *(* _resource-key_ [, ...] *)*

          _NAME_ is required, _ATTRIBUTES_ are optional, and _PROJECTIONS_
          may be required for some formats. Unknown attribute names are
          silently ignored.

          Each *gcloud* *list* command has a default format expression. The
          *--format* flag can alter or replace the default. For example,

              --format='[box]'

          adds box decorations to a default table, and

              --format=json

          lists the resource in *json* format.

          {format_registry}
          """).format(
            description=resource_topics.ResourceDescription('format'),
            format_registry=resource_topics.FormatRegistryDescriptions()),
        'EXAMPLES':
        """\
          List a table of compute instance resources sorted by *name* with
          box decorations and title *Instances*:

            $ gcloud compute instances list --format='table[box,title=Instances](name:sort=1, zone:label=zone, status)'

          List a nested table of the quotas of a region:

            $ gcloud compute regions describe us-central1 --format="table(quotas:format='table(metric,limit,usage)')"

          Print a flattened list of global quotas in CSV format:

            $ gcloud compute project-info describe --flatten='quotas[]' --format='csv(quotas.metric,quotas.limit,quotas.usage)'

          List the disk interfaces for all compute instances as a compact
          comma separated list:

            $ gcloud compute instances list --format='value(disks[].interface.list())'

          List the URIs for all compute instances:

            $ gcloud compute instances list --format='value(uri())'

          List the project authenticated user email address:

            $ gcloud info --format='value(config.account)'

          List resources filtered on repeated fields by projecting subfields on
          a repeated message:

            $ gcloud alpha genomics readgroupsets list --format 'default(readGroups[].name)'

          Return the scope of the current instance:

            $ gcloud compute zones list --format="value(selfLink.scope())"

          selfLink is a fully qualified name. (e.g. 'https://www.googleapis.com/compute/v1/projects/my-project/zones/us-central1-a')
          The previous example returns a list of just the names of each zone
          (e.g. 'us-central1-a'). This is because selfLink.scope() grabs the
          last part of the URL segment. To extract selfLink starting from
          /projects and return the scope of the current instance:

            $ gcloud compute zones list --format="value(selfLink.scope(projects))"

          List all scopes enabled for a Compute Engine instance and flatten the
          multi-valued resource:

            $ gcloud compute instances list --format="flattened(name,serviceAccounts[].email,serviceAccounts[].scopes[].basename())"

          Display a multi-valued resource's service account keys with the
          corresponding service account, extracting just the first '/' delimited
          part with segment(0):

            $ gcloud iam service-accounts keys list --iam-account [email protected] --project test-minutia-123 --format="table(name.scope(serviceAccounts).segment(0):label='service Account',name.scope(keys):label='keyID',validAfterTime)"

          The last example returns a table with service account names without
          their full paths, keyID and validity.
          """,
    }
 def testResourceDescriptionUnknown(self):
     with self.assertRaisesRegex(
             ValueError, r'Expected one of \[filter,format,'
             r'key,projection\], got \[unknown\].'):
         resource_topics.ResourceDescription('unknown')
示例#7
0
class Projections(base.TopicCommand):
    """Resource projections supplementary help."""

    detailed_help = {

        # pylint: disable=protected-access, need transform dicts.
        'DESCRIPTION':
        textwrap.dedent("""\
          {description}

          ### Projections

          A projection is a list of keys that selects resource data values.
          Projections are used in *--format* flag expressions. For example, the
          *table* format requires a projection that describes the table columns:

            table(name, network.ip.internal, network.ip.external, uri())

          ### Transforms

          A *transform* formats resource data values. Each projection key may
          have zero or more transform calls:

            _key_._transform_([arg...])...

          This example applies the *foo*() and then the *bar*() transform to the
          *status.time* resource value:

            (name, status.time.foo().bar())

          {transform_registry}

          ### Key Attributes

          Key attributes control formatted output. Each projection key may have
          zero or more attributes:

            _key_:_attribute_=_value_...

          where =_value_ is omitted for Boolean attributes and no-_attribute_
          sets the attribute to false. Attribute values may appear in any order,
          but must be specified after any transform calls. The attributes are:

          *alias*=_ALIAS-NAME_::
          Sets _ALIAS-NAME_ as an alias for the projection key.

          *align*=_ALIGNMENT_::
          Specifies the output column data alignment. Used by the *table*
          format. The alignment values are:

          *left*:::
          Left (default).

          *center*:::
          Center.

          *right*:::
          Right.

          *label*=_LABEL_::
          A string value used to label output. Use :label="" or :label=''
          for no label. The *table* format uses _LABEL_ values as column
          headings. Also sets _LABEL_ as an alias for the projection key.
          The default label is the the disambiguated right hand parts of the
          column key name in ANGRY_SNAKE_CASE.

          [no-]*reverse*::
          Sets the key sort order to descending. *no-reverse* resets to the
          default ascending order.

          *sort*=_SORT-ORDER_::
          An integer counting from 1. Keys with lower sort-order are sorted
          first. Keys with same sort order are sorted left to right.

          *wrap*::
          Enables the column text to be wrapped if the table would otherwise
          be too wide for the display.
          """).format(
            description=resource_topics.ResourceDescription('projection'),
            transform_registry=resource_topics.TransformRegistryDescriptions(
            )),
        'EXAMPLES':
        """\
          List a table of instance *zone* (sorted in descending order) and
          *name* (sorted by *name* and centered with column heading *INSTANCE*)
          and *creationTimestamp* (listed using the *strftime*(3) year-month-day
          format with column heading *START*):

            $ gcloud compute instances list --format='table(name:sort=2:align=center:label=INSTANCE, zone:sort=1:reverse, creationTimestamp.date("%Y-%m-%d"):label=START)'

          List only the *name*, *status* and *zone* instance resource keys in
          YAML format:

            $ gcloud compute instances list --format='yaml(name, status, zone)'

          List only the *config.account* key value(s) in the *info* resource:

            $ gcloud info --format='value(config.account)'
          """,
    }
示例#8
0
class Filters(base.TopicCommand):
    """Resource filters supplementary help."""

    detailed_help = {
        'DESCRIPTION':
        textwrap.dedent("""\
          {description}

          === Filter Expressions ===

          A filter expression is a Boolean function that selects the resources
          to print from a list of resources. Expressions are composed
          of terms connected by logic operators.

          *LogicOperator*::

          Expressions containing both *AND* and *OR* must be parenthesized to
          disambiguate precedence.

          *NOT* _term-1_:::

          True if _term-1_ is False, otherwise False.

          _term-1_ *AND* _term-2_:::

          True if both _term-1_ and _term-2_ are true.

          _term-1_ *OR* _term-2_:::

          True if at least one of _term-1_ or _term-2_ is true.

          _term-1_ _term-2_:::

          True if both _term-1_ and _term-2_ are true. Implicit conjunction has
          lower precedence than *OR*.

          *Terms*::

          A term is a _key_ _operator_ _value_ tuple, where _key_ is a dotted
          name that evaluates to the value of a resource attribute, and _value_
          may be:

          *number*::: integer or floating point numeric constant

          *unquoted literal*::: character sequence terminated by space, ( or )

          *quoted literal*::: _"..."_ or _'...'_

          Most filter expressions need to be quoted in shell commands. If you
          use _'...'_ shell quotes then use _"..."_ filter string literal quotes
          and vice versa.

          *Operator Terms*::

          _key_ *=* _value_:::

          True if _key_ is equal to _value_.

          _key_ *=(* _value_ ... *)*:::

          True if _key_ is equal to any _value_ in the
          (space, tab, newline, *,*) separated list.

          _key_ *!=* _value_:::

          True if _key_ is not _value_. Equivalent to
          -_key_=_value_ and NOT _key_=_value_.

          _key_ *<* _value_:::

          True if _key_ is less than _value_. If both _key_ and
          _value_ are numeric then numeric comparison is used, otherwise
          lexicographic string comparison is used.

          _key_ *<=* _value_:::

          True if _key_ is less than or equal to _value_. If both
          _key_ and _value_ are numeric then numeric comparison is used,
          otherwise lexicographic string comparison is used.

          _key_ *>=* _value_:::

          True if _key_ is greater than or equal to _value_. If
          both _key_ and _value_ are numeric then numeric comparison is used,
          otherwise lexicographic string comparison is used.

          _key_ *>* _value_:::

          True if _key_ is greater than _value_. If both _key_ and
          _value_ are numeric then numeric comparison is used, otherwise
          lexicographic string comparison is used.

          _key_ *:* _simple-pattern_:::

          True if _key_ matches _simple-pattern_. The match is anchored (all
          characters must match), case insensitive, and allows one ```*```
          operator that matches any sequence of 0 or more characters. The
          pattern ```abc``` matches ```abc```, the pattern ```abc*``` matches
          ```abc``` and ```abcxyz```, the pattern ```*xyz``` matches ```xyz```
          and ```abcxyz```, and the pattern ```*``` matches any non-empty
          string. Use _key_```:*``` to test if _key_ is defined and
          ```-```_key_```:*``` to test if _key_ is undefined.

          _key_ *:(* _simple-pattern_ ... *)*:::

          True if _key_ matches any _simple-pattern_ in the
          (space, tab, newline, comma) separated list.

          _key_ *~* _value_:::

          True if _key_ matches the RE (regular expression) pattern _value_.

          _key_ *!*~ _value_:::

          True if _key_ does not match the RE (regular expression)
          pattern _value_.

          """).format(
            description=resource_topics.ResourceDescription('filter')),
        'EXAMPLES':
        textwrap.dedent("""\
          List all instances resources:

            $ gcloud compute instances list

          List instances resources that have machineType *f1-micro*:

            $ gcloud compute instances list --filter='machineType:f1-micro'

          List resources with zone prefix *us* and not MachineType *f1-micro*:

            $ gcloud compute instances list --filter='zone ~ ^us AND -machineType:f1-micro'

          List in JSON format those projects where the labels match specific
          values (e.g. label.env is 'test' and label.version is alpha):

            $ gcloud projects list --format="json" --filter="labels.env=test AND labels.version=alpha"

          List projects that were created after a specific date:

            $ gcloud projects list --format="table(projectNumber,projectId,createTime)" --filter="createTime.date('%Y-%m-%d', Z)='2016-05-11'"

          Note that in the last example, a projection on the key was used. The
          filter is applied on the createTime key after the date formatting is
          set.
          """),
    }
示例#9
0
class Filters(base.TopicCommand):
    """Resource filters supplementary help."""

    detailed_help = {
        'DESCRIPTION':
        textwrap.dedent("""\
          {description}
          +
          Note: Depending on the specific server API, filtering may be done
          entirely by the client, entirely by the server, or by a combination
          of both.

          ### Filter Expressions

          A filter expression is a Boolean function that selects the resources
          to print from a list of resources. Expressions are composed
          of terms connected by logic operators.

          *LogicOperator*::

          Expressions containing both *AND* and *OR* must be parenthesized to
          disambiguate precedence.

          *NOT* _term-1_:::

          True if _term-1_ is False, otherwise False.

          _term-1_ *AND* _term-2_:::

          True if both _term-1_ and _term-2_ are true.

          _term-1_ *OR* _term-2_:::

          True if at least one of _term-1_ or _term-2_ is true.

          _term-1_ _term-2_:::

          Term conjunction (implicit *AND*) is True if both _term-1_
          and _term-2_ are true.  Conjunction has lower precedence than *OR*.

          *Terms*::

          A term is a _key_ _operator_ _value_ tuple, where _key_ is a dotted
          name that evaluates to the value of a resource attribute, and _value_
          may be:

          *number*::: integer or floating point numeric constant

          *unquoted literal*::: character sequence terminated by space, ( or )

          *quoted literal*::: _"..."_ or _'...'_

          Most filter expressions need to be quoted in shell commands. If you
          use _'...'_ shell quotes then use _"..."_ filter string literal quotes
          and vice versa.

          *Operator Terms*::

          _key_ *:* _simple-pattern_:::

          *:* operator evaluation is changing for consistency across Google
          APIs.  The current default is deprecated and will be dropped shortly.
          A warning will be displayed when a --filter expression would return
          different matches using both the deprecated and new implementations.
          +
          The current deprecated default is True if _key_ contains
          _simple-pattern_.  The match is case insensitive.  It allows one
          ```*``` that matches any sequence of 0 or more characters.
          If ```*``` is specified then the match is anchored, meaning all
          characters from the beginning and end of the value must match.
          +
          The new implementation is True if _simple-pattern_ matches any
          _word_ in _key_.  Words are locale specific but typically consist of
          alpha-numeric characters.  Non-word characters that do not appear in
          _simple-pattern_ are ignored.  The matching is anchored and case
          insensitive.  An optional trailing ```*``` does a word prefix match.
          +
          Use _key_```:*``` to test if _key_ is defined and
          ```-```_key_```:*``` to test if _key_ is undefined.

          _key_ *:(* _simple-pattern_ ... *)*:::

          True if _key_ matches any _simple-pattern_ in the
          (space, tab, newline, comma) separated list.

          _key_ *=* _value_:::

          True if _key_ is equal to _value_, or [deprecated] equivalent to *:*
          with the exception that the trailing ```*``` prefix match is not
          supported.
          +
          For historical reasons, this operation currently behaves differently
          for different Google APIs. For many APIs, this is True if key is
          equal to value. For a few APIs, this is currently equivalent to *:*,
          with the exception that the trailing ```*``` prefix match is not
          supported. However, this behaviour is being phased out, and use of
          ```=``` for those APIs is deprecated; for those APIs, if you want
          matching, you should use ```:``` instead of ```=```, and if you want
          to test for equality, you can use
          _key_ <= _value_ AND _key_ >= _value_.

          _key_ *=(* _value_ ... *)*:::

          True if _key_ is equal to any _value_ in the
          (space, tab, newline, *,*) separated list.

          _key_ *!=* _value_:::

          True if _key_ is not _value_. Equivalent to
          -_key_=_value_ and NOT _key_=_value_.

          _key_ *<* _value_:::

          True if _key_ is less than _value_. If both _key_ and
          _value_ are numeric then numeric comparison is used, otherwise
          lexicographic string comparison is used.

          _key_ *<=* _value_:::

          True if _key_ is less than or equal to _value_. If both
          _key_ and _value_ are numeric then numeric comparison is used,
          otherwise lexicographic string comparison is used.

          _key_ *>=* _value_:::

          True if _key_ is greater than or equal to _value_. If
          both _key_ and _value_ are numeric then numeric comparison is used,
          otherwise lexicographic string comparison is used.

          _key_ *>* _value_:::

          True if _key_ is greater than _value_. If both _key_ and
          _value_ are numeric then numeric comparison is used, otherwise
          lexicographic string comparison is used.

          _key_ *~* _value_:::

          True if _key_ contains a match for the RE (regular expression) pattern
          _value_.

          _key_ *!*~ _value_:::

          True if _key_ does not contain a match for the RE (regular expression)
          pattern _value_.

          For more about regular expression syntax, see:
          https://docs.python.org/3/library/re.html#re-syntax which follows the
          PCRE dialect.

          ### Determine which fields are available for filtering

          In order to build filters, it is often helpful to review some
          representative fields returned from commands. One simple way to do
          this is to add `--format=yaml --limit=1` to a command. With these
          flags, a single record is returned and its full contents are displayed
          as a YAML document. For example, a list of project fields could be
          generated by running:

            $ gcloud projects list --format=yaml --limit=1

          This might display the following data:

            ```yaml
            createTime: '2021-02-10T19:19:49.242Z'
            lifecycleState: ACTIVE
            name: MyProject
            parent:
              id: '123'
              type: folder
            projectId: my-project
            projectNumber: '456'
            ```

          Using this data, one way of filtering projects is by their parent's ID
          by specifying ``parent.id'' as the _key_.
          """).format(
            description=resource_topics.ResourceDescription('filter')),
        'EXAMPLES':
        textwrap.dedent("""\
          List all Google Compute Engine instance resources:

            $ gcloud compute instances list

          List Compute Engine instance resources that have machineType
          *f1-micro*:

            $ gcloud compute instances list --filter="machineType:f1-micro"

          List Compute Engine instance resources using a regular expression for
          zone *us* and not MachineType *f1-micro*:

            $ gcloud compute instances list --filter="zone ~ us AND -machineType:f1-micro"

          List Compute Engine instance resources with tag *my-tag*:

            $ gcloud compute instances list --filter="tags.items=my-tag"

          List Compute Engine instance resources with tag *my-tag* or
          *my-other-tag*:

            $ gcloud compute instances list --filter="tags.items=(my-tag,my-other-tag)"

          List Compute Engine instance resources with tag *my-tag* and
          *my-other-tag*:

            $ gcloud compute instances list --filter="tags.items=my-tag AND tags.items=my-other-tag"

          List Compute Engine instance resources which either have tag *my-tag*
          but not *my-other-tag* or have tag *alternative-tag*:

            $ gcloud compute instances list --filter="(tags.items=my-tag AND -tags.items=my-other-tag) OR tags.items=alternative-tag"

          List Compute Engine instance resources which contain the key *fingerprint*
          in the *metadata* object:

            $ gcloud compute instances list --limit=1 --filter="metadata.list(show="keys"):fingerprint"

          List Compute Engine instance resources with label *my-label* with any
          value:

            $ gcloud compute instances list --filter="labels.my-label:*"

          List in JSON format those projects where the labels match specific
          values (e.g. label.env is 'test' and label.version is alpha):

            $ gcloud projects list --format="json" --filter="labels.env=test AND labels.version=alpha"

          List projects that were created on and after a specific date:

            $ gcloud projects list --format="table(projectNumber,projectId,createTime)" --filter="createTime>=2018-01-15"

          List projects that were created on and after a specific date and time
          and sort from oldest to newest (with dates and times listed according
          to the local timezone):

            $ gcloud projects list --format="table(projectNumber,projectId,createTime.date(tz=LOCAL))" --filter="createTime>=2018-01-15T12:00:00" --sort-by=createTime

          List projects that were created within the last two weeks, using
          ISO8601 durations:

            $ gcloud projects list --format="table(projectNumber,projectId,createTime)" --filter="createTime>-P2W"

          For more about ISO8601 durations, see: https://en.wikipedia.org/wiki/ISO_8601
          +
          The table below shows examples of pattern matching if used with
          the `:` operator:

          PATTERN | VALUE | MATCHES | DEPRECATED_MATCHES
          --- | --- | --- | ---
          abc* | abcpdqxyz | True | True
          abc | abcpdqxyz | False | True
          pdq* | abcpdqxyz | False | False
          pdq | abcpdqxyz | False | True
          xyz* | abcpdqxyz | False | False
          xyz | abcpdqxyz | False | True
          * | abcpdqxyz | True | True
          * | (None) | False | False
          * | ('') | False | False
          * | (otherwise) | True | True
          abc* | abc.pdq.xyz | True | True
          abc | abc.pdq.xyz | True | True
          abc.pdq | abc.pdq.xyz | True | True
          pdq* | abc.pdq.xyz | True | False
          pdq | abc.pdq.xyz | True | True
          pdq.xyz | abc.pdq.xyz | True | True
          xyz* | abc.pdq.xyz | True | False
          xyz | abc.pdq.xyz | True | True
          """),
    }
示例#10
0
class Filters(base.Command):
    """Resource filters supplementary help."""
    def Run(self, args):
        self.cli.Execute(args.command_path[1:] + ['--document=style=topic'])
        return None

    detailed_help = {
        'DESCRIPTION':
        textwrap.dedent("""\
          {description}

          === Filter Expressions ===

          A filter expression is a Boolean function that selects resources from
          a list. Expressions are composed of terms connected by logic
          operators.

          *LogicOperator*::

          Expressions containing both *AND* and *OR* must be parenthesized to
          disambiguate precedence.

          *NOT* _term-1_:::

          True if _term-1_ is False, otherwise False.

          _term-1_ *AND* _term-2_:::

          True if both _term-1_ and _term-2_ are true.

          _term-1_ *OR* _term-2_:::

          True if at least one of _term-1_ or _term-2_ is true.

          _term-1_ _term-2_:::

          True if both _term-1_ and _term-2_ are true. Implicit conjunction has
          lower precedence than *OR*.

          *Terms*::

          A term is a _key_ _operator_ _value_ tuple, where _key_ is a dotted
          name for a resource attribute, and _value_ may be:

          *number*:::: integer or floating point numeric constant

          *unquoted literal*:::: character sequence terminated by space, ( or )

          *quoted literal*:::: _"..."_ or _'...'_

          Most filter expressions need to be quoted in shell commands. If you
          use _'...'_ shell quotes then use _"..."_ filter string literal quotes
          and vice versa.

          *Operator Terms*::

          _key_ *=* _value_:::

          True if the value of _key_ is _value_.

          _key_ *!=* _value_:::

          True if the value of _key_ is not _value_. Equivalent to
          -_key_=_value_ and NOT _key_=_value_.

          _key_ *<* _value_:::

          True if the value of _key_ is less than _value_. If both _key_ and
          _value_ are numeric then numeric comparison is used, otherwise
          lexicographic string comparison is used.

          _key_ *<=* _value_:::

          True if the value of _key_ is less than or equal to _value_. If both
          _key_ and _value_ are numeric then numeric comparison is used,
          otherwise lexicographic string comparison is used.

          _key_ *>=* _value_:::

          True if the value of _key_ is greater than or equal to _value_. If
          both _key_ and _value_ are numeric then numeric comparison is used,
          otherwise lexicographic string comparison is used.

          _key_ *>* _value_:::

          True if the value of _key_ is greater than _value_. If both _key_ and
          _value_ are numeric then numeric comparison is used, otherwise
          lexicographic string comparison is used.

          _key_ *:* _value_:::

          True if _value_ contains the value of _key_ using case insensitive
          string comparison.

          _key_ *~* _value_:::

          True if the value of _key_ matches the RE (regular expression)
          pattern _value_.

          _key_ *!*~ _value_:::

          True if the value of _key_ does not match the RE (regular expression)
          pattern _value_.

          """).format(
            description=resource_topics.ResourceDescription('filter')),
        'EXAMPLES':
        textwrap.dedent("""\
          List all instances resources:

            $ gcloud compute instances list

          List instances resources that have machineType *f1-micro*:

            $ gcloud compute instances list --filter='machineType:f1-micro'

          List resources with zone prefix *us* and not MachineType *f1-micro*:

            $ gcloud compute instances list --filter='zone ~ ^us AND -machineType:f1-micro'

          List resources with zone prefix *us* and not MachineType *f1-micro*:

            $ gcloud compute instances list --filter='zone ~ ^us AND -machineType:f1-micro'
          """),
    }