o
    v[                    @   sD  d Z ddlmZ ddlmZ ddlmZ ddlZddlZddlZddlZddl	Z	ddl
Z
ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlZddlmZ ddgZG dd deZG dd deej Z G dd deej!Z"G dd deZ#dddZ$dd Z%dZ&dZ'd Z(d!e( Z)d!e) Z*d"e* Z+e(e)e*e+d#Z,d d$d%d&d'd(d$d%d&d'd(d)Z-d*d*d+d+d,d,d-d-d.d.d/
Z.d0d1 Z/d2d3 Z0dd4d5Z1dd6d7Z2			8	.	dd9d:Z3d;d< Z4dd=d>Z5	?	@		?ddAdZ6				B	.ddCdZ7dDZ8G dEdF dFe9Z:G dGdH dHe9Z;G dIdJ dJe9Z<G dKdL dLe9Z=G dMdN dNe9Z>			OddPdQZ?dRdS Z@dTdU ZAdVdW ZBdXdY ZCdZd[ ZDdd]d^ZEd_d` ZFddadbZGG dcdd dde9ZHG dedf dfejIeHZJ	8ddgeKdheKdieKfdjdkZLdldm ZMdndo ZNdpdq ZOG drds dsejIeHZPG dtdu duejIeHZQdveRdweRdieRfdxdyZSG dzd{ d{eQZTG d|d} d}eTZUG d~d dejVZWG dd deWZXG dd dejYZZdddZ[G dd dejVZ\dd Z]G dd dejVZ^dd Z_G dd dejIZ`G dd de9ZaG dd dejbZcdddZdG dd dejVZeG dd de9ZfdS )a  A module that provides parsing utilities for argparse.

For details of how argparse argument pasers work, see:

http://docs.python.org/dev/library/argparse.html#type

Example usage:

import argparse
import arg_parsers

parser = argparse.ArgumentParser()

parser.add_argument(
'--metadata',
type=arg_parsers.ArgDict())
parser.add_argument(
'--delay',
default='5s',
type=arg_parsers.Duration(lower_bound='1s', upper_bound='10s')
parser.add_argument(
'--disk-size',
default='10GB',
type=arg_parsers.BinarySize(lower_bound='1GB', upper_bound='10TB')

res = parser.parse_args(
'--names --metadata x=y,a=b,c=d --delay 1s --disk-size 10gb'.split())

assert res.metadata == {'a': 'b', 'c': 'd', 'x': 'y'}
assert res.delay == 1
assert res.disk_size == 10737418240

    )absolute_import)division)unicode_literalsN)tz)arg_parsers_usage_text)parser_errors)log)
properties)console_attr)
console_io)files)times)zipDuration
BinarySizec                   @      e Zd ZdZdS )Errorz+Exceptions that are defined by this module.N__name__
__module____qualname____doc__ r   r   @/tmp/google-cloud-sdk/lib/googlecloudsdk/calliope/arg_parsers.pyr   M       r   c                   @   r   )ArgumentTypeErrorz7Exceptions for parsers that are used as argparse types.Nr   r   r   r   r   r   Q   r   r   c                   @   r   )ArgumentParsingErrorzRaised when there is a problem with user input.

  argparse.ArgumentError takes both the action and a message as constructor
  parameters.
  Nr   r   r   r   r   r   U   r   r   c                   @   r   )InvalidTypeErrorz=Error for when contributor provides incorrect type arguments.Nr   r   r   r   r   r   ]   r   r   c                 C   s<   |du r| S |s| d S |du r| d | S dj | ||dS )a  Constructs an error message for an exception.

  Args:
    error: str, The error message that should be displayed. This message should
      not end with any punctuation--the full error message is constructed by
      appending more information to error.
    user_input: str, The user input that caused the error.
    error_idx: int, The index at which the error occurred. If None, the index
      will not be printed in the error message.

  Returns:
    str: The message to use for the exception.
  Nz; received empty stringz; received: z2{error_message} at index {error_idx}: {user_input})error_message
user_input	error_idx)format)errorr   r    r   r   r   _GenerateErrorMessagea   s   r#   c                 C   s   d d| S )zConstructs an error message for exception thrown invalid input.

  Args:
    unit_scales: list, A list of strings with units that will be recommended to
      user.

  Returns:
    str: The message to use for the exception.
  zvgiven value must be of the form DECIMAL[UNITS] where units can be one of {0} and value must be a whole number of Bytes, )r!   join)unit_scalesr   r   r   InvalidInputErrorMessagey   s
   
r'   z
    ^                           # Beginning of input marker.
    (?P<amount>\d+\.?\d*)       # Amount.
    ((?P<suffix>[-/a-zA-Z]+))?  # Optional scale and type abbr.
    $                           # End of input marker.
z&^(?P<start>[0-9]+)(-(?P<end>[0-9]+))?$   <      )smhd   i   i   @l        l           ) KMGTPKiMiGiTiPiTiBGiBMiBKiBB)
PiBPBr;   TBr<   GBr=   MBr>   KBc                 C   sX   t | }|}t| s(|r(|tv r(|d t| }}t| s(|r(|tv s||fS )a  Convert input value and units to a whole number of a lower unit.

  Args:
    amount: str, a number, for example '3.25'
    unit: str, a binary prefix, for example 'GB' or 'GiB'

  Returns:
    (decimal.Decimal(), str), a tuple of number and suffix, converted such that
    the number returned is an integer, or the value, in Bytes, of the amount
    input. For example (23, 'MiB'). Note that IEC binary prefixes are always
    assumed and returned.
  r/   )decimalDecimalfloat
is_integer_UnitToLowerUnitDict)amountunitreturn_amountreturn_unitr   r   r   ConvertToWholeNumber   s   
rO   c                    s    fdd}|S )zCreate a completer to handle completion for comma separated lists.

  Args:
    individual_completer: A function that completes an individual element.

  Returns:
    A function that completes the last element of the list.
  c                    sT   d |  dd}t|dkr|d d  |d } | |fi |} fdd|D S )Nr0   ,r(   r   c                    s   g | ]} | qS r   r   ).0matchstartr   r   
