
    \              	          d Z ddlmZ ddlmZ ddlmZ ddlZddlmZ ddlm	Z
 ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlZdZdZdZ G d dej6                        Z G d de      Z eedei       ee      dZ G d d ej>                  dg d            Z e e ddiee      iZ! G d dejD                        Z#d  Z$d! Z% G d" d#e      Z&d$ Z'y)%z completers for resource library.    )absolute_import)division)unicode_literalsN)messages)resource)
completers)	arg_utils)registry)resource_parameter_info)
exceptions)log)
properties)	resourcesnamecloudresourcemanager.projects	projectIdc                       e Zd ZdZy)Errorz!Base error class for this module.N__name__
__module____qualname____doc__     :lib/googlecloudsdk/command_lib/util/concepts/completers.pyr   r   *   s    )r   r   c                   *    e Zd ZdZddZd Zd Zd Zy)ParentTranslatora>  Translates parent collections for completers.

  Attributes:
    collection: str, the collection name.
    param_translation: {str: str}, lookup from the params of the child
      collection to the params of the special parent collection. If None,
      then the collections match and translate methods are a no-op.
  Nc                 (    || _         |xs i | _        y N)
collectionparam_translation)selfr!   r"   s      r   __init__zParentTranslator.__init__8   s     DO.4"Dr   c                     | j                   r>t        j                  | j                         D ]  \  }}|j                  |      ||<   ||=  |S )zETranslate from original parent params to params that match the child.)r"   six	iteritemsget)r#   params
orig_param	new_params       r   ToChildParamszParentTranslator.ToChildParams<   sL    #&==1G1G#H
*i#ZZ	2z9 $I Mr   c                     i }t        j                  | j                        D ]'  \  }}	 |j                  |       t        ||d      ||<   ) |S # t        $ r Y 7w xY w)zCGet dict for translating parent params into the given message type.N)r&   r'   r"   field_by_nameKeyErrorgetattr)r#   messagerefmessage_resource_mapr*   special_params         r   MessageResourceMapz#ParentTranslator.MessageResourceMapD   sn     &)]]43I3I%J!
Mj)
 *1mT)J:& &K    s   A	AAc                 r   |D ci c].  }| j                   j                  ||      |j                  |      0 }}t        j                  |      D ]<  \  }}| j                   j                  ||      }|s%|j                  |d      r8|||<   > 	 t        j                  t
        j                  t
        j                  j                  | j                        d|d      S c c}w # t
        j                  $ r@}t        j                  t        j                  |      j                                Y d}~yd}~ww xY w)a  Parse the parent resource from parameter info and aggregations.

    Args:
      parent_params: [str], a list of params in the current collection's parent
        collection.
      parameter_info: the runtime ResourceParameterInfo object.
      aggregations_dict: {str: str}, a dict of params to values that are
        being aggregated from earlier updates.

    Returns:
      resources.Resource | None, the parsed parent reference or None if there
        is not enough information to parse.
    N collection_infosubcollectionparam_valuesendpoint_url)r"   r(   GetValuer&   r'   r   ResourceREGISTRYGetCollectionInfor!   r   r   info	text_typerstrip)	r#   parent_paramsparameter_infoaggregations_dictpr;   valuetranslated_namees	            r   ParsezParentTranslator.ParseS   s      A 	""1a(.*A*A!*DD    MM"345..221a8o	|''>(-_% 5


#,,>>tO#  " ?? 	hhs}}Q&&()s   3CAC# #D666D11D6r    )r   r   r   r   r$   r,   r5   rK   r   r   r   r   r   .   s    5 !r   r   
projectsId)rL   r   c                       e Zd ZdZy)CollectionConfigzAStores data about special collections for configuring completion.Nr   r   r   r   rN   rN      s     Jr   rN   )static_paramsid_field
param_namefilterzlifecycleState:ACTIVEc                        e Zd ZdZ	 d fd	Zed        Zd Zd Zd Z	d Z
d Z	 	 dd	Z	 	 dd
Zd Z	 	 ddZddZddZd Z	 	 ddZd Z xZS )ResourceArgumentCompleterz?A completer for an argument that's part of a resource argument.c                     || _         || _        |xs i | _        |xs t        | _        |j
                  }|j                  }	t        t        | &  d||	|dd| y)zInitializes.T)r!   api_versionparam	parse_allNr   )
