
    u:                     J   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ZddlmZ d Zd ZeedZ G d dej4                        Z G d de      Z G d d ej8                  ej:                  e            Zy)z2Facilities for user prompting for request context.    )absolute_import)division)unicode_literalsN)
exceptions)lister)utils)
properties)	resources)
console_io)gce)zipc                      t         j                  j                  j                  j	                         r"t        j                         j                         S y N)r	   VALUEScorecheck_gce_metadataGetBoolc_gceMetadataRegion     4lib/googlecloudsdk/api_lib/compute/scope_prompter.py_GetGCERegionr   #   s9    ..668>>""$$	r   c                      t         j                  j                  j                  j	                         r"t        j                         j                         S y r   )r	   r   r   r   r   r   r   Zoner   r   r   _GetGCEZoner   )   s9    ..668>>  ""	r   )zoneregionc                       e Zd ZdZy)Errorz"Exceptions for the scope prompter.N__name__
__module____qualname____doc__r   r   r   r!   r!   5   s    *r   r!   c                       e Zd ZdZy)_InvalidPromptInvocationz6Exception for invoking prompt with invalid parameters.Nr"   r   r   r   r(   r(   :   s    >r   r(   c                   P   e Zd ZdZej
                  d        Zej
                  d        Zej
                  d        Zej
                  d        Z	ej
                  d        Z
ej
                  d        Z	 dd	Zd
 Zd Zd Zd Z	 ddZ	 	 ddZ	 	 ddZ	 ddZ	 ddZddZddZy)ScopePrompterzBA mixin class prompting in the case of ambiguous resource context.c                      y)z<Specifies the name of the collection that should be printed.Nr   selfs    r   resource_typezScopePrompter.resource_typeB        	r   c                      y)z2Specifies the http client to be used for requests.Nr   r,   s    r   httpzScopePrompter.httpG   r/   r   c                      y)zSpecifies the user's project.Nr   r,   s    r   projectzScopePrompter.projectL   r/   r   c                      y)zSpecifies the API batch URL.Nr   r,   s    r   	batch_urlzScopePrompter.batch_urlQ   r/   r   c                      y)zSpecifies the compute client.Nr   r,   s    r   computezScopePrompter.computeV   r/   r   c                      y)z5Specifies the resources parser for compute resources.Nr   r,   s    r   r
   zScopePrompter.resources[   r/   r   Nc           	      P   |rdj                  |      }nd}g }t        j                  || j                  || j                  | j
                  |      }|D cg c]  }| }	}|s|	s<|rdnd}
t        j                  |dj                  |dj                  |      |
             |	S c c}w )z.Returns a list of choices used to prompt with.zname eq {0}.*N)servicer3   filter_exprr1   r5   errors:.zFUnable to fetch a list of {0}s. Specifying [{1}] may fix this issue{2}z, or )	formatr   GetGlobalResourcesr3   r1   r5   r   RaiseToolExceptionjoin)r-   	attributer:   
flag_namesprefix_filterr;   r<   global_resourcesresourcechoicespunctuations              r   FetchChoiceResourcesz"ScopePrompter.FetchChoiceResources`   s     #**=9kkF00YY.. )99(8Hx(8G9W!Csk
VIw||J'?MO
 N :s   	B#c                    fd}t        |      t        |      k7  r
t               d}d}	t        |      dk(  rCt        j                  |d         xs d }
 |
       }|r|d   }	| j	                  ||d   |||      }|Ei }t        ||      D ]  \  }}| j                  |||      ||<    | j                  |||||      \  }	}|J |	J g }|D ]\  \  }}}|j                         }|	|v r|||	<   	 | j                  j                  |||      }t        ||	      sL|j                  |       ^ |S # t        j                  t        j                  f$ r Y w xY w)a  Prompts user to specify a scope for ambiguous resources.

    Args:
      ambiguous_names: list(tuple(name, params, collection)),
        list of parameters which can be fed into resources.Parse.
      attributes: list(str), list of scopes to prompt over.
      services: list(apitool.base.py.base_api.BaseApiService), service for each
        attribute/scope.
      resource_type: str, collection name without api name.
      flag_names: list(str), flag names which can be used to specify scopes.
      prefix_filter: str, used to filter retrieved resources on backend.
    Returns:
      List of fully resolved names for provided ambiguous_names parameter.
    Raises:
      _InvalidPromptInvocation: if number of attributes does not match number of
        services.
    c                      t              dkD  rdnd} t        j                  dj                  | d   dj	                        | d               )zDCall this to raise an exn when prompt cannot read from input stream.   )zone of flags) flagz+Unable to prompt. Specify {0}the [{1}] {2}.r   , )lencompute_exceptionsFailedPromptErrorr?   rB   )phrasesrD   s    r   RaiseOnPromptFailurez;ScopePrompter._PromptForScope.<locals>.RaiseOnPromptFailure   sO    (+J!(;$g00
7
>
>aj$))J/=> >r   NrM   r   c                       y r   r   r   r   r   <lambda>z/ScopePrompter._PromptForScope.<locals>.<lambda>   s    r   params
collection)rR   r(   GCE_SUGGESTION_SOURCESget_PromptDidYouMeanScoper   rJ   _PromptForScopeListcopyr
   ParsehasattrappendRequiredFieldOmittedExceptionr	   RequiredPropertyError)r-   ambiguous_names