<listcomp>       z=GetMultiCompleter.<locals>.MultiCompleter.<locals>.<listcomp>)rsplitlen)prefixparsed_argskwargslstmatchesindividual_completerrS   r   MultiCompleter   s   z)GetMultiCompleter.<locals>.MultiCompleterr   )r_   r`   r   r^   r   GetMultiCompleter   s   
	ra   c                 C   sV   | s| S |   }t|}t|  D ]}|s n||d  |kr$|d8 }q| d| S )z7Returns suffix with trailing type abbreviation deleted.r(   N)upperrX   reversed)suffix	type_abbrr+   icr   r   r   _DeleteTypeAbbr   s   rh   c                 C   s   t |  |}t|S )aw  Returns the binary size per unit for binary suffix string.

  Args:
    suffix: str, A case insensitive unit suffix string with optional type
      abbreviation.
    type_abbr: str, The optional case insensitive type abbreviation following
      the suffix.

  Raises:
    ValueError for unknown units.

  Returns:
    The binary size per unit for a unit+type_abbr suffix.
  )rh   rb   _BINARY_SIZE_SCALESget)rd   re   rL   r   r   r   GetBinarySizePerUnit   s   
rk   Tc                    sj   d	fdd		fdd du rdn 
du r%dn 
 
fdd}|S )	a  A helper that returns a function that can parse values with units.

  Casing for all units matters.

  Args:
    scales: {str: int}, A dictionary mapping units to their magnitudes in
      relation to the lowest magnitude unit in the dict.
    default_unit: str, The default unit to use if the user's input is missing
      unit.
    lower_bound: str, An inclusive lower bound.
    upper_bound: str, An inclusive upper bound.
    strict_case: bool, whether to be strict on case-checking
    type_abbr: str, the type suffix abbreviation, e.g., B for bytes, b/s for
      bits/sec.
    suggested_binary_size_scales: list, A list of strings with units that will
      be recommended to user.

  Returns:
    A function that can parse values.
  Nc                    sD   t tdd d} du rfdd|D S  fdd|D S )z:Returns a list of the units in scales sorted by magnitude.c                 S   s   | d | d fS )Nr(   r   r   valuer   r   r   <lambda>)  s    z8_ValueParser.<locals>.UnitsByMagnitude.<locals>.<lambda>)keyNc                    s   g | ]\}}|  qS r   r   rQ   ro   _)re   r   r   rU   +      z:_ValueParser.<locals>.UnitsByMagnitude.<locals>.<listcomp>c                    s$   g | ]\}}|  v r| qS r   r   rp   )suggested_binary_size_scalesre   r   r   rU   ,  s
    )sortedsix	iteritems)rs   scale_items)scalesre   )rs   r   UnitsByMagnitude&  s   z&_ValueParser.<locals>.UnitsByMagnitudec                    s  t t| t j}|sttt | d|dpd}t|d|\}}t	|
 s9ttt | dt|}t|}rN|}t}}n| }t }tdd  D }|sp||krp|||  S ||v rz|||  S ttdd  |d)	z;Parses value that can contain a unit and type abbreviation.r   rd   r0   rK   c                 S   s   g | ]
\}}|  |fqS r   )rb   )rQ   kvr   r   r   rU   L      z/_ValueParser.<locals>.Parse.<locals>.<listcomp>zunit must be one of {0}r$   )rerR   _VALUE_PATTERNVERBOSEr   r#   r'   grouprO   rH   rI   intrh   rb   dictitemsr!   r%   )rm   rR   rd   rK   rL   	unit_casedefault_unit_casescales_case)ry   default_unitrx   strict_casers   re   r   r   Parse2  sP   

z_ValueParser.<locals>.Parsec                    d   | du rdS  | }dur|k rt td| ddur0|kr0t td| d|S z1Same as Parse except bound checking is performed.Nz*value must be greater than or equal to {0}rz   z'value must be less than or equal to {0}r   r#   r!   rm   parsed_valuer   lower_boundparsed_lower_boundparsed_upper_boundupper_boundr   r   ParseWithBoundsCheckingb  s(   z-_ValueParser.<locals>.ParseWithBoundsCheckingNr   )rx   r   r   r   r   re   rs   r   r   )r   ry   r   r   r   r   rx   r   rs   re   r   r   _ValueParser
  s   &r   c                        fdd}|S )a  Returns a function that validates a string against a regular expression.

  For example:

  >>> alphanumeric_type = RegexpValidator(
  ...   r'[a-zA-Z0-9]+',
  ...   'must contain one or more alphanumeric characters')
  >>> parser.add_argument('--foo', type=alphanumeric_type)
  >>> parser.parse_args(['--foo', '?'])
  >>> # SystemExit raised and the error "error: argument foo: Bad value [?]:
  >>> # must contain one or more alphanumeric characters" is displayed

  Args:
    pattern: str, the pattern to compile into a regular expression to check
    description: an error message to show if the argument doesn't match

  Returns:
    function: str -> str, usable as an argparse type
  c                    s$   t d | std|  | S )N$Bad value [{0}]: {1})r~   rR   r   r!   rl   descriptionpatternr   r   r     s   zRegexpValidator.<locals>.Parser   )r   r   r   r   r   r   RegexpValidatory  s   r   c                    s    fdd}|S )a  Returns a function that validates the input by running it through fn.

  For example:

  >>> def isEven(val):
  ...   return val % 2 == 0
  >>> even_number_parser = arg_parsers.CustomFunctionValidator(
        isEven, 'This is not even!', parser=arg_parsers.BoundedInt(0))
  >>> parser.add_argument('--foo', type=even_number_parser)
  >>> parser.parse_args(['--foo', '3'])
  >>> # SystemExit raised and the error "error: argument foo: Bad value [3]:
  >>> # This is not even!" is displayed

  Args:
    fn: str -> boolean
    description: an error message to show if boolean function returns False
    parser: an arg_parser that is applied to to value before validation. The
      value is also returned by this parser.

  Returns:
    function: str -> str, usable as an argparse type
  c                    sR   z
r| n| }W n	 t y   Y nw |r|S t| }d| }t |)zDValidates and returns a custom object from an argument string value.r   )r   r
   SafeTextr!   )rm   r   encoded_valueformatted_errr   fnparserr   r   r     s   
z&CustomFunctionValidator.<locals>.Parser   )r   r   r   r   r   r   r   CustomFunctionValidator  s   r   r+   0c                    sD   fdd  du rdn  fdd}|S )a  Returns a function that can parse time durations.

  See times.ParseDuration() for details. If the unit is omitted, seconds is
  assumed. The parsed unit is assumed to be seconds, but can be specified as
  ms or us.
  For example:

    parser = Duration()
    assert parser('10s') == 10
    parser = Duration(parsed_unit='ms')
    assert parser('10s') == 10000
    parser = Duration(parsed_unit='us')
    assert parser('10s') == 10000000

  Args:
    default_unit: str, The default duration unit.
    lower_bound: str, An inclusive lower bound for values.
    upper_bound: str, An inclusive upper bound for values.
    parsed_unit: str, The unit that the result should be returned as. Can be
      's', 'ms', or 'us'.

  Raises:
    ArgumentTypeError: If either the lower_bound or upper_bound
      cannot be parsed. The returned function will also raise this
      error if it cannot parse its input. This exception is also
      raised if the returned function receives an out-of-bounds
      input.

  Returns:
    A function that accepts a single time duration as input to be
      parsed an returns an integer if the parsed value is not a fraction;
      Otherwise, a float value rounded up to 4 decimals places.
  c           	   
      s   dkrd}ndkrd}ndkrd}nt tdz!tj|  d}|j| }t|}t|d	}|| }|r:|W S |W S  tjy\ } zt	|
d
}t tdj|| dd}~ww )z?Parses a duration from value and returns it in the parsed_unit.msi  usi@B r+   r(   z%parsed_unit must be one of s, ms, us.)default_suffix   .zFailed to parse duration: {0}rz   N)r   r#   r   ParseDurationtotal_secondsr   roundr   ru   	text_typerstripr!   )	rm   
multiplierdurationr   parsed_int_valueparsed_rounded_valuefractionemessage)r   parsed_unitr   r   r     s2   

zDuration.<locals>.ParseNc                    r   r   r   r   r   r   r   r     s$   z)Duration.<locals>.ParseWithBoundsCheckingr   )r   r   r   r   r   r   )r   r   r   r   r   r   r   r   r     s   &r3   c              	   C   s   t t|| |d||dS )aI  Returns a function that can parse binary sizes.

  Binary sizes are defined as base-2 values representing number of
  bytes.

  Input to the parsing function must be a string of the form:

    DECIMAL[UNIT]

  The amount must be non-negative. Valid units are "B", "KB", "MB",
  "GB", "TB", "PB", "KiB", "MiB", "GiB", "TiB", "PiB".  If the unit is
  omitted then default_unit is assumed.

  The result is parsed in bytes. For example:

    parser = BinarySize()
    assert parser('10GB') == 1073741824

  Another example:

    parser = BinarySize()
    assert parser('2.5KB') == 2560

  Args:
    lower_bound: str, An inclusive lower bound for values.
    upper_bound: str, An inclusive upper bound for values.
    suggested_binary_size_scales: list, A list of strings with units that will
      be recommended to user.
    default_unit: str, unit used when user did not specify unit.
    type_abbr: str, the type suffix abbreviation, e.g., B for bytes, b/s for
      bits/sec.

  Raises:
    ArgumentTypeError: If either the lower_bound or upper_bound
      cannot be parsed. The returned function will also raise this
      error if it cannot parse its input. This exception is also
      raised if the returned function receives an out-of-bounds
      input.

  Returns:
    A function that accepts a single binary size as input to be
      parsed.
  F)r   r   r   r   re   rs   )r   ri   )r   r   rs   r   re   r   r   r   r     s   0=c                   @   sD   e Zd ZdZdd Zedd Zdd Zdd	 Zd
d Z	dd Z
dS )RangezRange of integer values.c                 C      || _ || _d S r   rT   end)selfrT   r   r   r   r   __init__X     
zRange.__init__c                 C   sp   t t| }|std| t|d}|d}|du r"|}nt|}||k r3td||| t||S )z/Creates Range object out of given string value.zPExpected a non-negative integer value or a range of such values instead of "{0}"rT   r   NzCExpected range start {0} smaller or equal to range end {1} in "{2}")r~   rR   _RANGE_PATTERNr   r!   r   r   r   )string_valuerR   rT   r   r   r   r   r   \  s$   

zRange.Parsec                 C   sN   | j d |jk s| j|j d krtd| |tt| j|jt| j |j S )z>Combines two overlapping or adjacent ranges, raises otherwise.r(   zACannot combine non-overlapping or non-adjacent ranges {0} and {1})r   rT   r   r!   r   minmaxr   otherr   r   r   Combinep  s
    zRange.Combinec                 C   s&   t |tr| j|jko| j|jkS dS NF)
isinstancer   rT   r   r   r   r   r   __eq__w  s   
zRange.__eq__c                 C   s$   | j |j kr| j|jk S | j |j k S r   r   r   r   r   r   __lt__|  s   zRange.__lt__c                 C   s(   | j | jkrt| j S d| j | jS )Nz{0}-{1})rT   r   ru   r   r!   r   r   r   r   __str__  s   zRange.__str__N)r   r   r   r   r   staticmethodr   r   r   r   r   r   r   r   r   r   U  s    
r   c                   @   s.   e Zd ZdZdZdZdd Zed
ddZd	S )HostPortz.A class for holding host and port information.z/^(?P<address>[\w\d\.-]+)?(:|:(?P<port>[\d]+))?$z2^(\[(?P<address>[\w\d:]+)\])(:|:(?P<port>[\d]+))?$c                 C   r   r   )hostport)r   r   r   r   r   r   r     r   zHostPort.__init__Fc                 C   sz   | st ddS tt j| tj}|r(|s(tt j| tj}|s'ttd| dn
|s2ttd| dt |d|dS )a  Parse the given string into a HostPort object.

    This can be used as an argparse type.

    Args:
      s: str, The string to parse. If ipv6_enabled and host is an IPv6 address,
      it should be placed in square brackets: e.g.
        [2001:db8:0:0:0:ff00:42:8329] or
        [2001:db8:0:0:0:ff00:42:8329]:8080
      ipv6_enabled: boolean, If True then accept IPv6 addresses.

    Raises:
      ArgumentTypeError: If the string is not valid.

    Returns:
      HostPort, The parsed object.
    NzFailed to parse host and port. Expected format 

  IPv4_ADDRESS_OR_HOSTNAME:PORT

or

  [IPv6_ADDRESS]:PORT

(where :PORT is optional).rz   zlFailed to parse host and port. Expected format 

  IPv4_ADDRESS_OR_HOSTNAME:PORT

(where :PORT is optional).addressr   )	r   r~   rR   IPV4_OR_HOST_PATTERNUNICODEIPV6_PATTERNr   r#   r   )r+   ipv6_enabledrR   r   r   r   r     s*   
	zHostPort.ParseNF)	r   r   r   r   r   r   r   r   r   r   r   r   r   r     s    r   c                   @   s   e Zd ZdZedd ZdS )Dayz9A class for parsing a datetime object for a specific day.c              
   C   sR   | sd S z	t | d W S  t jy( } zttdt|| dd }~ww )Nz%Y-%m-%dzFailed to parse date: {0}rz   )	r   ParseDateTimedater   r   r#   r!   ru   r   r+   r   r   r   r   r     s   z	Day.ParseN)r   r   r   r   r   r   r   r   r   r   r     s    r   c                   @   s(   e Zd ZdZedd Zedd ZdS )Datetimez&A class for parsing a datetime object.c              
   C   sL   | sdS zt | W S  t jy% } zttdt|| dd}~ww )z?Parses a string value into a Datetime object in local timezone.NzFailed to parse date/time: {0}rz   )r   r   r   r   r#   r!   ru   r   r   r   r   r   r     s   zDatetime.Parsec              
   C   sT   | sdS z
t j| t dW S  t jy) } zttdt	|| dd}~ww )zBParses a string representing a time in UTC into a Datetime object.N)tzinfozFailed to parse UTC time: {0}rz   )
r   r   r   tzutcr   r   r#   r!   ru   r   r   r   r   r   ParseUtcTime  s   zDatetime.ParseUtcTimeN)r   r   r   r   r   r   r   r   r   r   r   r     s    
r   c                   @   s$   e Zd ZdZg dZedd ZdS )	DayOfWeekz&A class for parsing a day of the week.)SUNMONTUEWEDTHUFRISATc                 C   sD   | sdS |   dd }|tjvr ttddtj| d|S )z7Validates and normalizes a string as a day of the week.N   z7Failed to parse day of week. Value should be one of {0}r$   rz   )rb   r   DAYSr   r#   r!   r%   )r+   fixedr   r   r   r     s   

zDayOfWeek.ParseN)r   r   r   r   r   r   r   r   r   r   r   r     s
    r   Fc                    s    fdd}|S )aO  Returns a function that can parse given type within some bound.

  Args:
    type_builder: A callable for building the requested type from the value
      string.
    type_description: str, Description of the requested type (for verbose
      messages).
    lower_bound: of type compatible with type_builder, The value must be >=
      lower_bound.
    upper_bound: of type compatible with type_builder, The value must be <=
      upper_bound.
    unlimited: bool, If True then a value of 'unlimited' means no limit.

  Returns:
    A function that can parse given type within some bound.
  c                    s   r| dkrdS z| }W n t y    ttd| dw  dur4| k r4ttd | ddurG|k rGttd| d|S )a  Parses value as a type constructed by type_builder.

    Args:
      value: str, Value to be converted to the requested type.

    Raises:
      ArgumentTypeError: If the provided value is out of bounds or unparsable.

    Returns:
      Value converted to the requested type.
    	unlimitedNzValue must be {0}rz   z*Value must be greater than or equal to {0}z'Value must be less than or equal to {0})
ValueErrorr   r#   r!   )rm   r|   r   type_buildertype_descriptionr   r   r   r   r     s4   
z_BoundedType.<locals>.Parser   )r   r   r   r   r   r   r   r   r   _BoundedType   s   $r   c                  O      t tdg| R i |S )Nz
an integer)r   r   argsr[   r   r   r   
BoundedInt=     r   c                  O   r   )Nza floating point number)r   rH   r   r   r   r   BoundedFloatA  r   r   c                 C   s,   | sg S |  |s| |7 } | |d d S )N)endswithsplit)	arg_valuedelimr   r   r   _SplitOnDelimE  s
   
r   c                 C   s   ddd}t | }g }tt| D ]4}|dkr"| |d  dkr"q| | }||v r>|| }|r6|d |kr9 dS |  q||v rG|| q| S )	z1Checks whether the string contains balanced json.{[)}]r   r(   \r   F)setvaluesrangerX   popappend)	str_valueclosing_bracketsopening_bracketscurrent_bracketsrf   chmatching_bracer   r   r   _ContainsValidJSONM  s    


r  c                 C   sT   g }d}| D ]}|s|}n||| 7 }t |r|| d}q|r(td||S )a  Rejoins json substrings that are part of the same json strings.

  For example:
      [
          'key={"a":"b"',
          '"c":"d"}'
      ]

  Is merged together into: ['key={"a":"b","c":"d"}']

  Args:
    json_list: [str], list of json snippets
    delim: str, delim used to rejoin the json snippets
    arg_value: str, original value used to make json_list

  Returns:
    list of strings containing balanced json
  NzWInvalid entry "{}": missing opening brace ("{{" or "[") or closing brace ("}}" or "]").)r  r  r   r!   )	json_listr   r   resultcurrent_substrtokenr   r   r   _RejoinJSONStrsd  s    
r  rP   c                 C   s.   | sg S t | |}|r|dkr|S t||| S )a  Tokenize an argument into a list.

  Deliminators that are inside json will not be split. Even when the
  json is nested, we will not split on the delimitor until we reach the
  json's closing bracket. For example:

    '{"a": [1, 2], "b": 3},{"c": 4}'

  with default delim (',') will be split only on the `,` separating the 2
  json strings i.e.

    [
        '{"a": [1, 2], "b": 3}',
        '{"c": 4}'
    ]

  This also works for strings that contain dictionary pattern. For example:

    'key1={"a": [1, 2], "b": 3},key2={"c": 4}'

  with default delim (',') will be split on the delim (',') separating the
  two strings into

    [
        'key1={"a": [1, 2], "b": 3}',
        'key2={"c": 4}'
    ]


  Args:
    arg_value: str, The raw argument.
    delim: str, The delimiter on which to split the argument string.
    includes_json: str, determines whether to ignore delimiter inside json

  Returns:
    [str], The tokenized list.
  rP   )r   r  )r   r   includes_jsonstr_listr   r   r   _TokenizeQuotedList  s   &
r  c                 C   s<   | d u rg } t |tr|D ]}t| | q| S | | | S r   )r   list_ConcatListr  )existing_values
new_values	new_valuer   r   r   r    s   

r  c                 C   s    |rt  sd| d|  S | S )zReturns a help text for universes.

  Args:
    default: str, help text for argument.
    universe_help: str, additional specific help text for Universe.

  Returns:
    [str], The help text for argument.
  zUNIVERSE INFO: 

r	   IsDefaultUniverse)defaultuniverse_helpr   r   r   UniverseHelpText  s   
r   c                   @   r   )ArgTypezBase class for arg types.Nr   r   r   r   r   r!    r   r!  c                   @   sN   e Zd ZdZ			dddZdd Zedd	 Zd
d Zdd Z	dddZ
dS )
ArgBooleanzuInterpret an argument value as a bool.

  This should only be used to define the spec of a key of an ArgDict flag.
  NFc                 C   s8   || _ |r	|| _nddg| _|r|| _d S ddg| _d S )Ntrueyesfalseno)_case_sensitive_truthy_strings_falsey_strings)r   truthy_stringsfalsey_stringscase_sensitiver   r   r   r     s   

zArgBoolean.__init__c                 C   sN   | j s| }n|}|| jv rdS || jv rdS td|d| j| j )NTFz/Invalid flag value [{0}], expected one of [{1}]r$   )r'  lowerr(  r)  r   r!   r%   )r   r   normalized_arg_valuer   r   r   __call__  s   


zArgBoolean.__call__c                 C      dS r   r   r   r   r   r   hidden     zArgBoolean.hiddenc                 C      ~|S r   r   r   is_custom_metavarmetavarr   r   r   GetUsageMetavar      zArgBoolean.GetUsageMetavarc                 C      ~dS )Nbooleanr   r   	shorthandr   r   r   GetUsageExample  r8  zArgBoolean.GetUsageExamplec                 C   
   ~~~d S r   r   r   
field_namerequired	flag_namer   r   r   GetUsageHelpText     zArgBoolean.GetUsageHelpTextNNFr   )r   r   r   r   r   r/  propertyr1  r7  r=  rC  r   r   r   r   r"    s    

r"  default_universenon_default_universereturnc                 C   s   t  r| S |S )ai  Determines if the arg is required based on the universe domain.

  Args:
    default_universe: Whether the arg is required in the default universe.
      Defaults to False.
    non_default_universe: Whether the arg is required outside of the default
      universe. Defaults to True.

  Returns:
    bool, whether the arg is required in the current universe.
  r  )rG  rH  r   r   r   ArgRequiredInUniverse  s   rJ  c                 C   s   t d| S )N^\S*\.(yaml|json)$)r~   rR   r   r   r   r   _CheckIfJSONFileFormat!  s   rM  c                 C   s
   t  | S r   )FileContentsrL  r   r   r   	_LoadFile%     
rO  c                 C   s   ddl m} || S )Nr   yaml)googlecloudsdk.corerR  load)r   rR  r   r   r   	_LoadJSON)  s   
rU  c                   @   s>   e Zd ZdZedd Zdd Zdd Zdd	d
Zdd Z	dS )ArgJSONa+  Parses inline JSON or from a file.

  This is best for recursive values like struct fields
  of when any value can be passed. ArgObject is better
  for you want a specific format from the user.
  ArgObjet helps validate if the user provided value
  is valid and generates help text with examples.
  c                 C   r0  r   r   r   r   r   r   r1  ;  r2  zArgJSON.hiddenc                 C   r3  r   r   r4  r   r   r   r7  ?  r8  zArgJSON.GetUsageMetavarc                 C   r9  )Nz{...}r   r;  r   r   r   r=  C  r8  zArgJSON.GetUsageExampleNc                 C   r>  r   r   r?  r   r   r   rC  G  rD  zArgJSON.GetUsageHelpTextc                 C   s<   t |tstd|t|rt|}t|S |}t|S )Nz4ArgJSON can only convert string values. Received {}.)r   strr   r!   rM  rO  rU  )r   r   r   r   r   r   r/  K  s   
zArgJSON.__call__r   )
r   r   r   r   rF  r1  r7  r=  rC  r/  r   r   r   r   rV  1  s    	

rV  c                   @   sb   e Zd ZdZdZdZ							dddZd	d
 ZdZe	dd Z
dd Zdd ZdddZdS )ArgLista  Interpret an argument value as a list.

  Intended to be used as the type= for a flag argument. Splits the string on
  commas or another delimiter and returns a list.

  By default, splits on commas:
      'a,b,c' -> ['a', 'b', 'c']
  There is an available syntax for using an alternate delimiter:
      '^:^a,b:c' -> ['a,b', 'c']
      '^::^a:b::c' -> ['a:b', 'c']
      '^,^^a^,b,c' -> ['^a^', ',b', 'c']
  rP   ^Nr   Fc           	         sL   _  _|p	g _ r fdd}|_ |_|_|_|_dS )a  Initialize an ArgList.

    Args:
      element_type: (str)->str, A function to apply to each of the list items.
      min_length: int, The minimum size of the list.
      max_length: int, The maximum size of the list.
      choices: [element_type], a list of valid possibilities for elements. If
        None, then no constraints are imposed.
      custom_delim_char: char, A customized delimiter character.
      hidden_choices: [element_type], a subset of choices that should be hidden
        from documentation.
      includes_json: bool, whether the list contains any json

    Returns:
      (str)->[str], A function to parse the list of values in the argument.

    Raises:
      ArgumentTypeError: If the list is malformed.
    c                    sD   r| }n| }| vr t dj|dfdd D d|S )Nz"{value} must be one of [{choices}]r$   c                    s   g | ]}| j vrt|qS r   )hidden_choicesrW  )rQ   rg   r   r   r   rU     s    z8ArgList.__init__.<locals>.ChoiceType.<locals>.<listcomp>)rm   choices)r   r!   r%   )	raw_valuetyped_valuer[  element_typer   r   r   
ChoiceType  s   
z$ArgList.__init__.<locals>.ChoiceTypeN)r_  r[  rZ  
min_length
max_lengthcustom_delim_charr  )	r   r_  ra  rb  r[  rc  rZ  r  r`  r   r^  r   r   k  s   

