
                         `   S r SSKJr  SSKJr  SSKJr  SSKrSSKrSSKrSSKrSSK	r	SSK
r
SSKrSSKrSSKJr  SSKJr  SSKJr  SS	KJr  SS
KJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKrSr " S S\R<                  5      r " S S\5      r  " S S\!5      r" " S S\!5      r# " S S\RH                  5      r$ " S S\RJ                  " \RL                  \RN                  5      5      r( " S S \(5      r) " S! S"\RJ                  " \RL                  \(5      5      r*g)#a  Calliope argparse intercepts and extensions.

Calliope uses the argparse module for command line argument definition and
parsing. It intercepts some argparse methods to provide enhanced runtime help
document generation, command line usage help, error handling and argument group
conflict analysis.

The parser and intercepts are in these modules:

  parser_extensions (this module)

    Extends and intercepts argparse.ArgumentParser and the parser args
    namespace to support Command.Run() method access to info added in the
    Command.Args() method.

  parser_arguments

    Intercepts the basic argument objects and collects data for command flag
    metrics reporting.

  parser_errors

    Error/exception classes for all Calliope arg parse errors. Errors derived
    from ArgumentError have a payload used for metrics reporting.

Intercepted argument definitions for a command and all its ancestor command
groups are kept in a tree of ArgumentInterceptor nodes. Inner nodes have
is_group==True and an arguments list of child nodes. Leaf nodes have
is_group==False. ArgumentInterceptor keeps track of the arguments and flags
specified on the command line in a set that is queried to verify the specified
arguments against their definitions. For example, that a required argument has
been specified, or that at most one flag in a mutually exclusive group has been
specified.

The collected info is also used to generate help markdown documents. The
markdown is annotated with extra text that collates and describes argument
attributes and groupings. For example, mutually exclusive, required, and nested
groups.

The intercepted args namespace object passed to the Command.Run() method adds
methods to access/modify info collected during the parse.
    )absolute_import)division)unicode_literalsN)arg_parsers)base)parser_arguments)parser_errors)suggest_commands)
usage_text)
argv_utils)config)log)metrics)console_attr)
console_iozNTo search the help text of gcloud commands, run:
  gcloud help -- SEARCH_TERMSc                      ^  \ rS rSrSrU 4S jrS rS rS rSS jr	S r
\S	 5       r\S
 5       rS rS rS rS rS rS rS rS rS rS rSrU =r$ )	Namespace\   a  A custom subclass for parsed args.

Attributes:
  _deepest_parser: ArgumentParser, The deepest parser for the last command
    part.
  _parsers: ArgumentParser, The list of all parsers for the command.
  _specified_args: {dest: arg-name}, A map of dest names for known args
    specified on the command line to arg names that have been scrubbed for
    metrics. This dict accumulate across all subparsers.
c                 X   > S U l         / U l        0 U l        [        [        U ]  " S0 UD6  g )N )_deepest_parser_parsers_specified_argssuperr   __init__)selfkwargs	__class__s     0lib/googlecloudsdk/calliope/parser_extensions.pyr   Namespace.__init__h   s,    DDMD	)T#-f-    c                     Xl         g)z2Sets the parser for the first part of the command.Nr   )r   parsers     r   
_SetParserNamespace._SetParsern   s    !r!   c                     U R                   $ )z+Returns the deepest parser for the command.r#   r   s    r   
_GetParserNamespace._GetParserr   s    r!   c                 6    U R                  5       R                  $ )z+Returns the command for the deepest parser.)r)   _calliope_commandr(   s    r   _GetCommandNamespace._GetCommandv   s     ??...r!   c                 p    SnU R                  5       R                  R                  5       R                  XS9$ )zExecutes command in the current CLI.

Args:
  command: A list of command args to execute.
  call_arg_complete: Enable arg completion if True.

Returns:
  Returns the list of resources from the command.
F)call_arg_complete)r-   _cli_generatorGenerateExecute)r   commandr0   s      r   _ExecuteNamespace._Execute{   s>     ,,557?? @ 6 6r!   c                 J    U R                  5       R                  R                  $ )z Returns the parser display_info.)r-   aidisplay_infor(   s    r   GetDisplayInfoNamespace.GetDisplayInfo   s       ---r!   c                 d    U R                  5       R                  R                  nUc  U$ Xl        U$ )z%The holder for concepts v1 arguments.)r-   r8   concept_handlerparsed_argsr   handlers     r   CONCEPTSNamespace.CONCEPTS   s3      ##33GnNr!   c                 d    U R                  5       R                  R                  nUc  U$ Xl        U$ )z%The holder for concepts v2 arguments.)r-   r8   conceptsr>   r?   s     r   CONCEPT_ARGSNamespace.CONCEPT_ARGS   s3      ##,,GnNr!   c                 H    [        U R                  R                  5       5      $ )zReturns the scrubbed names for args specified on the command line.

For example,

  `$ {command} positional_value --foo=bar, --lorem-ipsum=hello`

returns ['POSITIONAL_NAME', '--foo', '--lorem-ipsum'].
sortedr   valuesr(   s    r   GetSpecifiedArgNamesNamespace.GetSpecifiedArgNames   s     $&&--/00r!   c           
          [         R                  " U R                  5       VVs0 s H  u  pU[        XS5      _M     snn$ s  snnf )a4  Gets the argument names and values that were actually specified.

For example,

  `$ {command} positional_value --foo=bar, --lorem-ipsum=1,2,3`

returns
  {
    'POSITIONAL_NAME': 'positional_value'
    '--foo': 'bar',
    '--lorem-ipsum': [1,2,3],
  }

In the returned dictionary, the keys are the specified arguments, including
positional argument names and flag names, in string type; the corresponding
values are the user-specified flag values, converted according to the type
defined by each flag.

Returns:
  {str: any}, A mapping of argument name to value.
UNKNOWN)six	iteritemsr   getattr)r   destnames      r   GetSpecifiedArgsNamespace.GetSpecifiedArgs   sF    0 --(<(<==JD 	gd),,=  s   Ac                     U R                   $ )a  Returns the _specified_args dictionary.

For example,

  $ {command} positional_value --foo=bar, --lorem-ipsum=hello --async,

returns
  {
    'positional_name', 'POSITIONAL_NAME'
    'foo': '--foo',
    'lorem_ipsum': '--lorem-ipsum',
    'async_': '--async',
  }.

In the returned dictionary, the keys are destinations in the argparse
namespace object.

In the above example, the destination of `--async` is set to 'async_' in its
flag definition, other flags use underscore separated flag names as their
default destinations.
)r   r(   s    r   GetSpecifiedArgsDictNamespace.GetSpecifiedArgsDict   s    , r!   c                     [        X5      (       d%  [        R                  " SR                  U5      5      eXR                  ;   $ )a  Returns True if args.dest was specified on the command line.

Args:
  dest: str, The dest name for the arg to check.

Raises:
  UnknownDestinationException: If there is no registered arg for dest.

Returns:
  True if args.dest was specified on the command line.
'No registered arg for destination [{}].)hasattrr	   UnknownDestinationExceptionformatr   r   rR   s     r   IsSpecifiedNamespace.IsSpecified   sA     455
3
:
:4
@B B''''r!   c                 B    [        X5      =(       a    XR                  ;   $ )zReturns True if dest is a known and args.dest was specified.

Args:
  dest: str, The dest name for the arg to check.

Returns:
  True if args.dest is a known argument was specified on the command line.
)r[   r   r^   s     r   IsKnownAndSpecifiedNamespace.IsKnownAndSpecified   s     4AD,@,@$@Ar!   c                    UR                  S5      (       a  USS R                  SS5      nUnOUnSUR                  SS5      -   nU R                  5       R                  nUR                  UR
                  -    H;  nX%R                  :X  d'  UR                  (       d  M%  X5R                  S   :X  d  M9  Us  $    [        R                  " SR                  U5      5      e)zReturns the flag argument object for name.

Args:
  name: The flag name or Namespace destination.

Raises:
  UnknownDestinationException: If there is no registered flag arg for name.

Returns:
  The flag argument object for name.
--   N-_r   z No registered flag arg for [{}].)
startswithreplacer-   r8   	flag_argsancestor_flag_argsrR   option_stringsr	   r\   r]   )r   rS   rR   flagr8   args         r   GetFlagArgumentNamespace.GetFlagArgument   s     t!"Xc3'dddDLLc**d						B||b333
((




););A)>!>
 4 
3
3*11$79 9r!   c                    UR                  SS5      R                  5       nUR                  SS5      R                  5       nU R                  5       R                  R
                   H<  n[        U[        5      (       a  M  X$R                  :X  d  X4R                  :X  d  M:  Us  $    [        R                  " SR                  U5      5      e)zReturns the positional argument object for name.

Args:
  name: The Namespace metavar or destination.

Raises:
  UnknownDestinationException: If there is no registered positional arg
    for name.

Returns:
  The positional argument object for name.
rg   rh   z&No registered positional arg for [{}].)rj   lowerupperr-   r8   positional_args
isinstancetyperR   metavarr	   r\   r]   )r   rS   rR   metaro   s        r   GetPositionalArgumentNamespace.GetPositionalArgument  s     <<S!'')D<<S!'')D!$$44	C				T[[0
	 5
 
3
3077=? ?r!   c                 h    U R                  U5      nUR                  (       a  UR                  S   $ S$ )a  Returns the flag name registered to dest or None is dest is a positional.

Args:
  dest: The dest of a registered argument.

Raises:
  UnknownDestinationException: If no arg is registered for dest.

Returns:
  The flag name registered to dest or None if dest is a positional.
r   N)rp   rm   )r   rR   ro   s      r   GetFlagNamespace.GetFlag,  s2     

t
$C$'$6$63a @D@r!   c                      [        X5      $ ! [         a&    [        R                  " SR	                  U5      5      ef = f)zReturns the value of the argument registered for dest.

Args:
  dest: The dest of a registered argument.

Raises:
  UnknownDestinationException: If no arg is registered for dest.

Returns:
  The value of the argument registered for dest.
rZ   )rQ   AttributeErrorr	   r\   r]   r^   s     r   GetValueNamespace.GetValue;  sG    BT   B55
3
:
:4
@B BBs   
 0=c                    ^ ^ UU 4S jnU$ )a  Returns a function to get given flag value or raise if it is not set.

This is useful when given flag becomes required when another flag
is present.

Args:
  flag_name: str, The flag_name name for the arg to check.

Raises:
  parser_errors.RequiredError: if flag is not specified.
  UnknownDestinationException: If there is no registered arg for flag_name.

Returns:
  Function for accessing given flag value.
c                     > TR                  S5      (       a  TSS  OTn [        TU 5      nUc*  TR                  U 5      (       d  [        R                  " TS9eU$ )Nre   rf   )argument)ri   rQ   r_   r	   RequiredError)rn   
flag_value	flag_namer   s     r   _Func'Namespace.MakeGetOrRaise.<locals>._Func]  sY    '22488Yqr]id4&j		D$4$4T$:$:))9==r!   r   )r   r   r   s   `` r   MakeGetOrRaiseNamespace.MakeGetOrRaiseM  s      Lr!   )r   r   r   )F)__name__
__module____qualname____firstlineno____doc__r   r%   r)   r-   r5   r:   propertyrA   rE   rK   rT   rW   r_   rb   rp   rz   r}   r   r   __static_attributes____classcell__r   s   @r   r   r   \   s    	." /
6.
    	16 0("	B94?.AB$ r!   r   c                   $    \ rS rSrSrS rS rSrg)_ErrorContextig  ac  Context from the most recent ArgumentParser.error() call.

The context can be saved and used to reproduce the error() method call later
in the execution.  Used to probe argparse errors for different argument
combinations.

Attributes:
  message: The error message string.
  parser: The parser where the error occurred.
  error: The exception error value.
c                 x    [         R                  " SSU5      U l        X l        X0l        UR
                  U l        g )N\bu'')resubmessager$   errorflags_locations)r   r   r$   r   s       r   r   _ErrorContext.__init__t  s.    66'30DLKJ!11Dr!   c                     U R                   R                  U5      nU(       a*  SR                  USR                  [	        U5      5      5      nU$ )z4Adds locaton info from context for arg if specified.{} ({}),)r   getr]   joinrI   )r   ro   	locationss      r   AddLocations_ErrorContext.AddLocationsz  s@    $$((-IS#((6)+<"=>cJr!   )r   r   r   r$   N)r   r   r   r   r   r   r   r   r   r!   r   r   r   g  s    
2r!   r   c                       \ rS rSrSrSrg)_HandleLaterErrori  a6  Error to be handled in a subsequent call to self.error.

This error exists to provide a way to break out of self.error so that we can
deduce a better error later; it will always be caught in parser_extensions and
never surfaced as a user-facing error (at least in theory; if that does happen
then it's a bug.)
r   Nr   r   r   r   r   r   r   r!   r   r   r     s     r!   r   c                       \ rS rSrSrSrg)DryRunErrori  z<Error to pack for dry run cases without causing system exit.r   Nr   r   r!   r   r   r     s    Dr!   r   c                   4  ^  \ rS rSrSrSrU 4S jrS rS rS r	S S jr
S	 rS
 rS!U 4S jjrS r\S 5       r S"S jrS#S jr\S 5       r\S 5       r\S 5       rS$S jrS rS S jrS rS r S S jrS rS%S jrS&S jrU 4S jr U 4S jr!U 4S jr"Sr#U =r$$ )'ArgumentParseri  a  A custom subclass for arg parsing behavior.

This overrides the default argparse parser.

Attributes:
  _args: Original argv passed to argparse.
  _calliope_command: base._Command, The Calliope command or group for this
    parser.
  _error_context: The most recent self.error() method _ErrorContext.
  _is_group: bool, True if _calliope_command is a group.
  _probe_error: bool, True when parse_known_args() is probing argparse errors
    captured in the self.error() method.
  _remainder_action: action, The argument action for a -- ... remainder
    argument, added by AddRemainderArgument.
  _specified_args: {dest: arg-name}, A map of dest names for known args
    specified on the command line to arg names that have been scrubbed for
    metrics. This value is initialized and propagated to the deepest parser
    namespace in parse_known_args() from specified args collected in
    _get_values().
    raise_error: This is set to true if we want to raise an exception for
    errors.
Nc                   > UR                  S5      U l        [        U R                  S5      U l        S U l        0 U l        S U l        SU l        [        R                  " [        5      U l        SU l        [        [        U ]>  " U0 UD6  g )Ncalliope_commandcommandsF)popr,   r[   	_is_group_remainder_actionr   _error_context_probe_errorcollectionsdefaultdictsetr   raise_errorr   r   r   r   argsr   r   s      r   r   ArgumentParser.__init__  sz    #ZZ(:;D T33Z@DN!DDDD&2237DD	.$($9&9r!   c                 ^    U R                  [        [        R                  " U5      X5      S9  g )N)context)r   r   r   SafeText)r   r   s     r   _ErrorArgumentParser._Error  s"    JJ}\%:%:5%A4OJPr!   c                     U R                   (       a%  U R                  [        R                  " S5      5        [        R
                  US'   U R                  " U0 UD6U l         U R                   $ )ap  Add an argument representing '--' followed by anything.

This argument is bound to the parser, so the parser can use its helper
methods to parse.

Args:
  *args: The arguments for the action.
  **kwargs: They keyword arguments for the action.

Raises:
  ArgumentException: If there already is a Remainder Action bound to this
  parser.

Returns:
  The created action.
z,There can only be one pass through argument.action)r   r   r	   ArgumentExceptionr   RemainderActionadd_argument)r   r   r   s      r   AddRemainderArgument#ArgumentParser.AddRemainderArgument  s]    " 
kk-11
8: ;"22F8!..??D!!!r!   c                 H    [        U R                  R                  5       5      $ )zBReturns the scrubbed names for args specified on the command line.rH   r(   s    r   rK   #ArgumentParser.GetSpecifiedArgNames  s    $&&--/00r!   c                     U(       a  SU;  a  SR                  X5      nOUnU R                  R                  U5      nU(       a*  SR                  USR                  [	        U5      5      5      nU$ )z:Adds file and line info from context for arg if specified.=z{}={}r   r   )r]   r   r   r   rI   )r   ro   valueargvalr   s        r   _AddLocationsArgumentParser._AddLocations  s\    C~~c)ff$$((0IVSXXfY.?%@AcJr!   c           
         / n[         R                  " 5       nU R                  R                  SS9 HS  nUR                  nU(       d  M  UR                  U5        [        USS5      nU(       d  M?  UR                  XeS   5        MU     0 nU GHb  n[        U[        R                  5      (       d  M%  UR                  S5      S   n[        UR                  S5      5      S:  a  UR                  S5      S   OSn	UR                  S5      (       d  U	(       a#  UR                  U5      n
U R                  U5      nOSn
X;   a  M  U R!                  U5      (       aT  U R!                  U5      nUR#                  S	R%                  U5      5        UR#                  S
R'                  U5      S-   5        U
(       a*  XU'   UR#                  USR%                  U
5      -   5        GMQ  UR#                  U5        GMe     [        U5      S:  a  Su  pOSu  pUR#                  SR%                  U[(        5      5        U R+                  [,        R.                  " SR%                  XR'                  U5      5      U [        U5      [        U5      US95        g)zDError out with a suggestion based on text distance for each unknown.Finclude_hiddensuggestion_aliasesNr   r      re   zE
 {} flag is available in one or more alternate release tracks. Try:

  
z (did you mean '{0}'?))r    ) z

z{}{}zunrecognized arguments:{0}{1})r$   total_unrecognizedtotal_suggestionssuggestions)r   TextChoiceSuggesterr,   GetAllAvailableFlagsrm   
AddChoicesrQ   
AddAliasesrv   rO   string_typessplitlenri   GetSuggestionr   %_ExistingFlagAlternativeReleaseTracksappendr]   r   _HELP_SEARCH_HINTr   r	   UnrecognizedArgumentsError)r   unknown_argsmessages	suggesterrn   optionsaliasesr   ro   r   
suggestionexisting_alternatives	separatorprefixs                 r   _SuggestArgumentParser._Suggest  s)   H..0I&&;; < ##g	W%$ 4d;7


w

3 KS--..YYs^Ad#&syy~#6#:ciinQe			%,,T2
  %
			3	3D	9	9 $ J J4 P 117	?$9:D@A	%C6==jIIJ/ 6 8}q$i%i OOFMM&*;<=KK88'..~~h/	1|,k*! "r!   c                     Xl         g)zDSets the current error context to context -- called by self.error().N)r   )r   r   s     r   _SetErrorContextArgumentParser._SetErrorContext!  s    !r!   c                 ,  > SU l         U(       a  U O[        [        U 5      n UR                  X5      u  p%U R                   nSU l         U(       d0  [        US5      (       a  [        R                  " [        5      Ul	        X%U4$ ! [         a    / n N\f = f)a  Calls parse_known_args() and adds error_context to the return.

Args:
  args: The list of command line args.
  namespace: The parsed args namespace.
  wrapper: Calls the parse_known_args() wrapper if True, otherwise the
    wrapped argparse parse_known_args().

Returns:
  namespace: The parsed arg namespace.
  unknown_args: The list of unknown args.
  error_context: The _ErrorContext if there was an error, None otherwise.
Nr   )
r   r   r   parse_known_argsr   r[   r   r   r   r   )r   r   	namespacewrapperr$   r   error_contextr   s          r   _ParseKnownArgsArgumentParser._ParseKnownArgs%  s     DT%"=F & 7 7 Hi ''MDGF,=>>*66s;fM11  ls   B BBc                 h   SU l         U H>  n UR                  S5      (       d    O& U R                  U/U5      u    pVU(       d  M<  Un  O   SU l         UR	                  UR
                  R                  5      UR
                  l        UR                  R                  USS9  g! [         a       Md  f = f)a  There is an argparse error in context, see if we can do better.

We are committed to an argparse error. See if we can do better than the
observed error in context by isolating each flag arg to determine if the
argparse error complained about a flag arg value instead of a positional.

Args:
  context: The _ErrorContext containing the error to improve.
  args: The subset of the command lines args that triggered the argparse
    error in context.
  namespace: The namespace for the current parser.
Trg   F)r   	reproduceN)r   ri   r   r   r   r   r   r$   )r   r   r   r   ro   rh   r   s          r   _DeduceBetterError!ArgumentParser._DeduceBetterError?  s     D~~c""
 # !00#	Bag  D$11'--2H2HIGMMNND9  s   B""
B10B1c           
      Z    [        U  Vs/ s H  n[        USU5      PM     sn5      $ s  snf )z=Returns the set of 'dest' attributes (or the arg if no dest).rR   )r   rQ   )r   as     r   GetDestinationsArgumentParser.GetDestinations\  s*     t4t!61%t4554s   (c                    / n/ n/ n/ n	UR                   (       a"  [        UR                  [        R                  S9OUR                  n
U
 H  nUR
                  (       a'  U R                  UUUU=(       a    UR                  SS9nOUR                  U;   nU(       a7  UR                  (       a  UR                  U5        Mu  UR                  U5        M  UR                  (       a*  [        U[        5      (       d  U	R                  U5        M  M  UR                  U5        M     U	(       Ga  U(       d  U(       ag  U(       d`  U(       dY  [        R                  " U	SUR                   S9nU R                  [        R                  " U [        R                   " USSUS9S95        U(       d  U(       a  [        R                  " Xx-   SUR                   S9n[        R                  " U	SUR                   S9nU R                  [        R"                  " U [        R                   " USSUS9[        R                   " USSUS9S95        [%        U R'                  U5      5      [%        U R'                  U5      5      -   nUR(                  (       GaZ  [        R                   " USSUS9nU(       a  UR                  (       a  US	:w  a  U(       a  [        R                   " [        X-   [        R                  S9S
   SSUS9n UR+                  U5      nU(       aM  UR/                  UR                  5      n[        U[0        [2        [4        45      (       d  U R7                  UU5      nOSnU R                  [        R8                  " U UUS95        O]US	:  aW  [        R                   " [        X-   [        R                  S9S
   SSUS9nU R                  [        R:                  " U UUS95        [1        U5      $ ! [        R,                   a    Sn Nf = f)a  Validate specified args against the arg group constraints.

Each group may be mutually exclusive and/or required. Each argument may be
required.

Args:
  ai: ArgumentInterceptor, The argument interceptor containing the
    ai.arguments argument group.
  specified_args: set, The dests of the specified args.
  namespace: object, The parsed args namespace.
  is_required: bool, True if all containing groups are required.
  top: bool, True if ai.arguments is the top level group.

Raises:
  ModalGroupError: If modal arg not specified.
  OptionalMutexError: On optional mutex group conflict.
  RequiredError: If required arg not specified.
  RequiredMutexError: On required mutex group conflict.

Returns:
  True if the subgroup was specified.
keyF)is_requiredtopT)	argumentsis_group	sort_args)r   hiddenr  )r$   r   )r$   r   conflictr   r   N)r  rI   r  r   GetArgSortKeyr  validate_specified_argsr  rR   r   rv   DynamicPositionalActionArgumentWrapperr   r	   r   GetArgUsageModalGroupErrorr   r  is_mutexrp   r\   r   booldictlistr   RequiredMutexErrorOptionalMutexError)r   r8   specified_argsr   r  r  also_optionalhave_optionalhave_requiredneed_requiredr  ro   arg_was_specified	need_args	have_argscountr  r   rn   r   s                       r   r  &ArgumentParser.validate_specified_argsb  s~   2 MMMM << 	r||!9!9:\\  	 88#7 9   HH6	??


s
#


s
#??#677


s
# 8 	S!' * 	}..#dbllL	M//++t>? 	@ 
-..#3dll$	 ..#dll$	 	M11++t>++t>	? 	@ %%m45%%m456E 
{{{''%#Nh	A:!--}4%335568Dc3H..x8d ((3edD'9::--h>H
++m66HxA B19))=0!//1124#/ 	M44(X? 	@ ;% !<< ds   4O* *PPc                    Uc  [         R                  " 5       SS nUc
  [        5       nUR                  U 5         U R                  (       aC   U R
                  R                  U R                  5        U R                  R                  X5      u  p!UR                  U l	        U R                  XSS9u  p#nUR                  R                  U R                  5        U(       a  U R                  U5        O>U(       a7  U R                  (       a
  [        5       eUR                  R!                  XAU5        UR"                  R%                  U 5        U R                  (       a%  U R
                  R%                  U R                  5        X#4$ ! [         a     GNf = f! U R                  (       a&  U R
                  R%                  U R                  5        f f = f)z=Overrides argparse.ArgumentParser's .parse_known_args method.Nr   F)r   )r   GetDecodedArgvr   r%   r   _actionsremove
ValueErrorParseKnownArgsr   r   updater   r   r   r$   r  r   r   )r   r   r   r   r   s        r   r   ArgumentParser.parse_known_args  s   |&&(,d+i5				
--

t55
6 00??P	&66d/3/C/C
5 0D 0*,i} &&t';';<	l#!#
#//	,% 
		T334$$-  	
	( 
		T334 
 s0   F %F 2CF 
FF FF 9Gc                 6    U(       a  US S  U l         g S U l         g N_args)clsoriginal_argss     r   _SaveOriginalArgs ArgumentParser._SaveOriginalArgs  s    "cicir!   c                     S U l         g r1  r2  r4  s    r   _ClearOriginalArgs!ArgumentParser._ClearOriginalArgs  s	    CIr!   c                     U R                   $ r1  r2  r9  s    r   _GetOriginalArgsArgumentParser._GetOriginalArgs  s    99r!   c                    U R                  U5        X0l        U R                  X5      u  p$nUR                  5       nUR                  Ul        U(       dm  UR
                   H+  n UR                  UR                  UR                  U5        M-     UR                  5       R                  (       a  UR                  S5        U$ UR                  (       a)   UR                  R                  XBU5      u  p$U(       d  U$  UR%                  U5        g! [        R                   a  nUR                  U5         SnAM  SnAff = f! [         R"                   a     N[f = f)z7Overrides argparse.ArgumentParser's .parse_args method.NCommand name argument expected.)r6  r   r   r)   r   r   r  r8   argparseArgumentErrorr   r-   r  r   r   ParseRemainingArgsr	   r   r   )	r   r   r   r   r   rh   deepest_parserr$   es	            r   
parse_argsArgumentParser.parse_args  s?   4 "!%!5!5d!FIQ ))+N%.%>%>N" &&&	#

(
(ii22I? ' 
			 	)	)>? ''

,,??/ 	 	 
  L)3 %% 	#



"
"	#( 55  	s*   $'D&E  D=!D88D= EEc                   ^ [        U[        5      nU(       a)  S[        R                  ;   a  [        R
                  Ul        UR                  b  X!R                  ;   a  g[        U[        R                  5      (       a  UnO[        R                  " U5      nU(       a  UR                  U5      (       a  gU R                  R                  nUR                  U R                  R                  5       U/-   5      nU(       a=  SSKJn  SR%                  SR'                  U5      S9nUR(                  R+                  XhS9  U(       a  UR-                  5         S	R%                  U5      n	U R/                  U5      n
U
(       a?  U	S
-  n	U	SR'                  U
5      -  n	U R1                  [2        R4                  " U	U UU
S95        Sn[7        US/ 5      m[9        U4S jUR                   5       5      nU(       d  [:        R<                  " U5      nUR?                  U5      nU(       a  U	SR%                  U5      -  n	OHU	SR%                  SR'                  U Vs/ s H  n[        R                  " U5      PM     sn5      5      -  n	U R1                  [2        R@                  " U	URB                  (       a  URB                  S   OSSU(       a  SOSU(       a  U/OUS95        gs  snf )aJ  Overrides argparse.ArgumentParser's ._check_value(action, value) method.

Args:
  action: argparse.Action, The action being checked against this value.
  value: The parsed command line argument provided that needs to correspond
      to this action.

Raises:
  argparse.ArgumentError: If the action and value don't work together.
_ARGCOMPLETENr   )update_managerzYou do not currently have this command group installed.  Using it requires the installation of components: [{missing_components}]z, )missing_components)msgzInvalid choice: '{0}'.zL
This command is available in one or more alternate release tracks.  Try:
  r   )r$   extra_path_argr   hidden_choicesc              3   6   >#    U  H  oT;  d  M
  Uv   M     g 7fr1  r   ).0crN  s     r   	<genexpr>.ArgumentParser._check_value.<locals>.<genexpr>  s     J1>2IQQs   		z Did you mean '{0}'?z

Valid choices are [{0}].r   )r   r   r   r   )"rv   CloudSDKSubParsersActionosenvironrA  _SubParsersAction_orig_classchoicesrO   r   	text_typeIsValidChoicer,   r1   ComponentsForMissingCommandGetPathgooglecloudsdk.core.updaterrJ  r]   r   UpdateManagerEnsureInstalledAndRestartLoadAllChoices(_ExistingCommandAlternativeReleaseTracksr   r	   WrongTrackErrorrQ   rI   r   r   r   UnknownCommandErrorrm   )r   r   r   is_subparserro   cli_generatorrK  rJ  rL  r   r   r   rY  r   rQ  rN  s                  @r   _check_valueArgumentParser._check_value1  s    f&>?L "**4#55f~~..!8%))**cMM% c ,,S11 **99M&BB&&(C502<&&,f$(II.@$A '- 'C 
 ""<<
 = '   '--e4G !II#N . /g233g
 kk-//
+	- . JV%5r:NJJJG009i**3/j	)00<< 	188II9As}}Q'9:< 	< 	KK11-3-B-B&&q))!q$.ZLG= > :s    Kc                    / nU R                   R                  nUR                  U R                   R                  5       U(       a  U/O/ -   5      nU(       a  U R                   R	                  5       n[        [        R                  " U5      S S9 HJ  u  pgUR                  USS 5      nU(       d  M"  UR                  5       (       a  M9  UR                  U5        ML     U$ )zGets alternatives for the command in other release tracks.

Args:
  value: str, The value being parsed.

Returns:
  [CommandCommon]: The alternatives for the command in other release tracks.
c                 2    U S   R                   =(       d    S$ )Nr   r   )r   )xs    r   <lambda>AArgumentParser._CommandAlternativeReleaseTracks.<locals>.<lambda>  s    !A$++2C2Cr!   r	  r   N)r,   r1   %ReplicateCommandPathForAllOtherTracksr]  _TopCLIElementrI   rO   rP   LoadSubElementByPathIsHiddenr   )	r   r   r   rf  
alternatestop_elementrh   command_pathalternative_cmds	            r    _CommandAlternativeReleaseTracks/ArgumentParser._CommandAlternativeReleaseTracks  s     **99MDD&&(uUG"EGJ**99;k#CMM*$=(CE/!%::<;KL??#;#;#=#=

&
&
7	E
 ! r!   c                    / nU R                  5        Hh  nXR                  SS9 Vs/ s H  oDR                  S   PM     sn;   d  M4  UR                  SR	                  UR                  5       5      S-   U-   5        Mj     U$ s  snf )zChecks whether the arg exists in other tracks of the command.

Args:
  arg: str, The argument being parsed.

Returns:
  [str]: The names of alternate commands that the user may use.
Fr   r   r   )rv  r   rm   r   r   r]  )r   ro   res	alternatefs        r   r   4ArgumentParser._ExistingFlagAlternativeReleaseTracks  s     C::<		.L.L /M /  ! / !!!$ /  ! 
!

388I--/036<= = J!s   Bc                     U R                  US9 Vs/ s H"  nSR                  UR                  5       5      PM$     sn$ s  snf )zGets the path of alternatives for the command in other release tracks.

Args:
  value: str, The value being parsed.

Returns:
  [str]:  The names of alternate commands that the user may use.
)r   r   )rv  r   r]  )r   r   rz  s      r   rb  7ArgumentParser._ExistingCommandAlternativeReleaseTracks  sM     111>@> /8CHHY&&()>@ @ @s   )>c                     U R                  5       n[        R                  " U[        R                  UUUS9  [        R
                  " UUUUS9  g)a  Logs `Commands` and `Error` Google Analytics events for an error.

Args:
  dotted_command_path: str, The dotted path to as much of the command as we
      can identify before an error. Example: gcloud.projects
  error: class, The class (not the instance) of the Exception for an error.
  error_extra_info: {str: json-serializable}, A json serializable dict of
    extra info that we want to log with the error. This enables us to write
    queries that can understand the keys and values in this dict.
)r   error_extra_info)r  N)rK   r   Commandsr   CLOUD_SDK_VERSIONError)r   dotted_command_pathr   r  r  s        r   _ReportErrorMetricsHelper(ArgumentParser._ReportErrorMetricsHelper  sO     ..0N  )+ MM)	+r!   c                    SR                  U R                  R                  5       5      n[        U[        R
                  5      (       aV  UR                  (       a  SR                  UUR                  /5      nU R                  UUR                  UR                  5        gSU;   a!  U R                  U[        R                  5        gU R                  U[        R                  5        g)zReports Command and Error metrics in case of argparse errors.

Args:
  error: Exception, The Exception object.
  message: str, The exception error message.
.Ntoo few arguments)r   r,   r]  rv   r	   rB  rM  r  r   r  TooFewArgumentsErrorOtherParsingError)r   r   r   r  s       r   ReportErrorMetrics!ArgumentParser.ReportErrorMetrics  s     ((4#9#9#A#A#CD %4455			!hh(;(-(<(<(> ?
$$%8%*__%*%;%;=  g%
$$%8%2%G%GI 	""#6#0#B#BDr!   c                    S[         R                  ;  ar  [        R                  " SU5      (       a  g[        R                  " SU5      (       a9  [        R                  " SU5      (       d  [        R                  " SU5      (       d  gU(       aH  U(       aA  UR                  nUR
                  nUR                  nU(       d  [        R                  " XS9nGOU(       a%  UR                  nUR
                  nUR                  nONSU;   a  [        R                  nO[        R                  nU(       a  [        R                  " S	S
U5      nU" XS9nU nS[         R                  ;  a  [        U[        R                  5      (       df  U R                  (       d  SU;   aO  U R                  (       a  SU;   a
  [        5       eU R                  U=(       d    [!        XU5      5        [        5       eSnU(       a]  UR#                  U5      (       aG  UR%                  SS5      nUR'                  US   [)        U5      S 5      n	SR+                  XyUS   5      nS[         R                  ;   a7  U R,                  R.                  (       a  U R,                  R1                  5         GOU R2                  (       Gd  [4        R6                  " U5      n[8        R                  " SR+                  U R:                  US95        S[         R                  ;   a"  [         R                  S   S:X  a  [=        U5      eSU;  Ga  Sn
SU;   =(       a    SU;  nU(       a4  [>        R@                  " U RC                  5       5      n
U RE                  5         U
(       a  [F        RH                  RJ                  RM                  SRO                  S/U
-   5      S-   5        [F        RH                  RJ                  RM                  S[P        -   S-   5        U
[)        U
5      SS.Ul)        GOSU:X  Ga_  SSK*J+n  U R,                  RY                  5       nSnU(       d  SnU R,                  R[                  5       nSnU(       d  [\        R^                  " SS9nU(       a4  [`        Rb                  " 5       nURM                  S R+                  US!95        O[F        RH                  RJ                  nURM                  S5        URe                  [`        Rb                  " U5      US"9  U(       a)  URM                  U R,                  Rg                  5       5        U(       a;  [\        Rh                  " URk                  5       [F        RH                  RJ                  S#9  OCU R,                  Rm                  5       n[F        RH                  RJ                  RM                  U5        URo                  XQ5        U Rq                  S$US%9  g)&a  Overrides argparse.ArgumentParser's .error(message) method.

Specifically, it avoids reprinting the program name and the string
"error:".

Args:
  message: str, The error message to print.
  context: _ErrorContext, An error context with affected parser.
  reproduce: bool, Reproduce a previous call to this method from context.

Raises:
  _HandleLaterError: if the error should be handled in a subsequent call to
    this method.
  DryRunError: If CLOUDSDK_CORE_DRY_RUN is set to 1.
rI  r  Nzarguments? .* requiredzin dict arg but not providedz\[.*\brequired\b.*\])r$   zInvalid choice:r   r   zInvalid choicezexpected one argumentz	argument :r   r   z{}{}:{}z({prog}) {message})progr   CLOUDSDK_CORE_DRY_RUN1r   zValid choicesr   zMaybe you meant:)r   r   r   r@  )render_documentFT)r   z
{message}
)r   )finout)r  rf   )	exception)9rU  rV  r   searchr   r$   r   r	   rB  r   r   rv   DetailedArgumentErrorr   r   r   r   ri   r   r   r   r]   r,   _sub_parserLoadAllSubElementsr   r   r   r   r  r   r
   GetCommandSuggestionsr=  r:  rA  _sysstderrwriter   r   r  &googlecloudsdk.core.document_renderersr  GetCategoricalUsageGetUncategorizedUsager   IsInteractiveioStringIORenderDocumentGetHelpHintMoregetvalueGetUsager  exit)r   r   r   r  r$   r   excr   partsro   r   is_invalid_commandr  usage_stringuncategorized_usageinteractiver  s                    r   r   ArgumentParser.error  sj   " RZZ'	&	0	0
)),g
6
6ii6@@ii/99Wg~~fmme++GA	//'88#++#FF7C1'G)



* C CDD') !8G!C!#
# 	gNw)NO!! F7%%f--mmC#e  q#f+,!78c  eAh7g
 #				+	+113%%g.g	ii$++G+LM
!RZZ
/jj01S8'"" 
W	 .'9 =-W< 	(>>##%'+

!
!
#
--


$
$kk-.<=DF
--


$
$T,=%=%D
E(#&{#3$%$%
  /'9
L//CCE, !&
"&11GGIL+$$22>K++-CIIm**7*;<--&&C
))D/

(
(++l+ ) 6 IId,,88:;OOCLLN0D0DE//88:,
--


$
$\
2
e-IIa5I!r!   c                 X    AU R                   (       a  Ue[        R                  " U5        g)zOverrides argparse.ArgumentParser's .exit() method.

Args:
  status: int, The exit status.
  message: str, The error message to print.
  exception: Exception, The exception that caused the exit, if any.
N)r   sysr  )r   statusr   r  s       r   r  ArgumentParser.exit  s!     	oHHVr!   c                   > [        U[        R                  5      (       d  gU R                  5       n[        [
        U ]  U5      nU=(       a    US   n[        U5      S:X  a)  US   R                  [        R                  :X  a  U(       d  gU$ )a)  Overrides argparse.ArgumentParser's ._parse_optional method.

This allows the parser to have leading flags included in the grabbed
arguments and stored in the namespace.

Args:
  arg_string: str, The argument string.

Returns:
  The normal return value of argparse.ArgumentParser._parse_optional.
Nr   r   )rv   rO   r   _get_positional_actionsr   r   _parse_optionalr   nargsrA  	REMAINDER)r   
arg_stringpositional_actionsoption_tupleknown_optionr   s        r   r  ArgumentParser._parse_optional  s~     j#"2"233557>zJL  3LOL1$1##x'9'99r!   c                   > UR                   [        R                  :w  a  SnUR                  (       a  UR                  S   nOvU(       ao  UR                  (       a  UR                  OUR                   nUR
                  (       a5  UR
                  S:w  a%  US[        R                  " [        U5      5      -   -  nU(       a  X0R                  UR                   '   [        [        U ]3  X5      $ )a  Intercepts argparse.ArgumentParser's ._get_values method.

This intercept does not actually change any behavior.  We use this hook to
grab the flags and arguments that are actually seen at parse time.  The
resulting namespace has entries for every argument (some with defaults) so
we can't know which the user actually typed.

Args:
  action: Action, the action that is being processed.
  arg_strings: [str], The values provided for this action.

Returns:
  Whatever the parent method returns.
Nr   ?r  )rR   rA  SUPPRESSrm   rx   r  rO   rZ  r   r   r   r   _get_values)r   r   arg_stringsrS   r   s       r   r  ArgumentParser._get_values  s     {{h''' d			$$Q'
 "(v~~V[[<<FLLC/ #c+&677
7$	,0V[[)26GGr!   c                 V   > S[         R                  ;   a  [        [        U ]  U5      $ / $ )a4  Intercepts argparse.ArgumentParser's ._get_option_tuples method.

Cloud SDK no longer supports flag abbreviations, so it always returns []
for the non-arg-completion case to indicate no abbreviated flag matches.

Args:
  option_string: The option string to match.

Returns:
  A list of matching flag tuples.
rI  )rU  rV  r   r   _get_option_tuples)r   option_stringr   s     r   r  !ArgumentParser._get_option_tuples  s(     #>4;MJJIr!   )r,   r   r   r   r   r   r   r   r1  )T)TT)NN)NNF)r   NF)r   NN)%r   r   r   r   r   r3  r   r   r   rK   r   r   r   r   r  staticmethodr  r  r   classmethodr6  r:  r=  rF  rg  rv  r   rb  r  r  r   r  r  r  r  r   r   r   s   @r   r   r     s    . %:Q"21	9"v"24:: 6 6 59l\"%H      ,*\h>T!. 
@ 26+2D:M"^4"HH r!   r   c                   `    \ rS rSrSr\R                  S 5       r\R                  S 5       rSr	g)rT  i  zA custom subclass for arg parsing behavior.

While the above ArgumentParser overrides behavior for parsing the flags
associated with a specific group or command, this class overrides behavior
for loading those sub parsers.
c                     g)zDetermines if the given arg is a valid sub group or command.

Args:
  choice: str, The name of the sub element to check.

Returns:
  bool, True if the given item is a valid sub element, False otherwise.
Nr   r   choices     r   r[  &CloudSDKSubParsersAction.IsValidChoice  s     	r!   c                     g)z:Load all the choices because we need to know the full set.Nr   r(   s    r   ra  'CloudSDKSubParsersAction.LoadAllChoices  s     	r!   r   N)
r   r   r   r   r   abcabstractmethodr[  ra  r   r   r!   r   rT  rT    s;     		 		 	 	r!   rT  c                   H   ^  \ rS rSrSrU 4S jrS rS rSU 4S jjrSr	U =r
$ )	CommandGroupActioni  zA subparser for loading calliope command groups on demand.

We use this to intercept the parsing right before it needs to start parsing
args for sub groups and we then load the specific sub group it needs.
c                 Z   > UR                  S5      U l        [        [        U ]  " U0 UD6  g )Nr   )r   r,   r   r  r   r   s      r   r   CommandGroupAction.__init__  s*    #ZZ(:;D	
d,d=f=r!   c                     S[         R                  ;   a  U R                  R                  U5        U R                  R	                  U5      $ )NrI  )rU  rV  r,   LoadSubElementIsValidSubElementr  s     r   r[   CommandGroupAction.IsValidChoice  s;     #
++F3!!33F;;r!   c                 8    U R                   R                  5         g r1  )r,   r  r(   s    r   ra  !CommandGroupAction.LoadAllChoices#  s    --/r!   c                    > US   nU R                   (       a  U R                   R                  U5        [        [        U ]  XX4S9  g )Nr   r  )r,   r  r   r  __call__)r   r$   r   rJ   r  parser_namer   s         r   r  CommandGroupAction.__call__&  sH     )K 
++K8	
d,6 - @r!   )r,   r1  )r   r   r   r   r   r   r[  ra  r  r   r   r   s   @r   r  r    s#    >
<0	@ 	@r!   r  c                      ^  \ rS rSrSrU 4S jrS rS rS r\	R                  S 5       r\	R                  S 5       rSU 4S	 jjrS
rU =r$ )r  i2  av  An argparse action that adds new flags to the parser when it is called.

We need to use a subparser for this because for a given parser, argparse
collects all the arg information before it starts parsing. Adding in new flags
on the fly doesn't work. With a subparser, it is independent so we can load
flags into here on the fly before argparse loads this particular parser.
c                    > UR                  SS5      U l        UR                  S5      U l        [        [        U ]  " U0 UD6  g )Nr  F	parent_ai)r   r  
_parent_air   r  r   r   s      r   r    DynamicPositionalAction.__init__<  s:    **Xu-DKjj-DO	
!414B6Br!   c                 &    U R                  U5        g)NT)
_AddParserr  s     r   r[  %DynamicPositionalAction.IsValidChoiceA  s     	OOF
 r!   c                     g r1  r   r(   s    r   ra  &DynamicPositionalAction.LoadAllChoicesQ  s     	r!   c                     U R                  USU R                  R                  R                  U R                  R                  R                  S9$ )NF)add_helpr  r   )
add_parserr  r$   r  r,   r  s     r   r  "DynamicPositionalAction._AddParserW  sF     ??T__%;%;%@%@//AA  C Cr!   c                     g r1  r   )r   r   r  s      r   GenerateArgs$DynamicPositionalAction.GenerateArgs^      r!   c                     g r1  r   )r   r   r>   r   s       r   Completions#DynamicPositionalAction.Completionsb  r  r!   c                 H  > US   nU R                  X%5      nU R                  U   n[        R                  " USS SU R                  R
                  S9n[        R                  " U R                  R                  U R                  R                  5       H8  n	U	R                  (       d  U	R                  (       a  M'  UR                  U	5        M:     UR                  R                  U R                  R                  5        U H_  n
U
R                  U5        U
R!                  U5      nS["        R$                  ;   d  M;  ['        US5      (       a  MN  UR(                  Ul        Ma     [,        [.        U ]c  XX4S9  S["        R$                  ;  a  U R                  R3                  5         g g )Nr   FT)	is_globalrf  allow_positionaldatarI  rX  r  )r  _name_parser_mapr   ArgumentInterceptorr  r  	itertoolschainrk   rl   do_not_propagater  _add_actionr9   AddLowerDisplayInfoRemoveFromParserAddToParserrU  rV  r[   r   rX  r   r  r  clear)r   r$   r   rJ   r  r  r   
sub_parserr8   rn   ro   	added_argr   s               r   r   DynamicPositionalAction.__call__f  sZ   AYFY/D&&v.J 
	-	-e4DOO$8$8
:B  9 9 $ B BD
 
		$"2"2 T"D OO''(D(DE 	2//"%i 
2::	%gi.O.O ) 3 3	  

!416 2 @" RZZ'
!!# (r!   )r  r  r1  )r   r   r   r   r   r   r[  ra  r  r  r  r  r  r  r   r   r   s   @r   r  r  2  s^    C
 	C 	 	 	 	A$ A$r!   r  )+r   
__future__r   r   r   r  rA  r   r  r  rU  r   r  googlecloudsdk.callioper   r   r   r	   r
   r   googlecloudsdk.corer   r   r   r   googlecloudsdk.core.consoler   r   rO   r   r   objectr   	Exceptionr   r   r   with_metaclassABCMetarW  rT  r  r  r   r!   r   <module>r     s   )V '  ' 
   	  	 	 
 / ( 4 1 4 . * & # ' 4 2 
! 
H"" HVF 6	 ) ZX,, Z|	s11#++2:2L2L N 	6#@1 #@Lu$c001IK u$r!   