resource_spec_method_static_paramsDEFAULT_ID_FIELDrP   	full_namerV   superrT   r$   )r#   rY   r9   methodrO   rP   rW   kwargscollection_namerV   	__class__s             r   r$   z"ResourceArgumentCompleter.__init__   so     'DDL'-2D0 0DM%//O!--K	
#T3 "	
 r   c                     | j                   S )zGets the list method for the collection.

    Returns:
      googlecloudsdk.command_lib.util.apis.registry.APIMethod, the method.
    )rZ   r#   s    r   r_   z ResourceArgumentCompleter.method   s     <<r   c                 >    | j                   j                  d      dd S )z(Get the parent params of the collection.r7   N)r9   	GetParamsrd   s    r   _ParentParamsz'ResourceArgumentCompleter._ParentParams   s     ))"-cr22r   c                 .   | j                   j                  d      d   }t        | j                  j                        D ]1  \  }}| j                  j                  |j                        |k(  s/|} n d}i }t        | j                  j                  d|       D ]z  \  }}t        | j                  |j                        }|r+|df|| j                  j                  |j                        <   Sd|| j                  j                  |j                        <   | |S )z*Helper function to build dict of updaters.r7   rf   r   NT)NF)r9   rg   	enumeraterY   
attributes	ParamNamer   CompleterForAttribute)r#   final_parami	attributeattribute_idxupdaters	completers          r   _GetUpdatersz&ResourceArgumentCompleter._GetUpdaters   s    &&004R8K!$"4"4"?"?@9				%	%inn	5	D A
 mH!%%n}579'(:(:INNKi	BKBFBH##--inn=>BI##--inn=>7 Or   c                     |j                   j                  |j                        }| j                         }t	        j
                  ||||| j                        S )zBuilds a ResourceParameterInfo object.

    Args:
      parsed_args: the namespace.
      argument: unused.

    Returns:
      ResourceParameterInfo, the parameter info for runtime information.
    )rr   r!   )CONCEPTSArgNameToConceptInfodestrt   r   ResourceParameterInfor!   )r#   parsed_argsargumentresource_inforr   s        r   ParameterInfoz'ResourceArgumentCompleter.ParameterInfo   sO      ((==hmmLM  "H"88{Hx??$ $r   c                    t        | j                  dd D cg c]  }|j                   c}      }t        |D cg c]  }|j                   c}      }| j                  j                  D ]U  }t        | j                  |j                        s$|j                  | j                  j                  |j                            W |j                  |      S c c}w c c}w )zEValidates that parent attributes values exitst before making request.Nrf   )	set
parametersr   rY   rk   rm   addattribute_to_params_mapissubset)r#   aggregationsrG   parameters_needing_resolutionaresolved_parametersrp   s          r   ValidateAttributeSourcesz2ResourceArgumentCompleter.ValidateAttributeSources   s    $'"9M(N9MA9M(N$O!|<|!qvv|<=''22		t119>>	B66y~~F	H 3 )112EFF )O<s
   CCc                 .   | j                   y | j                  |      sy t        j                  dj	                  | j
                  j                  d      D cg c]  }||j                  |      f c}|D cg c]  }|j                  |j                  f c}|j                  j                               | j                  ||      }	 | j                  |||      }	 | j                   j3                  |      }| j                   j4                  }|D 	cg c]  }	| j7                  |	||||       }
}	t        j                  dj	                  |
D cg c]  }|j9                          c}             |
D cg c]!  }| jA                  |j9                               # c}S c c}w c c}w # t        $ r}t        j                   j"                  j$                  j'                         r t        j                  t)        j*                  |      j-                                t/        dj	                  t1        |      t)        j*                  |      j-                                     d }~ww xY wc c}	w c c}w # t        $ r}t        j                   j"                  j$                  j'                         r t        j                  t)        j*                  |      j-                                t;        |t<        j>                        rEt/        dj	                  t1        |      t)        j*                  |      j-                                     t/        dj	                  |t1        |      t)        j*                  |      j-                                     d }~ww xY wc c}w )	Nz9Cache query parameters={} aggregations={}resource info={}r7   )parent_translatorz0Could not build query to list completions: {} {})rE   r   r   zcache items={}zVUpdate query failed, may not have enough information to list existing resources: {} {}zUpdate query [{}]: {} {})!r_   r   r   rA   formatr9   rg   r=   r   rH   r|   attribute_to_args_map_GetParentTranslatorBuildListQuery	Exceptionr   VALUEScoreprint_completion_tracebacksGetBoolr&   rB   rC   r   typeCallr!   _ParseResponseRelativeName
isinstancer   ValidationErrorStringToRow)r#   rE   r   rG   r   queryrJ   responseresponse_collectionritemsro   items                r   Updatez ResourceArgumentCompleter.Update   s   {{((6HH	!6**44R8:8 ((+,8:(451affagg5((>>	@A 11.,O/!!.,4E " Ge6!!%(h KK22
 !	" !1	 ""1&92@0<5F # H !	  "
 