zArgList.__init__c                    s   t |tr|}nAt |tjstdt|j| jp j	}|
 jrA j|dd  v rA|dd   jd\}}|sAtdt|| jd}t| jk rTtd jd urdt| jkrdtd jrp fdd|D }|S )	N%Invalid type [{}] for flag value [{}]r(   zInvalid delimeter. Please see `gcloud topic flags-file` or `gcloud topic escaping` for information on providing list or dictionary flag values with special characters.)r   r  znot enough argsztoo many argsc                    s   g | ]}  |qS r   )r_  )rQ   argr   r   r   rU     s    z$ArgList.__call__.<locals>.<listcomp>)r   r  ru   string_typesr   r!   typer   rc  DEFAULT_DELIM_CHAR
startswithALT_DELIM_CHARr   r  r  rX   ra  rb  r_  )r   r   arg_listr   r   r   r   r/    s0   

zArgList.__call__   c                 C   r0  r   r   r   r   r   r   r1    r2  zArgList.hiddenc                 C   s   ~| j p| j}||g| j }| jr| j| j }nd}|dkr#d}n|dkr-d|}n|dkr8d||}nd||}|d	d
 ||fD }t|| jk rS|S | jdkr^d||S | jdkrid||S d||S )a  Get a specially-formatted metavar for the ArgList to use in help.

    An example is worth 1,000 words:

    >>> ArgList().GetUsageMetavar('FOO')
    '[FOO,...]'
    >>> ArgList(min_length=1).GetUsageMetavar('FOO')
    'FOO,[FOO,...]'
    >>> ArgList(max_length=2).GetUsageMetavar('FOO')
    'FOO,[FOO]'
    >>> ArgList(max_length=3).GetUsageMetavar('FOO')  # One, two, many...
    'FOO,[FOO,...]'
    >>> ArgList(min_length=2, max_length=2).GetUsageMetavar('FOO')
    'FOO,FOO'
    >>> ArgList().GetUsageMetavar('REALLY_VERY_QUITE_LONG_METAVAR')
    'REALLY_VERY_QUITE_LONG_METAVAR,[...]'

    Args:
      is_custom_metavar: unused in GetUsageMetavar
      metavar: string, the base metavar to turn into an ArgList metavar

    Returns:
      string, the ArgList usage metavar
    Nr   r0   r(   z[{}]   z[{0}{1}[{0}]]z	[{}{}...]c                 S   s   g | ]}|r|qS r   r   )rQ   xr   r   r   rU     rV   z+ArgList.GetUsageMetavar.<locals>.<listcomp>z	{}{}[...]z{0}{1}...{1}[...])rc  rh  r%   ra  rb  r!   rX   _MAX_METAVAR_LENGTH)r   r5  r6  
