
    z                     n   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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\" 5       r " S S\5      r " S S\5      rS r " S S\5      r  " S S\5      r!S r"S r#S r$S r%S r&S r'S r( " S S \RR                  5      r*S!r+S" r,S# r-S$ r.\R^                  R`                  Rb                  Rd                  \R^                  R`                  Rb                  Rd                  \R^                  R`                  Rb                  Rd                  S%.r3SNS& jr4 " S' S(\5      r5 " S) S*\5      r6 " S+ S,\5      r7 " S- S.\5      r8S/ r9S0 r:S1r;S2 r<SOS3 jr=S4 r>SPS5 jr?SQS6 jr@SRS7 jrAS8 rBS9 rCSRS: jrDS; rES< rFS= rGS> rHS? rIS@ rJSA rK   SSSB jrLSRSC jrMSD rNSE rOSTSF jrPSG rQSH rR\R                  (       a  \TO\UrV\	R                  R                  \Y\	R                  R                  \Y\	R                  R                  \V\	R                  R                  \V\	R                  R                  \V\	R                  R                  \U\	R                  R                  \U\	R                  R                  \U\	R                  R                  \R                  \	R                  R                  \d\	R                  R                  \R                  \	R                  R                  \R\	R                  R                  S0riSUSI jrjSRSJ jrkSK rl " SL SM\5      rmg)Vz?Utilities for generating and parsing arguments from API fields.    )absolute_import)division)unicode_literalsN)messages)encoding)extra_types)arg_parsers)base)util)
properties)resource_property)http_encodingc                       \ rS rSrSrSrg)Error*   zBase exception for this module. N)__name__
__module____qualname____firstlineno____doc____static_attributes__r       5lib/googlecloudsdk/command_lib/util/apis/arg_utils.pyr   r   *   s    'r   r   c                   ,   ^  \ rS rSrSrU 4S jrSrU =r$ )UnknownFieldError/   z>The referenced field could not be found in the message object.c                    > [         [        U ]  SR                  U[	        U5      SR                  S UR                  5        5       5      5      5        g )Nz<Field [{}] not found in message [{}]. Available fields: [{}], c              3   8   #    U  H  oR                   v   M     g 7fNname).0fs     r   	<genexpr>-UnknownFieldError.__init__.<locals>.<genexpr>6   s     ;&:ff&:s   )superr   __init__format_GetFullClassNamejoin
all_fields)self
field_namemessage	__class__s      r   r)   UnknownFieldError.__init__2   sG    	
T+FMM)'2II;g&8&8&:;;	=>r   r   r   r   r   r   r   r)   r   __classcell__r1   s   @r   r   r   /   s    F> >r   r   c                     [        U [        5      (       a&  SR                  U R                  U R                  5      $ SR                  [        U 5      R                  [        U 5      R                  5      $ )Nz{}.{})
isinstancetyper*   r   r   )objs    r   r+   r+   9   sM    T>>#..#,,77	S	,,d3i.@.@	AAr   c                   ,   ^  \ rS rSrSrU 4S jrSrU =r$ )InvalidFieldPathError?   zCThe referenced field path could not be found in the message object.c                 `   > [         [        U ]  SR                  U[	        U5      U5      5        g )Nz7Invalid field path [{}] for message [{}]. Details: [{}])r(   r;   r)   r*   r+   )r.   
field_pathr0   reasonr1   s       r   r)   InvalidFieldPathError.__init__B   s+    	
/A	
-g6	?Ar   r   r3   r5   s   @r   r;   r;   ?   s    KA Ar   r;   c                   ,   ^  \ rS rSrSrU 4S jrSrU =r$ )ArgumentGenerationErrorH   zGGeneric error when we can't auto generate an argument for an api field.c                 J   > [         [        U ]  SR                  X5      5        g )Nz.Failed to generate argument for field [{}]: {})r(   rB   r)   r*   )r.   r/   r?   r1   s      r   r)    ArgumentGenerationError.__init__K   s     	
!418	
	#%r   r   r3   r5   s   @r   rB   rB   H   s    O% %r   rB   c                     UR                  S5      nUSS  H  n[        X5      R                  n M     [        XS   5      $ )a  Extract the field object from the message using a dotted field path.

If the field does not exist, an error is logged.

Args:
  message: The apitools message to dig into.
  field_path: str, The dotted path of attributes and sub-attributes.

Returns:
  The Field object.