hh&&%*
+U1>>U
+- . ?DDedDT..01eDDK:5  /						;	;	C	C	E	hhs}}Q&&()DKK
q'3==#**,. / /	/" , 6						;	;	C	C	E	hhs}}Q&&() 
Ax//	0 55;VQq!1!8!8!:6<= 	= ,33
a#--*1135 6 66 Esb   F7F$	F) 5I2 I(0 I2 I-'I2 6&N)	I%2B.I  I%(
I2 2
N<DN

Nc                     | j                  |||      }|j                  }|D ]  }t        ||d      }	|	|	||<    t        || j                  d      }
t        j
                  j                  |
|j                  |      S )z:Gets a resource ref from a single item in a list response.r   r   Nr7   )r!   r)   )_GetParamValuesFromParentdetailed_paramsr0   rP   r   r?   rK   r]   )r#   r   r   rE   r   r   r;   param_namesrW   vallines              r   r   z(ResourceArgumentCompleter._ParseResponse!  s     11\+ 2 -L &55KHeT*c	!U 
 8T]]B/D##,66| $ M Mr   c                 |    | j                  |||      }|si S |j                         }|r|j                  |      S |S )Nr   )	GetParentAsDictr,   )r#   rE   r   r   
parent_refr)   s         r   r   z3ResourceArgumentCompleter._GetParamValuesFromParent2  sL    \2C   EJi F,,V44Mr   c                 p    i }|g n|}|D ](  }|j                   s|j                   ||j                  <   * |S )z:Build a {str: str} dict of name to value for aggregations.)rH   r   )r#   r   rF   aggregations       r   _GetAggregationsValuesDictz4ResourceArgumentCompleter._GetAggregationsValuesDict=  sF    %-2<L#			.9.?.?+**+ $ r   c                 Z   | j                   }|y |j                                }t        j                  | j                        D ]  \  }}t        j                  |||        | j                  |||      }|s|S i }	|r|j                  ||      }	t        j                  ||||	d       |S )a-  Builds a list request to list values for the given argument.

    Args:
      parameter_info: the runtime ResourceParameterInfo object.
      aggregations: a list of _RuntimeParameter objects.
      parent_translator: a ParentTranslator object if needed.

    Returns:
      The apitools request.
    Nr   T)r3   is_primary_resource)