delim_charrA  num_optionaloptionalmsgr   r   r   r7    s*   

zArgList.GetUsageMetavarc                 C   s   ~d S r   r   r;  r   r   r   r=    r8  zArgList.GetUsageExamplec                 C   r>  r   r   r?  r   r   r   rC    rD  zArgList.GetUsageHelpText)Nr   NNNNFr   )r   r   r   r   rh  rj  r   r/  ro  rF  r1  r7  r=  rC  r   r   r   r   rX  Z  s&    
5
:rX  rm   charc                 C   s0   |  |r| dd } | |r| dd } | S )z4Trims characters from the start and end of a string.r(   Nr   )ri  r   )rm   rt  r   r   r   _TrimCharacter  s
   

ru  c                       s   e Zd ZdZ										d fdd	Zdd Zd	d
 ZdddZdddZdd Z	 fddZ
edd Z fddZdd ZdddZ  ZS )ArgDictzInterpret an argument value as a dict.

  Intended to be used as the type= for a flag argument. Splits the string on
  commas to get a list, and then splits the items on equals to get a set of
  key-value pairs to get a dict.
  Nr   Fc                    s   t t| j|||	d |r|rtd|| _|| _|| _|| _|p"g | _|
| _	|s-d|i}|
 D ]}t|dkr@td|q1dt|}djt|d}t|tj| _|| _d	S )
a6  Initialize an ArgDict.

    Args:
      key_type: (str)->str, A function to apply to each of the dict keys.
      value_type: (str)->str, A function to apply to each of the dict values.
      spec: {str: (str)->str}, A mapping of expected keys to functions. The
        functions are applied to the values. If None, an arbitrary set of keys
        will be accepted. If not None, it is an error for the user to supply a
        key that is not in the spec. If the function specified is None, then
        accept a key only without '=value'.
      min_length: int, The minimum number of keys in the dict.
      max_length: int, The maximum number of keys in the dict.
      allow_key_only: bool, Allow empty values.
      required_keys: [str], Required keys in the dict.
      operators: operator_char -> value_type, Define multiple single character
        operators, each with its own value_type converter. Use value_type==None
        for no conversion. The default value is {'=': value_type}
      includes_json: bool, whether string parsed includes json
      cleanup_input: bool, whether to clean up the input string

    Returns:
      (str)->{str:str}, A function to parse the dict in the argument.

    Raises:
      ArgumentTypeError: If the list is malformed.
      ValueError: If both value_type and spec are provided.
    )ra  rb  r  z"cannot have both spec and sub_typer   r(   z$Operator [{}] must be one character.r0   z([^{ops}]+)([{ops}]?)(.*))opsN)superrv  r   r   key_type
value_typespecallow_key_onlyrequired_keyscleanup_inputkeysrX   r   r!   r%   ru   iterkeysr~   escapecompileDOTALLkey_op_value	operators)r   ry  rz  r{  ra  rb  r|  r}  r  r  r~  oprw  key_op_value_pattern	__class__r   r   r     s4   
&

zArgDict.__init__c              	   C   sb   || j v r| j | d u r|rtd|d S | j | |S ttddt| j  |d)NzKey [{0}] does not take a valuezvalid keys are [{0}]r$   rz   )r{  r   r!   r#   r%   rt   r  r   ro   rm   r   r   r   
_ApplySpecU  s   

zArgDict._ApplySpecc                 C   s*   |r
| j r
t|ts|S | }t|dS )N")r~  r   rW  stripru  )r   rm   removed_spacer   r   r   _CleanupInputc  s   
zArgDict._CleanupInputr   c                 C   s   |r|du r| j std|| jr)z| |}W n ty(   td|w | j r4| jdd}nd}| j||}|rTz||}W n tyS   td|w | jdur_| ||}||fS );Converts and validates <key,value> and returns (key,value).NzBad syntax for dict arg: [{0}]. Please see `gcloud topic flags-file` or `gcloud topic escaping` for information on providing list or dictionary flag values with special characters.zInvalid key [{0}]r   zInvalid value [{0}])	r|  r   r!   ry  r   r  rj   r{  r  )r   ro   rm   r  default_convertconvert_valuer   r   r   _ValidateKeyValuej  s0   
zArgDict._ValidateKeyValuec                 C   s&   |  ||  |}}| j|||dS )r  r  )r  r  )r   ro   rm   r  r{   r|   r   r   r   _CleanupAndValidateKeyValue  s   z#ArgDict._CleanupAndValidateKeyValuec                 C   s&   | j D ]}||vrtd|qd S )Nz/Key [{0}] required in dict arg but not provided)r}  r   r!   )r   arg_dictrequired_keyr   r   r   _CheckRequiredKeys  s   
zArgDict._CheckRequiredKeysc           
         s   t |tr"|}t }t|D ]\}}| ||\}}|||< qnPt |tjs3td	t
|j|tt| |}t }|D ]0}| j|}|sRtd	||d|d|d}}	}| j|||	d\}}|||< qA| | |S )Nrd  zInvalid flag value [{0}]r(   rm  r   r  )r   r   collectionsOrderedDictru   rv   r  rf  r   r!   rg  r   rx  rv  r/  r  rR   r   r  )
r   r   raw_dictr  ro   rm   rk  re  rR   r  r  r   r   r/    s,   