.N)split	_GetFieldr8   )r0   r>   fieldsr%   s       r   GetFieldFromMessagerL   Q   sC     C &#2;a#((G 	72J	''r   c           
      v   U nUR                  S5      n[        U5       GHr  u  pE[        R                  " SU5      nU(       a  UR	                  5       u  pW[        U5      nOSn U R                  U5      nU(       a-  UR                  (       d  [        XSR                  U5      5      eO>UR                  (       a-  U[        U5      S-
  :  a  [        XSR                  U5      5      e[        X5      n U (       a  U(       a  U[        U 5      :  a  X   OSn U (       a  M  U[        U5      S-
  :  d  GM  [        U[        R                   5      (       a  UR#                  5       n GMF  [        XSR                  XXR"                  R$                  5      5      e   U $ ! [         a    [        X[        XP5      5      ef = f)aQ  Extract the value of the field given a dotted field path.

If the field_path does not exist, an error is logged.

Args:
  message: The apitools message to dig into.
  field_path: str, The dotted path of attributes and sub-attributes.

Raises:
  InvalidFieldPathError: When the path is invalid.

Returns:
  The value or if not set, None.
rG   z(.+)\[(\d+)\]$Nz5Index cannot be specified for non-repeated field [{}]   z3Index needs to be specified for repeated field [{}]z'[{}] is not a valid field on field [{}])rI   	enumeraterematchgroupsintfield_by_nameKeyErrorr;   r   repeatedr*   lengetattrr7   r   MessageFieldr8   r   )	r0   r>   root_messagerK   ir%   index_foundindexfields	            r   GetFieldValueFromMessager_   c   s    ,C &da((,a0K##%ha%jeeA##A&e ^^#CJJ1MO 	O 
 
AFa/#AHHKM 	M g!G;"'#g,"6Dg7q3v;?*	E800	1	1 **,#5VAzz**+- 	-G  P 
.;  A!*"3A"?A AAs   $F F8c                 6    Ub  [         R                  " X5      $ g r!   )r   PyValueToMessage)
field_typevalues     r   EncodeToMessagerd      s    
$$Z77r   c                 R   UR                  S5      nUSS  Hg  n[        X5      n[        X5      R                  nU(       d/  [        X5      R	                  5       nU(       a  U/n[        XU5        U(       a  US   OUn Mi     [        XS   5      R                  n[        U[        5      (       a  [        Xr5      n[        U[        5      (       aJ  [        U5       H;  u  p[        U[        5      (       d  M  [        X5      (       a  M.  [        Xy5      X('   M=     [        XS   U5        g)zSets the given field in the message object.

Args:
  message: A constructed apitools message object to inject the value into.
  field_path: str, The dotted path of attributes and sub-attributes.
  value: The value to set.
rG   NrH   r   )rI   rX   rJ   rV   r8   setattrr7   dictrd   listrO   )
r0   r>   rc   rK   r%   sub_messageis_repeatedrb   r[   items
             r   SetFieldInMessagerl      s     C &#2;a'%KG'00Kg)..0k	"mg+& +k!nG  *-22*tJ.EtU#	J	%	%j.J.J":4 $ 
'":u%r   c                     U (       d  gU nUR                  S5      nUSS  H  n[        X$S5      nU(       a  M    g   UR                  US   5        g)zResets the given field in the message object.

Args:
  message: A constructed apitools message object to inject the value into.
  field_path: str, The dotted path of attributes and sub-attributes.
NrG   rH   )rI   rX   reset)r0   r>   ri   rK   r%   s        r   ResetFieldInMessagero      sW     

+C &#2;a+$/K; 
 fRj!r   c                 *    U R                  S5      S   $ )zGets the child field name from the api field.

If api field path is multiple levels deep, return the last field name.
i.e. 'x.y.z' would return 'z'

Args:
  api_field: str, full api field path

Returns:
  str, child api field
rG   rH   )
rpartition)	api_fields    r   GetChildFieldNamers      s     
		c	"2	&&r   c                 X     U R                  U5      $ ! [         a    [        X5      ef = fr!   )rT   rU   r   )r0   r/   s     r   rJ   rJ      s2    1  ,,	 1
J
001s    )c                   (    \ rS rSrSrSrSrSrSrSr	g)		FieldType   mapr0   r^   json
json_valuer   N)
r   r   r   r   MAPMESSAGEFIELDJSON
JSON_VALUEr   r   r   r   rv   rv      s    #'
%	$*r   rv   additionalPropertiesc                     U R                   [        :X  a  U $  [        U R                  [        5      $ ! [         a     g f = fr!   )r#   ADDITIONAL_PROPSrL   r8   r   r^   s    r   _GetAdditionalPropsFieldr      s=    
ZZ##Luzz+;<<	 s   2 
??c                 <    U R                   [        R                  :H  $ r!   )r8   r   	JsonValuer   s    r   _IsJSONValueTyper     s    	{,,	,,r   c                    [        U [        R                  5      (       d  [        R                  $ [        U 5      nU=(       a-    [        U[        R                  5      =(       a    UR                  nU(       a  [        UR                  S5      OSnU(       a   [        U5      (       a  [        R                  $ U(       a  [        R                  $ [        U 5      (       a  [        R                  $ [        R                  $ )zDetermines whether the apitools field is a map, message, or field.

Args:
  field: messages.Field, apitools field instance

Returns:
  FieldType based on the apitools field type and the type of fields
    it contains.
rc   N)r7   r   rY   rv   r}   r   rV   rL   r8   r   r~   r{   r   r|   )r^   additional_props_fieldis_mapvalue_fields       r   GetFieldTyper     s     
E800	1	1??
 4E:" ,-x/D/DE,"++ 	  %%;%@%@'J $  %k22>>==r   )project	projectId
projectsIdc                     UR                  S5      (       a  USS nUR                  SS5      n[        XS5      nU(       d  U(       a  U" 5       nU(       d#  U(       a  [        R	                  US 5      " 5       nU$ )z+Gets the given argument from the namespace.--   N-_c                      g r!   r   r   r   r   <lambda>"GetFromNamespace.<locals>.<lambda>6  s    r   )
startswithreplacerX   DEFAULT_PARAMSget)	namespacearg_namefallbackuse_defaultsnormalized_arg_namerc   s         r   GetFromNamespacer   -  sh    |H ((c2
)$
7%	8JE	<x68E	,r   c                   $    \ rS rSrSrS rS rSrg)FileTypei:  z<An interface for custom type generators derived from a file.c                     gzAGenerates an argparse type function to use to parse the argument.Nr   r.   r^   s     r   GenerateTypeFileType.GenerateType=      r   c                     gz-The argparse action to use for this argument.storer   r.   s    r   ActionFileType.Action@      r   r   Nr   r   r   r   r   r   r   r   r   r   r   r   r   :  s    DLr   r   c                   $    \ rS rSrSrS rS rSrg)ArgJSONTypeiE  z?An interface for custom type generators for JSON (struct type).c                     gr   r   r   s     r   r   ArgJSONType.GenerateTypeH  r   r   c                     gr   r   r.   unused_repeateds     r   r   ArgJSONType.ActionK  r   r   r   Nr   r   r   r   r   r   E  s    GLr   r   c                   $    \ rS rSrSrS rS rSrg)ArgObjectTypeiP  zAn interface for custom type generators that bind directly to a message.

Like ArgDict, ArgObject type can only be generated one we know the type
of the message.
c                     gzoGenerates an argparse type function to use to parse the argument.

Args:
  field: The apitools field instance.
Nr   r   s     r   r   ArgObjectType.GenerateTypeW  r   r   c                     g)a3  The argparse action to use for this argument.

'store' is the default action, but sometimes something like 'append' might
be required to allow the argument to be repeated and all values collected.

Args:
  unused_repeated: whether or not the message is repeated

Returns:
  str, The argparse action to use.
r   r   r   s     r   r   ArgObjectType.Action^  s     r   r   Nr   r   r   r   r   r   P  s    r   r   c                   $    \ rS rSrSrS rS rSrg)RepeatedMessageBindableTypeim  a  An interface for custom type generators that bind directly to a message.

An argparse type function converts the parsed string into an object. Some
types (like ArgDicts) can only be generated once we know what message it will
be bound to (because the spec of the ArgDict depends on the fields and types
in the message. This interface allows encapsulating the logic to generate a
type function at the point when the message it is being bound to is known.
c                     gr   r   r   s     r   r   (RepeatedMessageBindableType.GenerateTypew  r   r   c                     g)zThe argparse action to use for this argument.

'store' is the default action, but sometimes something like 'append' might
be required to allow the argument to be repeated and all values collected.

Returns:
  str, The argparse action to use.
r   r   r   s    r   r   "RepeatedMessageBindableType.Action~  s     r   r   Nr   r   r   r   r   r   m  s    	r   r   c                    U (       a  U R                   OS nS nUR                  bm  UR                   Vs0 s H  oDR                  UR                  _M     nn[	        UR                  5       5      (       a  UnU$ [        UR                  5       5      nU$ U[        R                  R                  :X  a<  [        U R                  R                  5       5       Vs/ s H  n[        U5      PM     nnU$ s  snf s  snf r!   )variantchoices	arg_value	help_textanyvaluessortedkeysr   VariantENUMr8   namesEnumNameToChoice)r^   
attributesr   r   c
choice_mapr#   s          r   GenerateChoicesr     s    "EMM''#4>4F4FG4Fq++q{{*4FJG !!2!2!455zG 
. :??,-  
. (""'''289I9I9K2LM2L$%2LGM	. H Ns    C.C3c                     U R                   bA  U R                    Vs/ s H!  oR                  (       d  M  UR                  PM#     nnU(       a  U$ g s  snf r!   )r   hiddenr   )r   r   hidden_choicess      r   GenerateHiddenChoicesr     sF    #+5+=+=J+=akakk+=NJ	 Ks
   AA
store_truec                 H    U [         :H  =(       d    U [        R                  :H  $ r!   )
STORE_TRUEr	   StoreTrueFalseAction)actions    r   _IsStoreBoolActionr     s"    
J
 5
K44
46r   c                    UR                   (       a;  [        UR                   [        5      (       a  UR                   R                  U 5      nO>U (       a  U R                  OSnUR                   =(       d    [
        R                  US5      nUR                  nU[        :X  a  U(       a  U(       d  [        nSnU =(       a    U R                  =(       a    UR                  SLn[        U[        5      (       d  [        U[        5      (       ae  U(       a9  [        U R                  SR                  [        U5      R                   U5      5      eUR#                  U 5      nUR                  U 5      nX54$ U(       a  U(       a  [        U[$        5      n[        U[&        R(                  5      n	U(       d  U	(       a@  U(       a9  [        U R                  SR                  [        U5      R                   U5      5      eU(       a$  UR#                  5       nUR                  U 5      nX54$ U	(       d-  XV:w  a(  [&        R(                  " U[+        X5      [-        U5      S9nX54$ [        U[$        5      (       a8  [        U R                  SR                  [        U5      R                   5      5      eXV:X  a%  [        U R                  SR                  U5      5      eX54$ )a  Generates the type and action for a flag.

Translates the yaml type (or deault apitools type) to python type. If the
type is for a repeated field, then a function that turns the input into an
apitools message is returned.

Args:
  field: apitools field object flag is associated with
  attributes: yaml_arg_schema.Argument, data about flag being generated
  fix_bools: bool, whether to update flags to store_true action

Raises:
  ArgumentGenerationError: user cannot specify action for repeated field
  ArgumentGenerationError: cannot use a dictionary on a non-repeating field
  ArgumentGenerationError: append action can only be used for repeated fields

Returns:
  (str) -> Any, a type or function that returns input into correct type
  action, flag action used with a given type
NappendFzJType {0} cannot be used with a custom action. Remove action {1} from spec.)element_typer   r   z-Type {0} can only be used on repeated fields.z6{0} custom action can only be used on repeated fields.)r8   r7   r   r   r   TYPESr   r   boolr   rV   r   r   rB   r#   r*   r   r   r   r	   ArgListr   r   )
r^   r   	fix_bools	flag_typer   r   append_actionrV   is_repeatable_messageis_arg_lists
             r   GenerateFlagTyper     sJ   * __JOOX>>,,U3I$emm$G;599Wd#;I&$9V F-&LJ,?,?u,L(	=))Z	;-O-O#
**""(&i)A)A6"JL L e$F&&u-I@ 	? (4OPy+*=*=>k
;F%JJ$$*F4	?+C+CV$LN 	N 
!!#**51	$ 	 v6''"OE,N0<>	 	 )899
!

	&i1124 4 
!

@GGOQ Q 	r   c                     U (       a  U nOF[        U[        R                  5      (       a  SnO$[        U[        R                  5      (       a  UnOSnU(       a&  [        R
                  " UR                  SS5      5      $ g)zGets the metavar for specific flag.

Args:
  specified_metavar: str, metavar that is specified by user.
  flag_type: (str)->None, type function of the flag.
  flag_name: str, name of the flag

Returns:
  str | None, the flag's metavar
Nr   r   )r7   r	   ArgDictr   r   ConvertToAngrySnakeCaser   )specified_metavarr   	flag_namemetavars       r   
GetMetavarr     sc     G)[0011G)[0011GG44W__S#5NOOr   c           	      ~   [        XU5      u  pE[        U[        R                  5      (       a  SnSnO[	        X5      n[        U5      nU (       a5  U(       d.  U(       d'  UR                  (       d  [        U R                  S5      eUR                  n[        R                  " UR                  (       a  UOSU-   UR                  (       d  UOSU=(       d    SUR                  UR                  UR                  S9n	UR                   ["        :w  a  UR                   U	R$                  S'   ['        U5      (       d\  [)        UR*                  XH5      n
U
(       a  XR$                  S'   XIR$                  S'   XiR$                  S	'   U(       a  XyR$                  S
'   UR                  (       d  UR,                  U	R$                  S'   U	$ )a  Generates a flag for a single field in a message.

Args:
  field: The apitools field object.
  attributes: yaml_arg_schema.Argument, The attributes to use to
    generate the arg.
  fix_bools: True to generate boolean flags as switches that take a value or
    False to just generate them as regular string flags.
  category: The help category to put the flag in.

Raises:
  ArgumentGenerationError: When an argument could not be generated from the
    API field.

Returns:
  calliope.base.Argument, The generated argument.
NzqThe field is of an unknown type. You can specify a type function or a processor to manually handle this argument.r   r   )categoryr   	completerhelpr   defaultr   r8   r   r   required)r   r7   r	   r   r   r   	processorrB   r#   r   r
   Argumentis_positionalr   r   r   r   UNSPECIFIEDkwargsr   r   r   r   )r^   r   r   r   r   r   r   r   r#   argr   s              r   GenerateFlagr    si   $ 'u)D)	;..//GNe0G*:6N
9VJ4H4H "

 PQ Q 
		$&&dD4K)77xTw$$	# ;&&..CJJy	F	#	# ++Y=G%jj"JJv#JJy%3jj!"		!	!'00CJJz	*r   c           	         U R                   =(       a    USLnU(       a
  U" U5      nGOSnU(       a  UR                  5       nU R                  [        R                  R
                  :X  a  U R                  R                  5       nO/ n[        XtR                  5       5        U(       a  U Vs/ s H  n[        XH5      PM     nnO[        XA5      nU R                  [        R                  R
                  :X  a8  U R                  n	U(       a  U Vs/ s H  n[        XUS9PM     nnO
[        XUS9nU R                   (       a  U(       d  [        U[        5      (       d  U/nU$ s  snf s  snf )a  Coverts the parsed value into something to insert into a request message.

If a processor is registered, that is called on the value.
If a choices mapping was provided, each value is mapped back into its original
value.
If the field is an enum, the value will be looked up by name and the Enum type
constructed.

Args:
  field: The apitools field object.
  value: The parsed value. This must be a scalar for scalar fields and a list
    for repeated fields.
  repeated: bool, Set to False if this arg was forced to be singular even
    though the API field it corresponds to is repeated.
  processor: A function to process the value before putting it into the
    message.
  choices: {str: str} A mapping of argument value, to enum API enum value.

Returns:
  The value to insert into the message.
FN)valid_choices)rV   r   r   r   r   r   r8   r   CheckValidEnumNamesr   
_MapChoiceChoiceToEnumr7   rh   )
r^   rc   rV   r   r   arg_repeatedr  	api_namesvts
             r   ConvertValuer  O  s   , 9HE$9,eEMllnm	(**//	/JJ$$&		)^^%56	167AG'77*}}((---
**a	JOP%Qa-@%PU]C
^^LE41H1H GE	, 8 Qs   +E E%c                 J    Ub	  US-   U -   nOU n[         R                  " U5      $ )Nr   )format_utilFlagNameFormat)r   flag_prefixr#   s      r   GetFlagNamer    s-    x'DD		#	#D	))r   c                     / n[        U 5       H2  u  p4U[        U5      :  d  X   U:w  a    U$ UR                  X   5        M4     U$ )z0Gets the long common sub list between two lists.)rO   rW   r   )longest_arrarrnew_arrr[   longest_substr_segs        r   _GetCommonPrefixr    sO    '(5aCH}"44 
. NN36  6
 
.r   c                     U (       d  gU S   R                  S5      nU  H  nUR                  S5      n[        X5      nM!     SR                  U5      =(       d    S$ )a.  Gets shared parent of api_fields.

For a list of fields, find the common parent between them or None.
For example, ['a.b.c', 'a.b.d'] would return 'a.b'

Args:
  api_fields: [list], list of api fields that we need to find parent

Returns:
  str | None, shared common parent or None if one is not found
Nr   rG   )rI   r  r,   )
api_fieldslongest_parentr^   substrs       r   GetSharedParentr    sV     
a=&&s+.e[[F%n=N  
.	!	)T)r   c                    U(       a  [        U5      S-   OSn/ nU  H  nU(       a0  UR                  U5      (       d  [        SR                  XA5      5      eXBS R	                  S5      nU=(       a    US   nU(       a  U(       a  SR                  X45      nOU=(       d    UnU(       d  M  UR                  U5        M     U$ )a  Gets first child for api_fields.

For a list of fields, supply the full api_field up through the first child.
For example:
    ['a.b.c', 'a.b.d.e.f'] with shared parent 'a.b'
    returns children ['a.b.c', 'a.b.d']

Args:
  api_fields: [str], list of api fields to get children from
  shared_parent: str | None, the shared parent between all api fields

Returns:
  [str], list of the children api_fields
rN   r   z*Invalid parent: {} does not start with {}.NrG   )rW   r   
ValueErrorr*   rI   r,   r   )r  shared_parentstart_indexchild_fieldsrr   childrenfirst_childr^   s           r   _GetFirstChildFieldsr#    s      +8M"Q&Q+,iY11-@@CJJ
$ % % &,,S1H*x{Khh34e*{eu%    
r   c                 F    U  H  nUR                  U5      (       d  M    g   g)a  Get api fields of arguments when at least one is specified.

Args:
  specified_fields: List[str], list of api fields that have been specified.
  message_field: str, message field we are determining if specified

Returns:
  bool, whether the message field is specified.
TF)r   )specified_fieldsmessage_fieldspecified_fields      r   _IsMessageFieldSpecifiedr(    s'     *o!!-00 * r   c                     / nU  H6  nUR                  U5      (       d  M  UR                  UR                  5        M8     U$ )a?  Get api fields of arguments when at least arg is specified in namespace.

Args:
  arguments: List[yaml_arg_schema.YAMLArgument], list of arguments we want
    to see if they are specified.
  namespace: The parsed command line argument namespace.

Returns:
  List[str] of api_fields that are specified in the namespace.
)IsApiFieldSpecifiedextendr  )	argumentsr   r%  r   s       r   _GetSpecifiedApiFieldsInGroupr-    s?     c
y))cnn-  
r   c                    UR                   (       a  UR                  U5      (       d  g[        UR                  UR                  S9n[        UR                  U5      nU H   n[        XE5      (       a  M  [        X5        M"     g)a6  Clears message fields associated with this mutex ArgGroup.

Clearing fields is necessary when using read_modify_update. This prevents
more than one field in a mutex group from being sent in a request message.
Apitools does not contain information on which fields are mutually exclusive.
Therefore, we use the api_fields in the argument group to determine which
fields should be mutually exclusive.

Args:
  message: The api message that needs to have fields cleared
  namespace: The parsed command line argument namespace.
  arg_group: yaml_arg_schema.ArgGroup, arg
N)r  )	mutexr*  r#  r  parent_api_fieldr-  r,  r(  ro   )r0   r   	arg_groupfirst_child_fieldsr%  rr   s         r   ClearUnspecifiedMutexFieldsr3    sw     
	 = =i H H

 ,)*D*DF 39& &i $$4@@'-	 &r   c                     [        U[        R                  5      (       a  UR                  5       nU R	                  X5      $ r!   )r7   sixstring_typeslowerr   )r   rc   s     r   r  r    s/    s''((KKME	U	""r   c                 r    [        U [        5      (       a  U(       a  U $ U (       a  U S   $ S $ U(       a  U /$ U $ )Nr   )r7   rh   )r   plurals     r   
_ListValuer:    s7    m6!9(D(F8)6)r   c                     / n/ nU  H@  nUR                  UR                  US95        UR                  UR                  5       5        MB     X#4$ )N)parent_collection)r   ParentName)refsr<  parentsr   refs        r   _ParseParentsrB  (  sM    '
%cNN

%6
79	LL  
r   c                 h    U(       a  U R                  5       OU R                  5       n[        XU5      $ r!   )RelativeNamer>  rX   )rA  pdefault_relative_namedefault_vals       r   	_GetParamrH  2  s'    &;  "+		%%r   c           	         U=(       d    0 nUR                  5       nSn[        U [        5      (       d  SnU /n U(       at  U(       am  U(       af  UR                  R                  UR
                  R                  :w  a8  [        XR
                  R                  5      u  p[        X$[        X5      5        SnU(       a  U(       a  UR                  O/ n	U	 HM  n
UR                  U
/ 5      nU(       d  U  Vs/ s H  n[        XU5      PM     nn[        X*[        X5      5        MO     UR                  5        H  u  p[        X-[        X5      5        M     gs  snf )aU  Set fields in message corresponding to a resource.

Args:
  refs: googlecloudsdk.core.resources.Resource or list, the resource
    reference.
  method: the API method.
  message: apitools Message object.
  message_resource_map: {str: str}, A mapping of API method parameter name to
    resource ref attribute, if any
  request_id_field: str, the name that the ID of the resource arg takes if the
    API method params and the resource params don't match.
  use_relative_name: Used ref.RelativeName() if True, otherwise ref.Name().
  is_primary_resource: Determines if we should use method.params.
TFN)copyr7   rh   resource_argument_collectiondetailed_paramsrequest_collectionrB  	full_namerl   r:  paramspoprH  items)r?  methodr0   message_resource_maprequest_id_fielduse_relative_nameis_primary_resourcer9  r   rO  rE  r   rA  message_field_name	ref_params                  r   ParseResourceIntoMessagerY  7  s!   " .3-224&	D$		F6D .6))99		"	"	2	23&?&?&I&IJKDgE1JKF"':6==&a!%%a,F@DE	#"34fEg*V"<=	  (<'A'A'C#g 35 (D Fs   1Ec           	          U=(       d    0 n[         R                  " U5       H%  u  p#[        X5      n[        X[	        XC5      5        M'     g)zSet fields in message corresponding to a dict of static field values.

Args:
  message: the Apitools message.
  static_fields: dict of fields to values.
N)r5  	iteritemsrL   rl   r  )r0   static_fieldsr>   rc   r^   s        r   ParseStaticFieldsIntoMessager]  i  s@      %2-==7j4E\%79 8r   c                    [        U5      [        U 5      :X  a  U$ UR                  nU R                  UR                  5      nUR                  [        U5      :w  aU  UR                  5       nUR	                  5        H1  n UR                  [        U5      :X  a  USUR
                  -   -  n  OM3     [        XU5        U $ ! [         a     MP  f = f)a  Sets fields in message based on an existing message.

This function is used for get-modify-update pattern. The request type of
update requests would be either the same as the response type of get requests
or one field inside the request would be the same as the get response.

For example:
1) update.request_type_name = ServiceAccount
   get.response_type_name = ServiceAccount
2) update.request_type_name = updateInstanceRequest
   updateInstanceRequest.instance = Instance
   get.response_type_name = Instance

If the existing message has the same type as the message to be sent for the
request, then return the existing message instead. If they are different, find
the field in the message which has the same type as existing_message, then
assign exsiting message to that field.

Args:
  message: the apitools message to construct a new request.
  existing_message: the exsting apitools message returned from server.
  method: APIMethod, the method to generate request for.

Returns:
  A modified apitools message to be send to the method.
rG   )r8   request_fieldrT   message_typer-   r#   AttributeErrorrl   )r0   existing_messagerR  r>   r^   nested_messagenested_fields          r   ParseExistingMessageIntoMessagere  w  s    6 

tG},
 ##*


 4 4
5%
4 011 '')N&113$$-=(>>
l///
/*
 ? 4 G)9:	.	  s   ?+B>>
CCc                    U (       a?  U Vs/ s H1  nX ;   a  M
  [        [        R                  " U5      5      U ;   a  M/  UPM3     nnO/ nU(       a4  [        R                  " SR                  SR                  U5      5      5      egs  snf )zDEnsures the api_name given in the spec matches a value from the API.z {} is/are not valid enum values.r   N)ChoiceToEnumNamer5  	text_typer	   ArgumentTypeErrorr*   r,   )r  choices_valuesr#   bad_choicess       r   r  r    s    $2 0ND -MM$!$-. NK 0K K

'
'*11$))K2HIK K 0s   	B!BBc                 j   U c  g[        U 5      nU=(       d*    UR                  5        Vs/ s H  n[        U5      PM     snn UR                  U5      $ s  snf ! [         aN    [
        R                  " SR                  U[        U5      SR                  S [        U5       5       5      S95      ef = f)z6Converts the typed choice into an apitools Enum value.Nz;Invalid {item}: {selection}. Valid choices are: [{values}].r   c              3   $   #    U  H  ov   M     g 7fr!   r   )r$   r   s     r   r&   ChoiceToEnum.<locals>.<genexpr>  s     >(=1Q(=s   )rk   	selectionr   )
rg  r   r   lookup_by_namerU   r	   ri  r*   r,   r   )choice	enum_type	item_typer  r#   ns         r   r  r    s    ^	&	!$  D1:1BC1BA$Q'1BC A##D)) D 
 A

'
'ELL&t,99>}(=>> 	M 	@A AAs   AA AB2c                 B    U R                  SS5      R                  5       $ )zDConverts a typeable choice to the string representation of the Enum.r   r   )r   upper)rq  s    r   rg  rg    s    	S	!	'	'	))r   c                 B    U R                  SS5      R                  5       $ )z:Converts the name of an Enum value into a typeable choice.r   r   )r   r7  r"   s    r   r   r     s    	c3		%	%	''r   c                 4   0 nSn[         R                  " SR                  U5      U R                  =(       d    S[         R                  5      nU(       d  U$ U R                  UR                  5       S R                  5        H  n[         R                  " SU5      nU(       a4  UR                  S5      nUR                  S5      R                  5       X#'   MU  U(       d  M^  UR                  5       nU(       d  Mw  UR                  US5      nUS-   U-   X#'   M     U$ )a(  Gets the help text for the fields in the request message.

Args:
  message: The apitools message.
  section: str, The section to extract help data from. Fields is the default,
    may also be Values to extract enum data, for example.

Returns:
  {str: str}, A mapping of field name to help text.
Nz
^\s+{}:.*$ z^\s+(\w+): (.*)$rN   r    )rP   searchr*   r   	MULTILINEend
splitlinesrQ   groupstripr   )r0   sectionfield_helpscurrent_fieldrQ   line	to_appendcurrent_texts           r   FieldHelpDocsr    s     +-
))M((1OO)r2<<9%	ooeiikl+668dHH($/Ekk!nm#(;;q>#7#7#9k 	**,i	"}b9%1C%7)%C" 9 
r   c                     Uc  / nX;   a  0 $ UR                  U 5        [        U 5      n0 nU R                  5        GH)  nSUR                  UR                  5      0nUR
                  US'   UR                  [        R                  R                  :X  a9  UR                  R                  US'   [        UR                  US9nU(       a  XeS'   OUR                  US'   UR                  [        R                  R                  :X  aS  [        UR                  S5      nUR                  R                  5        Vs0 s H  nXR                  U5      _M     snUS'   XSUR                  '   GM,     UR                  5         U$ s  snf )zGets the recursive representation of a message as a dictionary.

Args:
  message: The apitools message.
  definitions: A list of message definitions already encountered.

Returns:
  {str: object}, A recursive mapping of field name to its data.
descriptionrV   r8   )definitionsrK   Valuesr   )r   r  r-   r   r#   rV   r   r   r   r|   r8   r   GetRecursiveMessageSpecr   r   rP  )	r0   r  r  datar^   
field_datarK   	enum_helprt  s	            r   r  r    sN    K IWg&+	$!!#e!<=J"^^Jz}}((000 ::..j&uzz{Kf	%8 ==j	(**//	/!%**h7	*/***:*:*<!>*<Q "#MM!$4!4*<!>
9 " $  //	+!>s   5E;c                 f    U =(       a)    U R                  S5      =(       d    U R                  S5      $ )z@Determines if the given field is output only based on help text.z[Output Only]z@OutputOnly)r   endswith)r   s    r   IsOutputFieldr  9  s0    	 
)?+ (')r   c                       \ rS rSrSrSr          SS jrS rS rS r	S	 r
S
 r\S 5       r\S 5       r\S 5       r\S 5       r\S 5       r\S 5       r\S 5       rSrg)ChoiceEnumMapperi@  a  Utility class for mapping apitools Enum messages to argparse choice args.

Dynamically builds a base.Argument from an enum message.
Derives choice values from supplied enum or an optional custom_mapping dict
(see below).

Class Attributes:
 choices: Either a list of strings [str] specifying the commandline choice
     values or an ordered dict of choice value to choice help string mappings
     {str -> str}
 enum: underlying enum whos values map to supplied choices.
 choice_arg: base.Argument object
 choice_mappings: Mapping of argparse choice value strings to enum values.
 custom_mappings: Optional dict mapping enum values to a custom
   argparse choice value. To maintain compatiblity with base.ChoiceAgrument(),
   dict can be either:
   {str-> str} - Enum String value to choice argument value i.e.
   {'MY_MUCH_LONGER_ENUM_VALUE':'short-arg'}
   OR
   {str -> (str, str)} -  Enum string value to  tuple of
   (choice argument value, choice help string) i.e.
   {'MY_MUCH_LONGER_ENUM_VALUE':('short-arg','My short arg help text.')}
zcustom_mappings must be a dict of enum string values to argparse argument choices. Choices must be either a string or a string tuple of (choice, choice_help_text): [{}]Nc                    [        U[        R                  5      (       d  [        SR	                  U5      5      eXl        X l        X0l        Xl        Ub*  [        U5      (       d  [        SR	                  U5      5      eXl        U R                  U l        U R                  5         [        R                  " UU R                   UUUUUU	U
US9
U l        g)ad  Initialize ChoiceEnumMapper.

Args:
  arg_name: str, The name of the argparse argument to create
  message_enum: apitools.Enum, the enum to map
  custom_mappings: See Above.
  help_str: string, pass through for base.Argument,
    see base.ChoiceArgument().
  required: boolean,string, pass through for base.Argument,
      see base.ChoiceArgument().
  action: string or argparse.Action, string, pass through for base.Argument,
      see base.ChoiceArgument().
  metavar: string,  string, pass through for base.Argument,
      see base.ChoiceArgument()..
  dest: string, string, pass through for base.Argument,
      see base.ChoiceArgument().
  default: string, string, pass through for base.Argument,
      see base.ChoiceArgument().
  hidden: boolean, pass through for base.Argument,
      see base.ChoiceArgument().
  hidden_choices: list, pass through for base.Argument,
      see base.ChoiceArgument().
  include_filter: callable, function of type string->bool used to filter
      enum values from message_enum that should be included in choices.
      If include_filter returns True for a particular enum value, it will be
      included otherwise it will be excluded. This is ignored if
      custom_mappings is specified.

Raises:
  ValueError: If no enum is given, mappings are incomplete
  TypeError: If invalid values are passed for base.Argument or
   custom_mapping
zInvalid Message Enum: [{}]Nz-include_filter must be callable received [{}])help_strr   r   r   destr   r   r   )r7   r   
_EnumClassr  r*   	_arg_name_enum_custom_mappings_hidden_choicescallable	TypeError_filter_filtered_enum_ValidateAndParseMappingsr
   ChoiceArgumentr   _choice_arg)r.   r   message_enumcustom_mappingsr  r   r   r   r  r   r   r   include_filters                r   r)   ChoiceEnumMapper.__init__]  s    ^ lH$7$7883::<HIINJ+)!(>*B*BELL
   "L**D""$**%
'Dr   c                    U R                   (       Ga  [        U R                   [        5      (       d.  [        U R                  R                  U R                   5      5      e[        U R                   Vs/ s H  oR                  PM     sn5      n[        U R                   R                  5       5      U-
  nU(       aQ  [        SR                  SR                  U R                   R                  5       5      SR                  U5      5      5      e U R                  5         GO [        U R                  5      (       aC  U R                   Vs/ s H&  o@R                  UR                  5      (       d  M$  UPM(     snU l        U R                    Vs0 s H  n[#        UR                  5      U_M     snU l        [&        R(                  " U R$                  5       VVs0 s H  u  pUR                  U_M     snnU l        [-        U R$                  R                  5       5      U l        U R0                  (       a  [        U R.                  5      R3                  U R0                  5      (       dM  [        SR                  SR                  U R0                  5      SR                  U R.                  5      5      5      eggs  snf ! [        [        4 a    U R                  5          Nf = fs  snf s  snf s  snnf )a:  Validates and parses choice to enum mappings.

Validates and parses choice to enum mappings including any custom mappings.

Raises:
  ValueError: custom_mappings does not contain correct number of mapped
    values.
  TypeError: custom_mappings is incorrect type or contains incorrect types
    for mapped values.
zScustom_mappings [{}] may only contain mappings for enum values. invalid values:[{}]r   z2hidden_choices [{}] must be subset of choices [{}]N)r  r7   rg   r  _CUSTOM_MAPPING_ERRORr*   setr  r#   r   r  r,   _ParseCustomMappingsFromTuples_ParseCustomMappingsFromStringsr  r  r  r   _choice_to_enumr5  r[  _enum_to_choicer   _choicesr  
issuperset)r.   xenum_stringsdiffeys         r   r  *ChoiceEnumMapper._ValidateAndParseMappings  sU    --t44&&--d.C.CDF 	F$**5*Q&&*56l&&++-.=d	 AAG!YYt'<'<'A'A'CD!YYt_B./ 	//++-
 
$,,		zz
!!\\!&&%9Az
 &&&a 166
"A
%&d mmD$8$899da &&!)9d T116689dm**4+?+?@@@GG		$../4==1IKL 	L A 9 6 $ /,,./

s0   3J3J8 #K/K K#K(8 KKc                 2   0 U l         0 U l        [        R                  " 5       U l        [        [        R                  " U R                  5      5       HB  u  nu  p#U R                  U5      U R                   U'   X R                  U'   X0R                  U'   MD     g)a  Parses choice to enum mappings from custom_mapping with tuples.

 Parses choice mappings from dict mapping Enum strings to a tuple of
 choice values and choice help {str -> (str, str)} mapping.

Raises:
  TypeError - Custom choices are not not valid (str,str) tuples.
N)
r  r  collectionsOrderedDictr  r   r5  r[  r  r  )r.   enum_stringrq  r  s       r   r  /ChoiceEnumMapper._ParseCustomMappingsFromTuples  s     DD++-DM+1d++,,.''f%)ZZ%<d6"*0;'&mmF	,.r   c                    0 U l         / U l        [        [        R                  " U R
                  5      5       H  u  p[        U[        R                  5      (       d.  [        U R                  R                  U R
                  5      5      eU R                  U5      U R                   U'   U R                  R                  U5        M     U R
                  U l        g)zParses choice to enum mappings from custom_mapping with strings.

 Parses choice mappings from dict mapping Enum strings to choice
 values {str -> str} mapping.

Raises:
  TypeError - Custom choices are not strings
N)r  r  r   r5  r[  r  r7   r6  r  r  r*   r  r   r  )r.   r  choice_strings      r   r  0ChoiceEnumMapper._ParseCustomMappingsFromStrings  s     DDM&,d++,'."s'7'788&&--d.C.CDF 	F,0JJ{,Cd=)
mm=)'.  00Dr   c                 `    U R                   R                  [        R                  " U5      5      $ )z2Converts an enum value to a choice argument value.)r  r   r5  rh  )r.   
enum_values     r   GetChoiceForEnum!ChoiceEnumMapper.GetChoiceForEnum  s"    ##CMM*$=>>r   c                 8    U R                   R                  U5      $ )z1Converts a mapped string choice value to an enum.)r  r   )r.   choice_values     r   GetEnumForChoice!ChoiceEnumMapper.GetEnumForChoice  s    ##L11r   c                     U R                   $ r!   )r  r   s    r   r   ChoiceEnumMapper.choices  s    ==r   c                     U R                   $ r!   )r  r   s    r   enumChoiceEnumMapper.enum	  s    ::r   c                     U R                   $ r!   )r  r   s    r   filtered_enumChoiceEnumMapper.filtered_enum  s    r   c                     U R                   $ r!   )r  r   s    r   
choice_argChoiceEnumMapper.choice_arg  s    r   c                     U R                   $ r!   )r  r   s    r   choice_mappings ChoiceEnumMapper.choice_mappings  s    r   c                     U R                   $ r!   )r  r   s    r   r   ChoiceEnumMapper.custom_mappings  s       r   c                     U R                   $ r!   )r  r   s    r   r  ChoiceEnumMapper.include_filter  s    <<r   )
r  r  r  r  r  r  r  r  r  r  )
NNFNNNNFNN)r   r   r   r   r   r  r)   r  r  r  r  r  propertyr   r  r  r  r  r  r  r   r   r   r   r  r  @  s    .5  $""F'P/Lb'$1*?2             ! !  r   r  )NF)T)TN)NNNr!   )NNTF)rq  N)Fields)nr   
__future__r   r   r   r  r  rP   apitools.base.protorpcliter   apitools.base.pyr   r   googlecloudsdk.callioper	   r
    googlecloudsdk.calliope.conceptsr   r  googlecloudsdk.corer   googlecloudsdk.core.resourcer   googlecloudsdk.core.utilr   r5  objectr   	Exceptionr   r   r+   r;   rB   rL   r_   rd   rl   ro   rs   rJ   Enumrv   r   r   r   r   VALUEScorer   Getr   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r#  r(  r-  r3  r  r:  rB  rH  rY  r]  re  r  r  rg  r   PY2longrS   
_LONG_TYPEr   DOUBLEfloatFLOATINT64UINT64SINT64INT32UINT32SINT32STRINGrh  BOOLr   BYTESEncoder   r|   r   r  r  r  r  r   r   r   <module>r     s    F &  '   	 / % ( / ( @ * : 2 
 hI 
> >BAE A%e %($9x&8"*'1		  * -D (..33;;??)0055==AA * 1 1 6 6 > > B B
v & F :& : 
6
K\8:z2j**,#L"$.D#*&
 JNFJ16/5d91h
KA"*
(
 WWT#
 UEJZZCSSS]]4 M00 +d)	0!H$N)_v _r   