r_   GetRequestTyper&   r'   r[   r	   SetFieldInMessager   r5   ParseResourceIntoMessage)
r#   rE   r   r   r_   r1   fieldrH   parentr3   s
             r   r   z(ResourceArgumentCompleter.BuildListQueryF  s     [[F~%f##%'Gd&9&9:u!!'5%8 ;^^N.?  AFn.AA
6 &&1tM Nr   c                 F   | j                  |      }| j                  ||      }	 | j                  |       y# t        j                  $ rA dj                  | j                               }|t        v rt        j                  |      cY S Y yt        j                  $ r Y yw xY w)z8Get a special parent translator if needed and available.rF   N.)
r   _GetRawParamValuesForParent_ParseDefaultParentr   #ParentCollectionResolutionExceptionjoinrh   _PARENT_TRANSLATORSr(   r   )r#   rE   r   rF   r;   keys         r   r   z.ResourceArgumentCompleter._GetParentTranslatorg  s    77E33*; 4 =L
|,88 , HHT'')*c	#	#"&&s++ 
$ ?? s   8 AB B B c                 L   | j                         D ci c]  }||j                  |       }}t        j                  |xs i       D ]   \  }}|s	|j	                  |d      r|||<   " | j
                  j                  d      d   }|j	                  |d      d||<   |S c c}w )zAGet raw param values for the resource in prep for parsing parent.Nr7   rf   fake)rh   r=   r&   r'   r(   r9   rg   )r#   rE   rF   rG   r;   r   rH   rn   s           r   r   z5ResourceArgumentCompleter._GetRawParamValuesForParent{  s    ;?;M;M;OP;OaA~..q11;OLP}}%6%<"=e	|''d3"T > &&004R8KT*2"(l; Qs   B!c                     t        j                  t         j                  | j                  d|d      }|j	                         S )z9Parse the parent for a resource using default collection.r7   Nr8   )r   r>   r?   r9   Parent)r#   r;   r   s      r   r   z-ResourceArgumentCompleter._ParseDefaultParent  s<    !!,,!H ??r   c                    | j                  |      }| j                  ||      }	 |s| j                  |      S |j                  | j	                         ||      S # t
        j                  $ r@}t        j                  t        j                  |      j                                Y d}~yd}~wt
        j                  $ r@}t        j                  t        j                  |      j                                Y d}~yd}~ww xY w)a  Gets the parent reference of the parsed parameters.

    Args:
      parameter_info: the runtime ResourceParameterInfo object.
      aggregations: a list of _RuntimeParameter objects.
      parent_translator: a ParentTranslator for translating to a special
        parent collection, if needed.

    Returns:
      googlecloudsdk.core.resources.Resource | None, the parent resource or None
        if no parent was found.
    r   N)r   r   r   rK   rh   r   r   r   rA   r&   rB   rC   r   )r#   rE   r   r   rF   r;   rJ   s          r   r   z#ResourceArgumentCompleter.GetParent  s     77E33*; 4 =L''55$$T%7%7%9>%68 888 	hhs}}Q&&()?? 	hhs}}Q&&()s(   A  A C>-6B((C>>6C99C>c                     t        |t              sy| j                  |j                  k(  xr4 | j                  |j                  k(  xr | j                  |j                  k(  S )z
Overrides.F)r   rT   rY   r!   r_   )r#   others     r   __eq__z ResourceArgumentCompleter.__eq__  sW     e67%"5"55 (OOu///(KK5<<')r   )NNN)NNr    )r   r   r   r   r$   propertyr_   rh   rt   r}   r   r   r   r   r   r   r   r   r   r   r   __classcell__)rb   s   @r   rT   rT      s    G 9=   30$$	G/Ed 8<'+M" DH26	 9='+B(	 48"&>)r   rT   c                    | j                   }t        j                  |      }|y|| j                  d   k(  r|j                  S | j                  j                  |      }|j                  }t        j                  ||j                        }|j                  d|dz    }|D ]  }|j                  |k(  s|j                  c S  y)z3Gets the collection for an attribute in a resource.Nrf      )
_collection_infor
   APICollectionrk   r   indexapi_nameGetAPICollectionsrV   r   )	rY   rp   resource_collection_inforesource_collectionrq   r   resource_collectionsr)   cs	            r   _MatchCollectionr     s    *;; ..  -**2..###**00;-%..(!33**, ../A0AB&aF"VVm  r   c                     d}t        | |      }|r3| j                  j                  dz   |z   }| j                  j                  }n|j                  dk(  rd}nyt
        j                  j                  ||      S )z4Gets collection info for an attribute in a resource.Nr   projectr   rV   )r   r   r   rV   r   r   r?   r@   )rY   rp   rV   r!   full_collection_names        r   _GetCompleterCollectionInfor     s    +y9* 	&&//#5