"

zArgDict.__call__c                 C   r0  r   r   r   r   r   r   r1    r2  zArgDict.hiddenc                    s   | j r|rtt| ||S g }tt| j }|D ]\}}|d u r1| js,td	||
| q|D ]\}}|rJt|sJ|
d	||  q4dd| d }|S )NzQKey [{0}] specified in spec without a function but allow_key_only is set to Falsez{0}={1}r   z],[r   )r{  rx  rv  r7  rt   ru   rv   r|  r   r!   r  
usage_textIsHiddenrb   r%   )r   r5  r6  msg_list	spec_listspec_keyspec_functionrs  r  r   r   r7    s&   

zArgDict.GetUsageMetavarc                 C   sT   ~| j rddd t| j  D S | jr| j}n| jpt}tj| j	p%t|ddS )a  Returns a string of usage examples.

    Generates an example of expected user input.
    For example, an ArgDict with spec={'x': int, 'y': str} will generate

      x=int,y=string

    An ArgDict with key_type=str and value_type=str will generate

      string=string

    Args:
      shorthand: unused bool, whether to display in shorthand (ArgDict is
        always parsed as shorthand)

    Returns:
      str, example text of usage
    rP   c                 s   s$    | ]\}}t j||d dV  qdS )Tr<  Nr  GetNestedKeyValueExamplerQ   ro   rm   r   r   r   	<genexpr>  s
    
z*ArgDict.GetUsageExample.<locals>.<genexpr>T)ry  rz  r<  )
r{  r%   rt   r   r|  rz  rW  r  r  ry  )r   r<  rz  r   r   r   r=    s   

zArgDict.GetUsageExamplec                 C   r>  r   r   r?  r   r   r   rC    rD  zArgDict.GetUsageHelpText)
NNNr   NFNNFF)r   r   )r   r   r   r   r   r  r  r  r  r  r/  rF  r1  r7  r=  rC  __classcell__r   r   r  r   rv    s0    =


'rv  c                       s   e Zd ZdZdZdd Zdd Z							d4 fd
d	Zedd Z	dd Z
dd Zdd Zdd Zdd Zdd Z fddZdd Zdd Z fd d!Zd"d# Zd$d% Zed&d' Z fd(d)Zd*d+ Zd,d- Zd.d/ Zd0d1 Zd5d2d3Z  ZS )6	ArgObjecta	  Catch all arg type that will accept a file, json, or ArgDict.

  ArgObject is very similar to ArgDict with some extra functionality. ArgObject
  will first try to parse a value as an arg_dict if string contains '='. The
  type will then try to parse string as a file if string contains
  .yaml or .json. Finally, parser will parse the string as json.

  I. For example, with the following flag defintion:

    parser.add_argument(
        '--inputs',
        type=arg_parsers.ArgObject(key_type=str, value_type=int))

  a caller can retrieve {"foo": 100} by specifying any of the following
  on the command line.

    (1) --inputs=foo=100
    (2) --inputs='{"foo": 100}'
    (3) --inputs=path_to_json.(json|yaml)

  II. If we need the type return a list of messages, use the repeated arg.
  NOTE: when using repeated values, it is recommended to specify the
  action as arg_parsers.FlattenAction()

  For example, with the following flag defintion:

    parser.add_argument(
        '--inputs',
        type=arg_parsers.ArgObject(key_type=str, value_type=int),
        action=arg_parsers.FlattenAction()
        repeated=True)

  a caller can retrieve [{"foo": 1, "bar": 2}, {"bax": 3}] by specifying any
  of the following on the command line.

    (1) --inputs=foo=1,bar=2 --inputs=bax=3
    (2) --inputs='[{"foo": 1, "bar": 2}, {"bax": 3}]'
    (3) --inputs=path_to_json.(json|yaml)

  III. If we need to parse non key-value pairs, do not provide key_type or spec.
  For example, with the following flag defintion:

    parser.add_argument(
        '--inputs',
        type=arg_parsers.ArgObject(value_type=int))

  a caller can retrieve 100 by specifying the following
  on the command line.

    (1) --inputs=100
    (2) --inputs=path_to_json.(json|yaml)

  IV. If we need to create nested objects, set value_type to another ArgObject
  type. ArgDict syntax is automatically disabled for the nested ArgObject type
  with enable_shorthand=False

  For example, with the following flag defintion:

    parser.add_argument(
        '--inputs',
        type=arg_parsers.ArgObject(
            key_type=str,
            value_type=arg_parsers.ArgObject(
                key_type=str, value_type=int, enable_shorthand=False)))

  a caller can retrieve {"foo": {"bar": 1}} by specifying any
  of the following on the command line.

    (1) --inputs='foo={bar=1}'
    (2) --inputs='{"foo": {"bar": 1}}'
    (3) --inputs=path_to_json.(json|yaml)
  rK  c                 C   s   t |tr
d|_d S d S r   )r   r  
root_level)r   arg_typer   r   r   _UpdateAsNestedC  s   

zArgObject._UpdateAsNestedc                 C   s   |t krt S |S r   )boolr"  )r   rz  r   r   r   _JSONValueTypeG  s   zArgObject._JSONValueTypeNFTc              	      s   |r  | n|r| D ]}  | q|o" fdd| D }tt j| |||dd|d | _| _|d upB|d u _	| _
| _|	 _|
 _| _ jra j	sctd jd S d S )Nc                    s   i | ]
\}}|  |qS r   )r  r  r   r   r   
<dictcomp>^  r}   z&ArgObject.__init__.<locals>.<dictcomp>T)ry  rz  r{  r}  r  r~  r|  zArgObject type listed required keys as {}. Keys can only be listed as required if `spec` or `key_type` arguments are provided to the ArgObject type.)r  r  r   rx  r  r   r  	help_textrepeated_keyed_values_hiddenenable_shorthandenable_file_upload_disable_key_descriptionr  r}  r   r!   )r   ry  rz  r{  r}  r  r  r1  r  r  disable_key_descriptionr  r|  rm   	spec_typer  r   r   r   P  s6   

zArgObject.__init__c                 C   s   | j o| jS r   )r  r  r   r   r   r   parse_as_arg_dicts  s   zArgObject.parse_as_arg_dictc                 C   s   t |tr| jrg }|D ]}| ||}|| q|S t |tr>| jr>t }|	 D ]\}}|||\}}|||< q,|S |d|\}}|S )aq  Applies callback for arg_value.

    Arg_value can be a dictionary, list, or other value.

    Args:
      arg_value: can be a dictionary, list, or other value,
      callback: (key, val) -> key, val, function that accepts key and value
        and returns transformed values.

    Returns:
      dictionary, list, or value with callback operation performed on it.
    N)
r   r  r  _Mapr  r   r  r  r  r   )r   r   callbackrk  rm   r  ro   rq   r   r   r   r  w  s   
zArgObject._Mapc                 C   sZ   |du r| j rtd||durt|tst|}|dur)t|ts)t|}||fS )z$Returns string version of arguments.Nz*Expecting {} to be json or arg_dict format)r  r   r!   r   rW  jsondumpsr  r   r   r   _StringifyValues  s   
zArgObject._StringifyValuesc                 C   s   |  || jS r   )r  r  r   r   r   r   r   _StringifyDictValues  s   zArgObject._StringifyDictValuesc                 C   s   | j ot|S r   )r  rM  r  r   r   r   _CheckIfFileFormat  s   zArgObject._CheckIfFileFormatc                 C   s|   ddl m} z,||}t|tr|r| }n|}t|ts"W dS tdd | D r0W dS W dS  |j	y=   Y dS w )z5Checks if arg_value can be loaded into a json object.r   rQ  Fc                 s   s    | ]}|d u V  qd S r   r   rQ   valr   r   r   r    s    z/ArgObject._CheckIfJSONObject.<locals>.<genexpr>T)
rS  rR  rT  r   r  r  r   allr  YAMLParseError)r   r   rR  parsed_json	json_dictr   r   r   _CheckIfJSONObject  s   


zArgObject._CheckIfJSONObjectc                 C   s$   | j s| jrt|}n|}| |S )zLoads json string or file into a dictionary.

    Args:
      arg_value: str, path to a json or yaml file or json string

    Returns:
      Dictionary [str: str] where the value is a json string or other String
        value
    )r  r  rU  r  )r   r   
json_valuer   r   r   rU    s   


zArgObject._LoadJSONc                    s<   t |tr|D ]
}tt| | qd S tt| | d S r   )r   r  rx  r  r  )r   r  rm   r  r   r   r    s
   
zArgObject._CheckRequiredKeysc                 C   s"   |  || j}| jr| | |S r   )r  r  r}  r  )r   r   r  r   r   r   _ParseAndValidateJSON  s   
zArgObject._ParseAndValidateJSONc                 C   s*   d | j }td| d|p| jS )N|())r%   r  r  r~   searchr|  )r   r   rw  r   r   r   _ContainsArgDict  s   zArgObject._ContainsArgDictc                    s~   |  }|dr$|dr$ jr$t|dd dd} fdd|D S |d	r5|d
r5|dd }n|}tt |S )Nr   r   r(   r   T)r  c                    s   g | ]	}  | qS r   )_ParseArgDictr  r  r   r   r   rU     s    z+ArgObject._ParseArgDict.<locals>.<listcomp>r   r   )r  ri  r   r  r  rx  r  r/  )r   r   stripped_valuer  arg_dict_strr  r   r   r    s   zArgObject._ParseArgDictc                 C   s,   | j sdS d}||kp| |o| | S )NFr0   )r  r  r  )r   r   empty_obj_shorthandr   r   r   _CheckIfArgDictFormat  s   