attributesservicesr.   rD   rE   rV   selected_resource_nameselected_attributegce_suggestorgce_suggested_resourcechoice_resourcesr:   rC   resultambigous_namerZ   r[   
new_paramsresource_refs        `               r   _PromptForScopezScopePrompter._PromptForScope{   s   *> :#h-'$&& " :!
 
$
$Z]
3
E ,	']!%!<!<Z]M"$8":
 % #Hj 9
'9%%7J? 	# !: 483K3K
:}6F
4 00
 "---)))F-<)vz;;=j	z	))?
%&&~~++* , E <!34
--
% .= M 55..0 s   1D11#EEc                     t        j                  |      }|D cg c]  \  }}}|
 }	}}dj                  |||dj                  |	            }
	 t	        j
                  |
dd      r|S yc c}}w # t        j                  $ r
  |        Y yw xY w)z@Prompts "did you mean <scope>".  Returns str or None, or raises.z&Did you mean {0} [{1}] for {2}: [{3}]?rQ   T)messagedefaultthrow_if_unattendedN)r   CamelCaseToOutputFriendlyr?   rB   r   PromptContinueUnattendedPromptError)r-   ambiguous_refsrC   r.   suggested_resourceraise_on_prompt_failureresource_namename_namesrt   s              r   r^   z$ScopePrompter._PromptDidYouMeanScope   s    
 33MBM$23NjdAqTNE36==%}dii6FHG 		"	"7D7;
=!! 4 ++   s   A*A0 0BBc           	         t        j                  |      }|D cg c]  \  }}}dj                  |       }	}}g }
g }|D ]  }||   D ]  }|j                  }|r'dj                  |j                  |j
                        }n|j                  }t        |      dkD  rdj                  ||      }|j                  ||j                  f       |
j                  |         t        j                  dj                  |      |	      }t        j                  |
dj                  |dj                  |                  }| |        y	||   S c c}}w )
zDPrompt to resolve abiguous resources.  Either returns str or throws.z[{0}]z	{0} ({1})rM   z{0}: {1}zFor the following {0}:z{0}choose a {1}:z or )optionsrt   N)r   rw   r?   
deprecatedr~   staterR   rc   ConstructListr   PromptChoicerB   )r-   rz   rg   r.   rm   r|   r}   r~   r   r   choice_nameschoice_mappingrC   choice_resourcer   choice_nametitleidxs                     r   r_   z!ScopePrompter._PromptForScopeList   sH   
 33MBM4BCNjdAqW^^D!NECLN	-i8/$//
#**""J$4$46+ (,,+z?Q")))[A+y/*>*>?@K( 9    ''6?E

!
!"))%Z1HIKC {C  7 Ds   Ec           	         t        |      t        |      k7  st        |      t        |      k7  r
t               g }g }|D ]  }|D ]  }	t        j                  |	      }
dt        j
                  j                  j                  j                  i}| j                  j                  |
      }d|j                  v r2t        j
                  j                  j                  j                  |d<   n?d|j                  v r1t        j
                  j                  j                  j                  |d<   	 | j                  j                  |||
      }|j!                  |         |r|| j)                  ||||d   |d      z  }|S # t        j"                  $ r Y Pt        j$                  t        j&                  f$ r |j!                  |||
f       Y w xY w)zFPrompt for resources, which can be placed in several different scopes.r3   r   r   rY   r   Nrf   rg   rh   r.   rD   rE   )rR   r(   r   GetApiCollectionr	   r   r   r3   	GetOrFailr
   GetCollectionInforZ   r7   r   r   ra   rc    WrongResourceCollectionExceptionrd   re   rr   )r-   resource_namesscope_namesscope_servicesresource_typesrD   resource_refsrf   r}   r.   r[   rZ   collection_inforq   s                 r   PromptForMultiScopedReferencesz,ScopePrompter.PromptForMultiScopedReferences  s    ;3~..KC//$&&MO')-++M:
z((--55??
 ..:::F_+++%,,4499CC&.///'..66==GG&
		---Fz . C, 

|
,' * (, t++) !&q) ,  m # 99 	
77002 	F

 
 -!D
E	Fs   )E??G6GGc           	      D   g }g }	|xs | j                   }t        j                  |      }
|D ]  }dt        j                  j
                  j                  j                  ||xs. t        t        j                  j                  |      j                  i}	 | j                  j                  ||
|      }|j                  |        |	r|s|| j                  |	|g|g|||      z  }|S # t        j                  t        j                  f$ r |	j                  |||
f       Y w xY w)zDReturns a list of resolved resource references for scoped resources.r3   )r[   rZ   r   )r.   r   r   r	   r   r   r3   r   getattrr7   r
   ra   rc   rd   re   rr   )r-   r   
scope_name	scope_argscope_servicer.   rD   rE   r   rf   r[   r}   rZ   rq   s                 r   CreateScopedReferencesz$ScopePrompter.CreateScopedReferences.  s7    MO!7T%7%7M''6J'
Z&&++33==
y Pz0088*EOOf
	+~~++! ,  	\* (" yt++) \!?%% , ' 'm ! 55..0 DvzBCDs   C%%7DDc           	      &   |dg}|r]| j                   j                  |dt        j                  j                  j
                  j                  id      }|j                         }nd}| j                  |d|| j                  j                  |||      S )z5Returns a list of resolved zonal resource references.Nz--zoner3   zcompute.zonesrY   r   )r   r   r   r.   rD   rE   )r
   ra   r	   r   r   r3   r   Namer   r7   zones)r-   r   zone_argr.   rD   region_filterzone_ref	zone_names           r   CreateZonalReferencesz#ScopePrompter.CreateZonalReferencesS  s     :j%%
**//77AA % & &h --/ii&&ll((## ' % %r   c                 4    | j                  |g||||      d   S Nr   )r   )r-   r}   r   r.   rD   r   s         r   CreateZonalReferencez"ScopePrompter.CreateZonalReferencem  s-    %%	=*mMMNP Pr   c                 $   |dg}|r]| j                   j                  |dt        j                  j                  j
                  j                  id      }|j                         }nd}| j                  |d|| j                  j                  ||      S )z8Returns a list of resolved regional resource references.Nz--regionr3   zcompute.regionsrY   r   )r   r   r   rD   r.   )r
   ra   r	   r   r   r3   r   r   r   r7   regions)r-   r   
region_argrD   r.   
region_refregion_names          r   CreateRegionalReferencesz&ScopePrompter.CreateRegionalReferencesr  s     <j>>''
**//77AA ' ( (j OO%kk&&ll**# ' % %r   c                 2    | j                  |g|||      d   S r   )r   )r-   r}   r   rD   r.   s        r   CreateRegionalReferencez%ScopePrompter.CreateRegionalReference  s+    ((	Z@@AC Cr   c                    g }|D ]~  }|j                  | j                  j                  |dt        j                  j
                  j                  j                  it        j                  |xs | j                                      |S )z6Returns a list of resolved global resource references.r3   rY   )rc   r
   ra   r	   r   r   r3   r   r   r   r.   )r-   r   r.   r   r}   s        r   CreateGlobalReferencesz$ScopePrompter.CreateGlobalReferences  s    M'4>>//
**//77AA ++1t113 0 4 5 ( r   c                 .    | j                  |g|      d   S r   )r   )r-   r}   r.   s      r   CreateGlobalReferencez#ScopePrompter.CreateGlobalReference  s    &&FqIIr   r   )NNN)NN)r#   r$   r%   r&   abcabstractpropertyr.   r1   r3   r5   r7   r
   rJ   rr   r^   r_   r   r   r   r   r   r   r   r   r   r   r   r*   r*   ?   s   J	 	 	 	 	 	 	 	 	 	 	 	
 *.6M^ &"!H+^ ,0#J KO;?%4 IM:>P ?C%4 >BC
Jr   r*   ) r&   
__future__r   r   r   r   googlecloudsdk.api_lib.computer   r   r   "googlecloudsdk.command_lib.computerS   googlecloudsdk.corer	   r
   googlecloudsdk.core.consoler   googlecloudsdk.core.credentialsr   r   six	six.movesr   r   r   r\   r!   r(   with_metaclassABCMetaobjectr*   r   r   r   <module>r      s    9 &  ' 
 5 1 0 O * ) 2 8 
   J 
u 
_J&C&&s{{F; _Jr   