B 00<<K ~~":				-	-.B:E 
. 
G Gr   c                   2    e Zd ZdZ	 	 ddZed        Zd Zy)CompleterInfoz@Holds data that can be used to instantiate a resource completer.Nc                 J    || _         || _        || _        || _        || _        y r    )rO   rP   r9   r_   rQ   )r#   rO   rP   r9   r_   rQ   s         r   r$   zCompleterInfo.__init__  s'    &DDM*DDK DOr   c                    |j                   D ]  }|j                  |k(  s|} n t        dj                  |            |j	                  |      }|j
                  }|j                  }t        ||      }|j                  t        v rct        j                  |j                        }	t        j                  |j                  d      }
|	j                  }|	j                  }|	j                  }|st!        ||dd|      S 	 t        j                  |j                  d|j"                        }
t!        ||||
|      S # t        j$                  $ r |j                  t&        k7  rm|j                  j)                  d      d   dk(  rLt        j                  t&              }	t        j                  t&        d      }
|	j                  }|	j                  }nd}
Y t        j*                  $ r d}
Y w xY w)a  Gets the method, param_name, and other configuration for a completer.

    Args:
      resource_spec: concepts.ResourceSpec, the overall resource.
      attribute_name: str, the name of the attribute whose argument will use
        this completer.

    Raises:
      AttributeError: if the attribute doesn't belong to the resource.

    Returns:
      CompleterInfo, the instantiated object.
    z%Attribute [{}] not found in resource.listNr   r   rf   projects)rk   r   AttributeErrorr   rl   completion_request_paramscompletion_id_fieldr   r]   _SPECIAL_COLLECTIONS_MAPr(   r
   	GetMethodrO   rP   rQ   r   rV   UnknownMethodError_PROJECTS_COLLECTIONsplitr   )clsrY   attribute_namer   rp   rQ   rO   rP   r9   special_infor_   s              r   FromResourcezCompleterInfo.FromResource  s    %%	
>	!	 &
 
1
8
8
HJ J((8J77M,,H1-KO  $<<-11/2K2KLl!!/";";VDf"00m&&h**j=(D$
KK!!

#
#V%113f, /6#% %' && 

#
#';
;''--c226*D 0334HI##$8&A$22((>> fs   ;,D6 6BG$G$#G$c                     | j                   S )z1Get the APIMethod for an attribute in a resource.)r_   rd   s    r   r   zCompleterInfo.GetMethod)  s    ;;r   )NNNNN)r   r   r   r   r$   classmethodr   r   r   r   r   r   r     s*    HHL'+! ;% ;%zr   r   c                 T      G  fddt               j                         syS )z<Gets a resource argument completer for a specific attribute.c                   F     e Zd ZdZW W f fd	Zefd       Z xZS )(CompleterForAttribute.<locals>.Completerz5A specific completer for this attribute and resource.c                     t         j                  ||      }t        |   ||j                  |j
                  f|j                  |j                  |j                  d| y )N)rO   rP   rW   )	r   r   r^   r$   r9   r_   rO   rP   rQ   )r#   rY   r   r`   completer_info	Completerrb   s        r   r$   z1CompleterForAttribute.<locals>.Completer.__init__4  se    $11-PnIt%


(
(


 '44!**)) r   c                 ^    t        t        j                        j                               S )z:Checks whether the completer is valid (has a list method).)boolr   r   r   )r   r   rY   s    r   validatez1CompleterForAttribute.<locals>.Completer.validateA  s-     

$
$]N
C
M
M
OQ Qr   )r   r   r   r   r$   r   r   r   )rb   r   r   rY   s   @r   r   r   1  s'    ?%2 . Q Qr   r   N)rT   r   )rY   r   r   s   ``@r   rm   rm   .  s/    Q Q+ Q, 
				r   )(r   
__future__r   r   r   collectionsapitools.base.protorpcliter   googlecloudsdk.api_lib.utilr   resource_libgooglecloudsdk.command_lib.utilr   $googlecloudsdk.command_lib.util.apisr	   r
   (googlecloudsdk.command_lib.util.conceptsr   googlecloudsdk.corer   r   r   r   r&   r\   r   _PROJECT_ID_FIELDr   objectr   r   
namedtuplerN   r   ResourceCompleterrT   r   r   r   rm   r   r   r   <module>r     s   ' &  '  / @ 6 : 9 L * # * ) 
 6  *J *Fv F\ ##7$02C#DF!"679 J-{--
 J* *H6M+N+<+<>? [)
 < < [)|(G&KF K\r   