zArgObject._CheckIfArgDictFormatc                 C   s   t |tstd|| |r t|}| |}| |}n| |r+| 	|}n
| |}| |}| j
r@t |ts@|g}|S )Nz6ArgObject can only convert string values. Received {}.)r   rW  r   r!   r  rO  rU  r  r  r  r  r  )r   r   file_contentr  rm   r   r   r   r/    s"   





zArgObject.__call__c                 C   sF   | j d ur| j S | jrtdd | j D S t| jp"t| jS )Nc                 s   s    | ]}t |V  qd S r   )r  r  )rQ   rm   r   r   r   r    s    z#ArgObject.hidden.<locals>.<genexpr>)r  r{  r  r  r  r  ry  rz  r   r   r   r   r1    s   

zArgObject.hiddenc                    s   | j rtt| ||S |S r   )r  rx  r  r7  r4  r  r   r   r7     s   zArgObject.GetUsageMetavarc           	         s   | j rdS |o	| j}| j}| j}|p| p| | jdur; r dnd} fddt| j D }|dd |D }nt	| j
| jpCt }| pL| j }|rW|rWd| d }|ra|rad	| d
 }|S )az  Returns a string of usage examples.

    Recursively generates an example of expected user input.
    For example, an ArgObject with spec={'x': int, 'y': str} will generate...

      x=int,y=string (shorthand) and
      {"x": int, "y": "string"} (json)

    An ArgObject with key_type=str and value_type=str will generate...

      string=string (shorthand) and
      {"string": "string"} (json)

    An ArgObject with value_type=str will always generate...

      string (shorthand and json)

    Args:
      shorthand: bool, whether to display in shorthand

    Returns:
      str | None, example text of usage. None if hidden.
    NrP   r$   c                 3   s"    | ]\}}t || V  qd S r   r  r  format_as_shorthandr   r   r  K  s
    
z,ArgObject.GetUsageExample.<locals>.<genexpr>c                 s       | ]	}|d ur|V  qd S r   r   rQ   liner   r   r   r  N      r   r   r   r   )r1  r  r  r  r{  rt   r   r%   r  r  ry  rz  rW  r  )	r   r<  shorthand_enabledis_json_objis_arraycommaexampleusageinclude_bracketsr   r  r   r=  &  s*   


zArgObject.GetUsageExamplec                 C   s   | j dd}| js| jrd}| d| }n| j}|}tj|||d}tj|| j ddd}tj|dd}||kr?d||S d	|||S )
z(Returns a string of user input examples.Tr  FrP   )arg_namer   r  )r  r   zpath_to_file.(yaml|json)z)*Input Example:*

{}

*File Example:*

{}zB*Shorthand Example:*

{}

*JSON Example:*

{}

*File Example:*

{})r=  r  r  r  FormatCodeSnippetr!   )r   rB  shorthand_snippetr  snippetshorthand_examplejson_examplefile_exampler   r   r   _GetCodeExamples]  s4   zArgObject._GetCodeExamplesc                 C   s^   t j||| jd}| js| jst| jt jr| j||}nd}|r-||kr-| d| S |S )+Returns a string of help text for the flag.)r  N )	r  FormatHelpTextr  r{  ry  r   rz  ArgTypeUsagerC  )r   r@  rA  root_help_textadditional_help_textr   r   r   _FormatRootHelpText~  s   zArgObject._FormatRootHelpTextc                    sj   g } j r fddt j  D }|| |S  jr3|td j |td jp0t	 |S )r  c                 3   s(    | ]\}}t ||| jv V  qd S r   )r  GetNestedUsageHelpTextr}  )rQ   ro   r  r   r   r   r    s
    
z6ArgObject._GetKeyValueUsageHelpText.<locals>.<genexpr>KEYVALUE)
r{  rt   r   extendry  r  r  r  rz  rW  )r   r  r   r   r   r   _GetKeyValueUsageHelpText  s   


z#ArgObject._GetKeyValueUsageHelpTextc                 C   sb   | j rdS g }|| || | js||   |r'|tj| |  d	dd |D S )a9  Returns a string of usage help text.

    Recursively generates usage help text to provide the user with
    more information on valid flag values and the general schema.
    For example, ArgObject with...

      spec={
          'x': int,
          'y': arg_parsers.ArgObject(help_text='Y help.', spec={'z': str}),
      }

    will generate the following by default...

      ```
      *x*
        Sets `z` value.

      *y*
        Y help.

        *z*
          Sets `z` value.
      ```

    Args:
      field_name: str | None, field the flag of this type is setting
      required: bool, whether the flag of this type is required
      flag_name: str | None, the name of the flag. If not none, will generate
        code examples.

    Returns:
      str | None, help text with schema and examples. None if hidden.
    Nr  c                 s   r  r   r   r  r   r   r   r    r  z-ArgObject.GetUsageHelpText.<locals>.<genexpr>)
r1  r  r  r  r  r  r  ASCII_INDENTr  r%   )r   r@  rA  rB  r  r   r   r   rC    s   "zArgObject.GetUsageHelpText)NNNNNFNTTFTFr   )r   r   r   r   _file_path_patternr  r  r   rF  r  r  r  r  r  r  rU  r  r  r  r  r  r/  r1  r7  r=  r  r  r  rC  r  r   r   r  r   r    sB    H	#


	7!r  c                	       sP   e Zd ZdZdddZddddddddef	 fdd	Zdd	 Zdd
dZ  ZS )UpdateActiona=  Create a single dict value from delimited or repeated flags.

  This class is intended to be a more flexible version of
  argparse._AppendAction.

  For example, with the following flag definition:

      parser.add_argument(
        '--inputs',
        type=arg_parsers.ArgDict(),
        action='append')

  a caller can specify on the command line flags such as:

    --inputs k1=v1,k2=v2

  and the result will be a list of one dict:

    [{ 'k1': 'v1', 'k2': 'v2' }]

  Specifying two separate command line flags such as:

    --inputs k1=v1 \
    --inputs k2=v2

  will produce a list of dicts:

    [{ 'k1': 'v1'}, { 'k2': 'v2' }]

  The UpdateAction class allows for both of the above user inputs to result
  in the same: a single dictionary:

    { 'k1': 'v1', 'k2': 'v2' }

  This gives end-users a lot more flexibility in constructing their command
  lines, especially when scripting calls.

  Note that this class will raise an exception if a key value is specified
  more than once. To allow for a key value to be specified multiple times,
  use UpdateActionWithAppend.
  Nc                 C   sB   |d u rd }nd t|t|g}t| td||d)Nr$   z("{0}" cannot be specified multiple timesrz   )r%   ru   r   argparseArgumentErrorr#   r!   )r   ro   existing_valuer  r   r   r   r   OnDuplicateKeyRaiseError  s   z%UpdateAction.OnDuplicateKeyRaiseErrorFc                    sz   |dkrt d|d ur|tjkrt dtj || _t|tr&t| }tt	| j
|||||||||	|
d
 || _d S )Nr   znargs for append actions must be > 0; if arg strings are not supplying the value to append, the append const action may be more appropriatez nargs must be %r to supply const)
option_stringsdestnargsconstr  rg  r[  rA  helpr6  )r   r  OPTIONALr[  r   r   rt   r  rx  r  r   onduplicatekey_handlerr   r  r  r  r   r  rg  r[  rA  r  r6  r  r  r   r   r     s(   


zUpdateAction.__init__c                 C   s&   t ||d d u rt||| t ||S r   )getattrsetattr)r   	namespacenamerm   r   r   r   _EnsureValue6  s   
zUpdateAction._EnsureValuec                 C   s   t |tr/t| || jt }t|D ]\}}||v r)| 	| ||| |}|||< qn t| || jg }|D ]}||v rI| 	| | q<|
| q<t|| j| d S r   )r   r   copyr	  r  r  r  ru   rv   r  r  r  )r   r   r  r  option_stringr   r{   r|   r   r   r   r/  <  s   

zUpdateAction.__call__NNr   )	r   r   r   r   r  r   r	  r/  r  r   r   r  r   r    s    
*#r  c                	       s>   e Zd ZdZdddZddddddddef	 fdd	Z  ZS )	UpdateActionWithAppenda^  Create a single dict value from delimited or repeated flags.

  This class provides a variant of UpdateAction, which allows for users to
  append, rather than reject, duplicate key values. For example, the user
  can specify:

    --inputs k1=v1a --inputs k1=v1b --inputs k2=v2

  and the result will be:

     { 'k1': ['v1a', 'v1b'], 'k2': 'v2' }
  Nc                 C   s(   |d u r|S t |tr||g S ||gS r   )r   r  )r   ro   r  r  r   r   r   OnDuplicateKeyAppendc  s
   

z+UpdateActionWithAppend.OnDuplicateKeyAppendFc                    s*   t t| j|||||||||	|
|d d S )N)r  r  r  r   r  rg  r[  rA  r  r6  r  )rx  r  r   r  r  r   r   r   k  s   

zUpdateActionWithAppend.__init__r  )r   r   r   r   r  r   r  r   r   r  r   r  U  s    
r  c                       s8   e Zd ZdZ fddZdd Zdd Zdd	 Z  ZS )
RemainderActiona0  An action with a couple of helpers to better handle --.

  argparse on its own does not properly handle -- implementation args.
  argparse.REMAINDER greedily steals valid flags before a --, and nargs='*' will
  bind to [] and not  parse args after --. This Action represents arguments to
  be passed through to a subcommand after --.

  Primarily, this Action provides two utility parsers to help a modified
  ArgumentParser parse -- properly.

  There is one additional property kwarg:
    example: A usage statement used to construct nice additional help.
  c                    s   |d t jurtddj|d d| _d|v r6|d  d| j 7  < d|v r6|d  d	|d  7  < |d= tt| j|i | d S )
Nr  zFThe RemainderAction should only be used when nargs=argparse.REMAINDER.zhThe '--' argument must be specified between gcloud specific args on the left and {metavar} on the right.r6  )r6  r  z
+
r  z Example:

)r  	REMAINDERr   r!   explanationrx  r  r   r   r   r[   r  r   r   r     s   zRemainderAction.__init__c                 C   s&   | d}|d | ||d d  fS )N--r(   )index)r   r   split_indexr   r   r   _SplitOnDash  s   
zRemainderAction._SplitOnDashc                 C   s.   d}d|v r|  |\}}| d|| ||fS )z)Binds all args after -- to the namespace.Nr  )r  )r   r   r  remainder_argsr   r   r   ParseKnownArgs  s
   zRemainderAction.ParseKnownArgsc                 C   s   d|v r|  |\}}d}ttt|t|D ]\}\}}||kr*t|| } nq||d }	|d| }|	rJd| j jd|	d}
t	|
| d||	 ||fS )a  Parses the unrecognized args from the end of the remaining_args.

    This method identifies all unrecognized arguments after the last argument
    recognized by a parser (but before --). It then either logs a warning and
    binds them to the namespace or raises an error, depending on strictness.

    Args:
      remaining_args: A list of arguments that the parsers did not recognize.
      namespace: The Namespace to bind to.
      original_args: The full list of arguments given to the top parser,

    Raises:
      ArgumentError: If there were remaining arguments after the last recognized
      argument and this action is strict.

    Returns:
      A tuple of the updated namespace and unrecognized arguments (before the
      last recognized argument).
    r  r   Nzunrecognized args: {args}
r  )r   )
r  	enumerater   rc   rX   r  r!   r%   r   UnrecognizedArgumentsError)r   remaining_argsr  original_argsrq   r  rf   arg1arg2pass_through_argsrs  r   r   r   ParseRemainingArgs  s*   

z"RemainderAction.ParseRemainingArgs)	r   r   r   r   r   r  r  r   r  r   r   r  r   r    s    
r  c                    s   G  fdddt j}|S )zCreates an action that concats flag values.

  Args:
    dedup: bool, determines whether values in generated list should be unique

  Returns:
    A custom argparse action that flattens the values before adding
    to namespace
  c                       s   e Zd ZdZd fdd	ZdS )zFlattenAction.<locals>.Actiona2  Create a single list from delimited flags.

    For example, with the following flag defition:

        parser.add_argument(
            '--inputs',
            type=arg_parsers.ArgObject(repeated=True),
            action=FlattenAction(dedup=True))

    a caller can specify on the command line flags such as:

        --inputs '["v1", "v2"]' --inputs '["v3", "v4"]'

    and the result will be one list of non-repeating values:

        ["v1", "v2", "v3", "v4"]

    Recommend using this action with ArgObject where `repeated` is set to True.
    This allows users to set the list either with append action or with
    one json list. For example, all below examples result
    in ["v1", "v2", "v3", "v4"]

        1) --inputs v1 --inputs v2 --inputs v3 --inputs v4
        2) --inputs '["v1", "v2", "v3", "v4"]'
    Nc           	         sR   t || jd }t||} r g }|D ]}||vr|| q|}t|| j| d S r   )r  r  r  r  r  )	r   r   r  r  r  r  
all_valuesdeduped_valuesrm   dedupr   r   r/  	  s   

z&FlattenAction.<locals>.Action.__call__r   )r   r   r   r   r/  r   r#  r   r   Action  s    r%  r  r%  )r$  r%  r   r#  r   FlattenAction  s   'r'  c                       s2   e Zd ZdZdd Z fddZd	ddZ  ZS )
StoreOnceActiona  Action that disallows repeating a flag.

  When using action='store' (the default), argparse allows multiple instances of
  a flag to be specified with the last one determining the value and the rest
  silently dropped. This is often undesirable if the command accepts only one
  value but users try to repeat the flag (either accidentally, or when
  mistakenly expecting the repeated values to be appended or merged somehow).

  In such cases, one can instead use StoreOnceAction which disallows specifying
  the same flag multiple times. So for instance, providing:

    --foo 123 --foo 456

  will result in an error stating that --foo cannot be specified more than once.
  c                 C   s   t | td| j)Nz1"{0}" argument cannot be specified multiple times)r  r  r#   r!   r  r   r   r   r   OnSecondArgumentRaiseError%	  s   z*StoreOnceAction.OnSecondArgumentRaiseErrorc                    s    d| _ tt| j|i | d S r   )dest_is_populatedrx  r(  r   r  r  r   r   r   ,	     zStoreOnceAction.__init__Nc                 C   &   | j r|   d| _ t|| j| d S NT)r*  r)  r  r  r   r   r  r  r  r   r   r   r/  1	     zStoreOnceAction.__call__r   )r   r   r   r   r)  r   r/  r  r   r   r  r   r(  	  s
    r(  c                       G  fdddt j  S )a  Emits a warning message when a flag is specified more than once.

  The created action is similar to StoreOnceAction. The difference is that
  this action prints a warning message instead of raising an exception when the
  flag is specified more than once. Because it is a breaking change to switch an
  existing flag to StoreOnceAction, StoreOnceWarningAction can be used in the
  deprecation period.

  Args:
    flag_name: The name of the flag to apply this action on.

  Returns:
    An Action class.
  c                       s8   e Zd ZdZfddZ fddZd	ddZ  ZS )
z&StoreOnceWarningAction.<locals>.Actionz@Emits a warning message when a flag is specified more than once.c                    s   t d  d S )Nzt"{0}" argument is specified multiple times which will be disallowed in future versions. Please only specify it once.)r   warningr!   r   rB  r   r   OnSecondArgumentPrintWarningL	  s   zCStoreOnceWarningAction.<locals>.Action.OnSecondArgumentPrintWarningc                    s    d| _ t | j|i | d S r   )r*  rx  r   r  r%  r  r   r   r   Q	  r+  z/StoreOnceWarningAction.<locals>.Action.__init__Nc                 S   r,  r-  )r*  r3  r  r  r.  r   r   r   r/  U	  r/  z/StoreOnceWarningAction.<locals>.Action.__call__r   )r   r   r   r   r3  r   r/  r  r   r%  rB  r  r   r%  I	  s
    r%  r&  r2  r   r5  r   StoreOnceWarningAction9	  s   r6  c                       *   e Zd ZdZ fddZdddZ  ZS )_HandleNoArgActionzFThis class should not be used directly, use HandleNoArgAction instead.c                    s&   t t| jdi | || _|| _d S )Nr   )rx  r8  r   none_argdeprecation_message)r   r9  r:  r[   r  r   r   r   b	  s   
z_HandleNoArgAction.__init__Nc                 C   s:   |d u rt | j | jrt|| jd t|| j| d S r-  )r   r1  r:  r9  r  r  )r   r   r  rm   r  r   r   r   r/  g	  s
   z_HandleNoArgAction.__call__r   r   r   r   r   r   r/  r  r   r   r  r   r8  _	  s    r8  c                    r   )a  Creates an argparse.Action that warns when called with no arguments.

  This function creates an argparse action which can be used to gracefully
  deprecate a flag using nargs=?. When a flag is created with this action, it
  simply log.warning()s the given deprecation_message and then sets the value of
  the none_arg to True.

  This means if you use the none_arg no_foo and attach this action to foo,
  `--foo` (no argument), it will have the same effect as `--no-foo`.

  Args:
    none_arg: a boolean argument to write to. For --no-foo use "no_foo"
    deprecation_message: msg to tell user to stop using with no arguments.

  Returns:
    An argparse action.

  c                     s   t  fi | S r   )r8  )r[   r:  r9  r   r   HandleNoArgActionInit	  s   z0HandleNoArgAction.<locals>.HandleNoArgActionInitr   )r9  r:  r=  r   r<  r   HandleNoArgActionp	  s   r>  c                   @   sH   e Zd ZdZdddZedd Zdd Zd	d
 ZdddZ	dd Z
dS )rN  af  Creates an argparse type that reads the contents of a file or stdin.

  This is similar to argparse.FileType, but unlike FileType it does not leave
  a dangling file handle open. The argument stored in the argparse Namespace
  is the file's contents.

  Attributes:
    binary: bool, If True, the contents of the file will be returned as bytes.
    default_help_text_disabled: bool, If True, the autogenerated help text will
      include additional information about how to use this file flag type.

  Returns:
    A function that accepts a filename, or "-" representing that stdin should be
    used as input.
  Fc                 C   r   r   )binarydefault_help_text_disabled)r   r?  r@  r   r   r   r   	  r   zFileContents.__init__c                 C   r0  r   r   r   r   r   r   r1  	  r2  zFileContents.hiddenc                 C   s   |s| j sdS |S )a  Provides a more user friendly metavar for file contents.

    `PATH_TO_FILE` is used as the default metavar for file contents flags only
    when (1) a custom metavar is not provided and (2) the default help text is
    enabled.

    Args:
      is_custom_metavar: bool, True if the user provided a custom metavar.
      metavar: str, the metavar to use if a custom metavar was not provided.
    Returns:
      The metavar to use for this file contents flag.
    PATH_TO_FILE)r@  r4  r   r   r   r7  	  s   
zFileContents.GetUsageMetavarc                 C   r9  )aV  Generates a usage example for file contents flags.

    This default usage example is used to generate example input values.
    This is currently just used to generate ArgObject help text examples.

    Args:
      shorthand: bool, unused for file contents flags.

    Returns:
      The example input value for this file contents flag.
    path_to_filer   r;  r   r   r   r=  	  s   zFileContents.GetUsageExampleNc                 C   s(   ~~| j stdd|}d| dS dS )a  Autogenerates additional help text for file contents flags.

    Additional help text is only added when the default help text is enabled.

    Args:
      field_name: str, the name of the field this flag is associated with.
      required: bool, True if this flag is required.
      flag_name: str, the name of the flag this help text is associated with.

    Returns:
      Additional help text for this file contents flag.
    z_from_file$r0   zDUse a full or relative path to a local file containing the value of r   N)r@  r~   sub)r   r@  rA  rB  sub_field_namer   r   r   rC  	  s   zFileContents.GetUsageHelpTextc              
   C   s6   z	t j|| jdW S  tjy } zt|d}~ww )aS  Return the contents of the file with the specified name.

    If name is "-", stdin is read until EOF. Otherwise, the named file is read.

    Args:
      name: str, The file name, or '-' to indicate stdin.

    Returns:
      The contents of the file.

    Raises:
      ArgumentTypeError: If the file cannot be read or is too large.
    r?  N)r   ReadFromFileOrStdinr?  r   r   r   r   r  r   r   r   r   r/  	  s   zFileContents.__call__)FFr   )r   r   r   r   r   rF  r1  r7  r=  rC  r/  r   r   r   r   rN  	  s    


rN  c                   @   s2   e Zd ZdZdddZdd Zdd Zd	d
 ZdS )YAMLFileContentsa  Creates an argparse type that reads the contents of a YAML or JSON file.

  This is similar to argparse.FileType, but unlike FileType it does not leave
  a dangling file handle open. The argument stored in the argparse Namespace
  is the file's contents parsed as a YAML object.

  Attributes:
    validator: function, Function that will validate the provided input file
      contents.

  Returns:
    A function that accepts a filename that should be parsed as a YAML
    or JSON file.
  Nc                 C   s   |r
t |s
td|| _d S )NzValidator must be callable)callabler   	validator)r   rJ  r   r   r   r   	  s   
zYAMLFileContents.__init__c                 C   s6   ddl m} ||s||std|d S d S )Nr   rQ  zInvalid YAML/JSON Data [{}])rS  rR  	dict_like	list_liker   r!   )r   	yaml_datarR  r   r   r   _AssertJSONLike
  s   z YAMLFileContents._AssertJSONLikec                 C   sp   ddl m} |dkrt }||}n||}dd |D }t|dkr*|d S |dkr3||S ||S )a  Returns the yaml data for a file or from stdin for a single document.

    YAML allows multiple documents in a single file by using `---` as a
    separator between documents. See https://yaml.org/spec/1.1/#id857577.
    However, some YAML-generating tools generate a single document followed by
    this separator before ending the file.

    This method supports the case of a single document in a file that contains
    superfluous document separators, but still throws if multiple documents are
    actually found.

    Args:
      name: str, The file path to the file or "-" to read from stdin.

    Returns:
      The contents of the file parsed as a YAML data object.
    r   rQ  -c                 S   s   g | ]}|d ur|qS r   r   )rQ   r.   r   r   r   rU   $
  rr   z<YAMLFileContents._LoadSingleYamlDocument.<locals>.<listcomp>r(   )	rS  rR  r   	ReadStdinload_allload_all_pathrX   rT  	load_path)r   r  rR  stdinrM  r   r   r   _LoadSingleYamlDocument

  s   


z(YAMLFileContents._LoadSingleYamlDocumentc              
   C   sn   ddl m} z| |}| | | jr | |s td||W S  |j|jfy6 } zt	|d}~ww )a  Load YAML data from file path (name) or stdin.

    If name is "-", stdin is read until EOF. Otherwise, the named file is read.
    If self.validator is set, call it on the yaml data once it is loaded.

    Args:
      name: str, The file path to the file.

    Returns:
      The contents of the file parsed as a YAML data object.

    Raises:
      ArgumentTypeError: If the file cannot be read or is not a JSON/YAML like
        object.
      ValueError: If file content fails validation.
    r   rQ  zInvalid YAML/JSON content [{}]N)
rS  rR  rU  rN  rJ  r   r!   r  FileLoadErrorr   )r   r  rR  rM  r   r   r   r   r/  1
  s   


zYAMLFileContents.__call__r   )r   r   r   r   r   rN  rU  r/  r   r   r   r   rH  	  s    
'rH  c                       s    e Zd ZdZ fddZ  ZS )StoreTrueFalseActiona  Argparse action that acts as a combination of store_true and store_false.

  Calliope already gives any bool-type arguments the standard and `--no-`
  variants. In most cases we only want to document the option that does
  something---if we have `default=False`, we don't want to show `--no-foo`,
  since it won't do anything.

  But in some cases we *do* want to show both variants: one example is when
  `--foo` means "enable," `--no-foo` means "disable," and neither means "do
  nothing." The obvious way to represent this is `default=None`; however, (1)
  the default value of `default` is already None, so most boolean actions would
  have this setting by default (not what we want), and (2) we still want an
  option to have this True/False/None behavior *without* the flag documentation.

  To get around this, we have an opt-in version of the same thing that documents
  both the flag and its inverse.
  c                    s   t t| j|dd i| d S )Nr  )rx  rW  r   r  r  r   r   r   e
     zStoreTrueFalseAction.__init__)r   r   r   r   r   r  r   r   r  r   rW  R
  s    rW  c                    r0  )zReturns Action that stores both file content and file path.

  Args:
   binary: boolean, whether or not this is a binary file.

  Returns:
   An argparse action.
  c                       s0   e Zd ZdZ fddZdfdd	Z  ZS )z.StoreFilePathAndContentsAction.<locals>.ActionzStores both file content and file path.

      Stores file contents under original flag DEST and stores file path under
      DEST_path.
    c                    s   t  | j|i | d S r   )rx  r   r  r4  r   r   r   z
  s   z7StoreFilePathAndContentsAction.<locals>.Action.__init__Nc              
      s`   z	t j| d}W n tjy } zt|d}~ww t|| j| d| j}t||| dS )z?Stores the contents of the file and the file name in namespace.rE  Nz{}_path)r   rF  r   r   r   r  r  r!   )r   r   r  rm   r  contentr   new_destrE  r   r   r/  }
  s   z7StoreFilePathAndContentsAction.<locals>.Action.__call__r   r;  r   r%  r?  r  r   r%  s
  s    r%  r&  rE  r   r[  r   StoreFilePathAndContentsActioni
  s   
r\  c                       r7  )ExtendConstActionz*Extends the dest arg with a constant list.c                    s   t t| j|ddi| d S )Nr  r   )rx  r]  r   r  r  r   r   r   
  rX  zExtendConstAction.__init__Nc                 C   s&   t | | jg }t|| j|| j  dS )z%Extends the dest with the const list.N)r  r  r  r   )r   r   r  rm   r  curr   r   r   r/  
  s   zExtendConstAction.__call__r   r;  r   r   r  r   r]  
  s    r]  c                   @   s"   e Zd ZdZdddZdd ZdS )	FilePathOrStdinContentsa  Creates an argparse type that stores a file path or the contents of stdin.

  This is similar to FileContents above but only reads content from stdin,
  otherwise just stores the file/directory path.

  Attributes:
    binary: bool, If True, the contents of the file will be returned as bytes.

  Returns:
    A function that accepts a filename, or "-" representing that stdin should be
    used as input.
  Fc                 C   s
   || _ d S r   rE  )r   r?  r   r   r   r   
  rP  z FilePathOrStdinContents.__init__c              
   C   sJ   z|dkrt j|| jdW S t|W S  tjy$ } zt|d}~ww )aj  Return the contents of stdin or the filepath specified.

    If name is "-", stdin is read until EOF. Otherwise, the named file path is
    returned.

    Args:
      name: str, The file name, or '-' to indicate stdin.

    Returns:
      The contents of stdin or the file path.

    Raises:
      ArgumentTypeError: If stdin cannot be read or is too large.
    rO  rE  N)r   rF  r?  r   ExpandHomeAndVarsr   r   rG  r   r   r   r/  
  s   z FilePathOrStdinContents.__call__Nr   )r   r   r   r   r   r/  r   r   r   r   r_  
  s    
r_  r  )r?   )NNTr?   Nr   )r+   r   Nr+   )NNNr3   r?   rE  )rP   F)FT)Tr   )gr   
__future__r   r   r   r  r  r
  rF   r  r~   dateutilr   googlecloudsdk.callioper   r  r   rS  r   r	   googlecloudsdk.core.consoler
   r   googlecloudsdk.core.utilr   r   ru   	six.movesr   __all__	Exceptionr   r   r  r   r   r#   r'   r   r   _SECOND_MINUTE_HOUR_DAY_DURATION_SCALESri   rJ   rO   ra   rh   rk   r   r   r   r   r   _KV_PAIR_DELIMITERobjectr   r   r   r   r   r   r   r   r   r  r  r  r  r   r!  r  r"  r  rJ  rM  rO  rU  rV  rX  rW  ru  rv  r  r%  r  r  _StoreActionr  r'  r(  r6  r8  r>  rN  rH  _StoreTrueActionrW  r\  r]  r_  r   r   r   r   <module>   s  "



o
(
Z
:27
=
(0
3
) .	 i   b~1
Y5%&dd
!