
                            d Z ddlmZ ddlmZ ddlmZ ddlZddlZddlZddlZddl	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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&dZ'dZ(dZ)dZ* G d dejV                        Z, G d dejZ                        Z. G d d e/      Z0de'dd!d!dfd"Z1de)dd!d!dfd#Z2 G d$ d%ejZ                        Z3 G d& d'e4      Z5d9d(Z6 G d) d*e4      Z7 G d+ d,e4      Z8 G d- d.e4      Z9 G d/ d0e4      Z:d1 Z;d2 Z<d3 Z=d9d4Z>d5 Z?d:d6Z@d7 ZAd8 ZBy);z3Flags and helpers for the compute related commands.    )absolute_import)division)unicode_literalsN)filter_rewrite)service)actions)arg_parsers)
completers)scope)scope_prompter)
exceptions)log)
properties)	resources)
console_io)resource_projection_spec)textz projects/([^/]+)/global/([^/]+)/z!projects/([^/]+)/regions/([^/]+)/zprojects/([^/]+)/zones/([^/]+)/a  If not specified and the ``compute/zone'' property isn't set, you
might be prompted to select a zone (interactive mode only).

To avoid prompting when this flag is omitted, you can set the
``compute/zone'' property:

  $ gcloud config set compute/zone ZONE

A list of zones can be fetched by running:

  $ gcloud compute zones list

To unset the property, run:

  $ gcloud config unset compute/zone

Alternatively, the zone can be stored in the environment variable
``CLOUDSDK_COMPUTE_ZONE''.
zIf not specified, you might be prompted to select a zone (interactive mode
only).

A list of zones can be fetched by running:

  $ gcloud compute zones list
a  If not specified, you might be prompted to select a region (interactive mode
only).

To avoid prompting when this flag is omitted, you can set the
``compute/region'' property:

  $ gcloud config set compute/region REGION

A list of regions can be fetched by running:

  $ gcloud compute regions list

To unset the property, run:

  $ gcloud config unset compute/region

Alternatively, the region can be stored in the environment
variable ``CLOUDSDK_COMPUTE_REGION''.
zIf not specified, you might be prompted to select a region (interactive mode
only).

A list of regions can be fetched by running:

  $ gcloud compute regions list
c                       e Zd ZdZdZdZdZy)ScopeFlagsUsagezFEnum representing gcloud flag generation options for ResourceArgument.         N)__name__
__module____qualname____doc__GENERATE_DEDICATED_SCOPE_FLAGSUSE_EXISTING_SCOPE_FLAGSDONT_USE_SCOPE_FLAGS     /lib/googlecloudsdk/command_lib/compute/flags.pyr   r   p   s    N#$ r!   r   c                       e Zd Zy)ScopesFetchingExceptionN)r   r   r   r    r!   r"   r$   r$   w   s    r!   r$   c                       e Zd ZdZy)BadArgumentExceptionz2Unhandled error for validating function arguments.N)r   r   r   r   r    r!   r"   r&   r&   {   s    :r!   r&   Fc	           
      j   dj                  t        j                  t        |      dz   |xs d|      |      }	d}
||dz   |
z   }
| j	                  d|
z   |t
        j                  t        j                  t        j                  j                  j                        |xs dj                  |	|      	       y)
aG  Adds a --zone flag to the given parser.

  Args:
    parser: argparse parser.
    resource_type: str, human readable name for the resource type this flag is
      qualifying, for example "instance group".
    operation_type: str, human readable name for the operation, for example
      "update" or "delete".
    flag_prefix: str, flag will be named --{flag_prefix}-zone.
    explanation: str, detailed explanation of the flag.
    help_text: str, help text will be overridden with this value.
    hidden: bool, If True, --zone argument help will be hidden.
    plural: bool, resource_type will be pluralized or not depending on value.
    custom_plural: str, If plural is True then this string will be used as
                        resource types, otherwise resource_types will be
                        pluralized by appending 's'.
  zZone of the {0} to {1}.r    zoneN---{0} {1})hidden	completeractionhelp)formatr   	Pluralizeintadd_argumentr
   ZonesCompleterr   StorePropertyr   VALUEScomputer)   parserresource_typeoperation_typeflag_prefixexplanation	help_textr-   pluralcustom_plural
short_help	flag_names              r"   AddZoneFlagrD      s    ( )//
nn
f+/=.B?@NP* )c!I-I
Y))"":#4#4#<#<#A#ABA	(([A  Cr!   c	           
      j   dj                  t        j                  t        |      dz   |xs d|      |      }	d}
||dz   |
z   }
| j	                  d|
z   t
        j                  t        j                  t        j                  j                  j                        ||xs dj                  |	|      	       y)
aM  Adds a --region flag to the given parser.

  Args:
    parser: argparse parser.
    resource_type: str, human readable name for the resource type this flag is
      qualifying, for example "instance group".
    operation_type: str, human readable name for the operation, for example
      "update" or "delete".
    flag_prefix: str, flag will be named --{flag_prefix}-region.
    explanation: str, detailed explanation of the flag.
    help_text: str, help text will be overridden with this value.
    hidden: bool, If True, --region argument help will be hidden.
    plural: bool, resource_type will be pluralized or not depending on value.
    custom_plural: str, If plural is True then this string will be used as
                        resource types, otherwise resource_types will be
                        pluralized by appending 's'.
  zRegion of the {0} to {1}.r   r(   regionNr*   r+   r,   )r.   r/   r-   r0   )r1   r   r2   r3   r4   r
   RegionsCompleterr   r6   r   r7   r8   rF   r9   s              r"   AddRegionFlagrH      s    * +11
nn
f+/=.B?@NP* )c!I-I
Y++"":#4#4#<#<#C#CDA	(([A  Cr!   c                   "     e Zd ZdZ fdZ xZS )UnderSpecifiedResourceErrorzARaised when argument is required additional scope to be resolved.c           
          t        |      dkD  rdnd}t        t        |   dj	                  |d   dj                  t        |            |d   dj                  |                   y )Nr   )zone of flags)r(   flagz8Underspecified resource [{3}]. Specify {0}the [{1}] {2}.r   z, )lensuperrJ   __init__r1   joinsorted)selfunderspecified_names
flag_namesphrases	__class__s       r"   rP   z$UnderSpecifiedResourceError.__init__   s^    &)*o&9"|G	
%t5B	
		&,-
		./
12r!   )r   r   r   r   rP   __classcell__)rW   s   @r"   rJ   rJ      s    I2 2r!   rJ   c                       e Zd ZdZddZy)ResourceStubz6Interface used by scope listing to report scope names.Nc                      || _         || _        y N)name
deprecated)rS   r]   r^   s      r"   rP   zResourceStub.__init__   s    DI DOr!   r\   r   r   r   r   rP   r    r!   r"   rZ   rZ      s
    >!r!   rZ   c                 @   t         j                  j                  t        j                  t
        j                  |       t         j                  j                  t        j                  t        j                  |       t         j                  j                  d ifd}|S )z&Constructs default zone/region lister.c                     t        d      gS )Nr(   )r]   )rZ   )_s    r"   <lambda>z'GetDefaultScopeLister.<locals>.<lambda>   s    21F0Gr!   c                     xs4 t         j                  j                  j                  j	                  d      }i }| D ]  } |   |      ||<    |S )NT)required)r   r7   coreprojectGet)scopesrb   prjresultsr   rg   
scope_funcs        r"   Listerz%GetDefaultScopeLister.<locals>.Lister   sV    

FZ&&++33777FCG(z%(-gen Nr!   )
compute_scope	ScopeEnumZONE	functoolspartialzones_serviceListREGIONregions_serviceGLOBAL)compute_clientrg   rm   rl   s    ` @r"   GetDefaultScopeListerry      st     ""


M..
?$$


O00.
A$$&G* 
-r!   c                       e Zd ZdZd Zy)ResourceArgScopez2Facilitates mapping of scope, flag and collection.c                 J   || _         |r^|j                  dd      }|t        j                  j                  u r|j
                  dz   |z   | _        n)|dz   |j
                  z   | _        n|j
                  | _        d| j
                  j                  dd      z   | _        || _        y )Nr*   rb   r+   )
scope_enumreplacern   ro   rw   rC   rM   
collection)rS   r   r=   r   s       r"   rP   zResourceArgScope.__init__   s    DO''S1k	-))00	03.<$s*U__<dnt~~--c377DI DOr!   Nr_   r    r!   r"   r{   r{      s
    :!r!   r{   c                   H    e Zd ZdZd Zd Zd Zd ZddZd Z	d	 Z
d
 Zd Zy)ResourceArgScopesz Represents chosen set of scopes.c                      || _         i | _        y r\   )r=   ri   )rS   r=   s     r"   rP   zResourceArgScopes.__init__   s    "DDKr!   c                 L    t        || j                  |      | j                  |<   y r\   )r{   r=   ri   )rS   r   r   s      r"   AddScopezResourceArgScopes.AddScope  s    )%1A1A:NDKKr!   c                     t        j                  | j                        D ]!  }t        ||j                  d      }|||fc S  y)z8Given argparse args return selected scope and its value.NNN)six
itervaluesri   getattrrC   )rS   argsresource_scopescope_values       r"   SpecifiedByArgsz!ResourceArgScopes.SpecifiedByArgs  sC    ..5D.":":DAk		 {** 6 r!   c                    t        j                  t        |      r)| j                  t        j
                  j                     dfS t        j                  t        |      r)| j                  t        j
                  j                     dfS t        j                  t        |      r)| j                  t        j
                  j                     dfS y)z9Given resource value return selected scope and its value.globalrF   r)   r   )rematch_GLOBAL_RELATIVE_PATH_REGEXri   rn   ro   rw   _REGIONAL_RELATIVE_PATH_REGEXru   _ZONAL_RELATIVE_PATH_REGEXrp   )rS   values     r"   SpecifiedByValuez"ResourceArgScopes.SpecifiedByValue  s    	xx+U3[[00778(BB	/	7[[00778(BB	,e	4[[00556>>r!   Nc                     t        | j                        dk(  r(t        t        j                  | j                              S |S )zBSee if there is no ambiguity even if scope is not known from args.r   )rN   ri   nextr   r   )rS   default_scopes     r"   GetImplicitScopez"ResourceArgScopes.GetImplicitScope  s1    
4;;1#..-..r!   c                 R    t        t        j                  | j                              S r\   )iterr   r   ri   rS   s    r"   __iter__zResourceArgScopes.__iter__  s    t{{+,,r!   c                     || j                   v S r\   ri   rS   r   s     r"   __contains__zResourceArgScopes.__contains__"  s    DKKr!   c                      | j                   |   S r\   r   r   s     r"   __getitem__zResourceArgScopes.__getitem__%  s    ;;ur!   c                 ,    t        | j                        S r\   )rN   ri   r   s    r"   __len__zResourceArgScopes.__len__(  s    t{{r!   r\   )r   r   r   r   rP   r   r   r   r   r   r   r   r   r    r!   r"   r   r      s3    (O- r!   r   c                   f    e Zd ZdZd Zedd       Zd Zd Z	 ddZ	d Z
d	 Z	 dd
Z	 	 	 	 	 ddZy)ResourceResolvera  Object responsible for resolving resources.

  There are two ways to build an instance of this object:
  1. Preferred when you don't have instance of ResourceArgScopes already built,
     using .FromMap static function. For example:

     resolver = ResourceResolver.FromMap(
         'instance',
         {compute_scope.ScopeEnum.ZONE: 'compute.instances'})

     where:
     - 'instance' is human readable name of the resource,
     - dictionary maps allowed scope (in this case only zone) to resource types
       in those scopes.
     - optional prefix of scope flags was skipped.

  2. Using constructor. Recommended only if you have instance of
     ResourceArgScopes available.

  Once you've built the resover you can use it to build resource references (and
  prompt for scope if it was not specified):

  resolver.ResolveResources(
        instance_name, compute_scope.ScopeEnum.ZONE,
        instance_zone, self.resources,
        scope_lister=flags.GetDefaultScopeLister(
            self.compute_client, self.project))

  will return a list of instances (of length 0 or 1 in this case, because we
  pass a name of single instance or None). It will prompt if and only if
  instance_name was not None but instance_zone was None.

  scope_lister is necessary for prompting.
  c                      || _         || _        y)aZ  Initilize ResourceResolver instance.

    Prefer building with FromMap unless you have ResourceArgScopes object
    already built.

    Args:
      scopes: ResourceArgScopes, allowed scopes and resource types in those
              scopes.
      resource_name: str, human readable name for resources eg
                     "instance group".
    N)ri   resource_name)rS   ri   r   s      r"   rP   zResourceResolver.__init__P  s     DK&Dr!   Nc                     t        |      }t        j                  |      D ]  \  }}|j                  ||        t	        ||       S )a  Initilize ResourceResolver instance.

    Args:
      resource_name: str, human readable name for resources eg
                     "instance group".
      scopes_map: dict, with keys should be instances of ScopeEnum, values
              should be instances of ResourceArgScope.
      scope_flag_prefix: str, prefix of flags specyfying scope.
    Returns:
      New instance of ResourceResolver.
    r=   )r   r   	iteritemsr   r   )r   
scopes_mapscope_flag_prefixri   r   resources         r"   FromMapzResourceResolver.FromMap_  sA     +<=F==4xooeX& 5FM22r!   c                 X    t        |t              st        dj                  |            y )Nz+Expected names to be a list but it is '{0}')
isinstancelistr&   r1   )rS   namess     r"   _ValidateNameszResourceResolver._ValidateNamesq  s.    eT" 
7
>
>u
EG G #r!   c                     |e|| j                   vrVt        dj                  |dj                  | j                   D cg c]  }|j                  j
                   c}                  y y c c}w )Nz<Unexpected value for default_scope {0}, expected None or {1}z or )ri   r&   r1   rQ   r}   r]   )rS   r   ss      r"   _ValidateDefaultScopez&ResourceResolver._ValidateDefaultScopev  sj     ]$++%E 
H6-++$++F+Qq||00+FGIJ J &F  Gs   A)c                    ||j                   t        j                  j                  k(  ryt        j                  j	                  |j                         }|r$|j                  |d|i|      j                         S |j                  |i |      j                         S |r>|j                   t        j                  j                  k7  r|j                   j                  S yy)z#Gets the resource scope parameters.Nrg   )paramsr   )r}   rn   ro   rw   CollectionForScopeParseNameproperty_func)rS   r   r   rg   api_resource_registrywith_projectr   s          r"   _GetResourceScopeParamz'ResourceResolver._GetResourceScopeParam}  s     		"	"m&=&=&D&D	D",,??%%'
&,,W#& - ( )-/
 ',," - ==ATVD 
^66*44;;<((666<r!   c                    g }g }|D ]*  }	 |j                  |||d      g}	|j                  |	       , ||fS # t        j                  t        j                  t        j
                  f$ r |r |g}	|j                  |	       Y bw xY w)aK  Returns pair of lists: resolved references and unresolved names.

    Args:
      names: list of names to attempt resolving
      params: params given when attempting to resolve references
      collection: collection for the names
      scope_defined: bool, whether scope is known
      api_resource_registry: Registry object
    Fr   r   enforce_collection)r   r   UnknownCollectionExceptionRequiredFieldOmittedExceptionr   RequiredPropertyErrorappend)
rS   r   r   r   scope_definedr   refsrT   r]   refs
             r"   _GetRefsAndUnderspecifiedNamesz/ResourceResolver._GetRefsAndUnderspecifiedNames  s     D)$**46@>C + E F kk#  %%% 2255..0 ) 
f##C()s   8A	BBc                    t        j                  |      }| j                  D ]  }|rd|i}ni }|j                  j                  ||j                  j
                  <   |D ]Y  }		 |j                  |	d   ||j                  d      g}
|j                  |	       |j                  |
       |j                  |	       [  y# t        j                  t        j                  t        j                  t        f$ r Y w xY w)z:Resolve argument against available scopes of the resource.rg   r   Fr   N)copydeepcopyri   r}   r   
param_namer   r   remover   r   r   r   r   r   
ValueError)rS   r   rg   rT   r   r   r   r   r   r]   r   s              r"   _ResolveMultiScopez#ResourceResolver._ResolveMultiScope  s     MM./E	w
 ,1,<,<,J,JfU(()$	&,,T!WV8=8H8H@E - G H# ++d

++c


%
%d
+    447700 	 		s   !AB<<7C65C6c                    |sy|D cg c]  }|d   	 }}t        j                         s.t        || j                  D 	cg c]  }	|	j                   c}	      t        j                  | j                  || j                  D 	cg c]  }	|	j                   c}	||j                  nd|      \  }
}|
.t        || j                  D 	cg c]  }	|	j                   c}	      | j                  |
   }|rd|i}ni }|j                  t        j                  j                  k7  r|||j                  j                  <   |D ]'  }|j                  |d   ||j                  d      |d<   ) yc c}w c c}	w c c}	w c c}	w )a  Attempt to resolve scope for unresolved names.

    If unresolved_names was generated with _GetRefsAndUnderspecifiedNames
    changing them will change corresponding elements of refs list.

    Args:
      underspecified_names: list of one-items lists containing str
      default_scope: default scope for the resources
      scope_lister: callback used to list potential scopes for the resources
      project: str, id of the project
      api_resource_registry: resources Registry
      with_project: indicates whether or not project is associated. It should be
        False for flexible resource APIs

    Raises:
      UnderSpecifiedResourceError: when resource scope can't be resolved.
    Nr   rg   Tr   )r   	CanPromptrJ   ri   rM   r   PromptForScoper   r}   rn   ro   rw   r   r   r   )rS   rT   r   scope_listerrg   r   r   nr   r   resource_scope_enumr   r   r   r]   s                  r"   _ResolveUnderspecifiedNamesz,ResourceResolver._ResolveUnderspecifiedNames  sr   0  /0/aQqT/E0!'/L1/LMM'5'D'DE$++#F+QALL+#F$1$=  4($ "'/L1/LMM[[!45N
Wf f  M$;$;$B$BB5@f^&&112$%++
q'#..!	 , #d1g %/ 1 0M $G 0Ms   E#E(
E-E2
c
                    | j                  |       | j                  |       || j                  |   }|| j                  |   }|#|j                  |d      }
|
j	                         }d}|r;|xs2 t
        j                  j                  j                  j                         }d|i}ni }|| j                  j                  |      }|	ri ||	}| j                  |||||      }||||j                  j                  <   |xr |j                  }| j                  ||||du|      \  }}|r-t!        | j                        dkD  r| j#                  |||||       | j%                  ||||||       |D cg c]  }|d   	 }}| j                  D cg c]  }|j                   }}|D ]W  }|j'                         |vst)        j*                  dj-                  |      |j'                         |j/                         	       |S c c}w c c}w )
a@  Resolve this resource against the arguments.

    Args:
      names: list of str, list of resource names
      resource_scope: ScopeEnum, kind of scope of resources; if this is not None
                   scope_value should be name of scope of type specified by this
                   argument. If this is None scope_value should be None, in that
                   case if prompting is possible user will be prompted to
                   select scope (if prompting is forbidden it will raise an
                   exception).
      scope_value: ScopeEnum, scope of resources; if this is not None
                   resource_scope should be type of scope specified by this
                   argument. If this is None resource_scope should be None, in
                   that case if prompting is possible user will be prompted to
                   select scope (if prompting is forbidden it will raise an
                   exception).
      api_resource_registry: instance of core.resources.Registry.
      default_scope: ScopeEnum, ZONE, REGION, GLOBAL, or None when resolving
          name and scope was not specified use this as default. If there is
          exactly one possible scope it will be used, there is no need to
          specify default_scope.
      scope_lister: func(scope, underspecified_names), a callback which returns
        list of items (with 'name' attribute) for given scope.
      with_project: indicates whether or not project is associated. It should be
        False for flexible resource APIs.
      source_project: indicates whether or not a project is specified. It could
          be other projects. If it is None, then it will use the current project
          if with_project is true
      additional_params: Dict, additional parameters to pass in.
    Returns:
      Resource reference or list of references if plural.
    Raises:
      BadArgumentException: when names is not a list or default_scope is not one
          of the configured scopes.
      UnderSpecifiedResourceError: if it was not possible to resolve given names
          as resources references.
    Nzcompute.projectsr   rg   )r   r   r   ,)expectedgotpath)r   r   ri   r   r   r   r7   rf   rg   	GetOrFailr   r   r}   r   r   r   rN   r   r   
Collectionr    WrongResourceCollectionExceptionrQ   SelfLink)rS   r   r   r   r   r   r   r   source_projectadditional_paramssource_project_refrg   r   resource_scope_paramr   r   rT   r   r   expected_collectionss                       r"   ResolveResourcesz!ResourceResolver.ResolveResources  sR   ^ 	}-!{{>2n kk-0m!066
%7 7 9)..0nGL*"3"3"8"8"@"@"J"J"Lg
Wf f{{33MBn.&.-.f66! 7 # '5If^&&112=N$=$=J "&!D!Dvz;d#:"D

 DKK 01 4
lG5I3T;
 	$$! % # ##dsCFdD# ;?++F+E,,+F		!5	588XX23 ! 	!  K $ Gs   5HH	r\   )TNNTNN)r   r   r   r   rP   staticmethodr   r   r   r   r   r   r   r   r    r!   r"   r   r   ,  sd    !F' 3 3"G
J +/76&:@ 047#| &*$($(&*)-tr!   r   c                   |    e Zd ZdZddddddddddddddddddej
                  fdZ	 	 	 	 	 d	dZ	 	 	 	 	 d
dZd Z	y)ResourceArgumenta  Encapsulates concept of compute resource as command line argument.

  Basic Usage:
    class MyCommand(base.Command):
      _BACKEND_SERVICE_ARG = flags.ResourceArgument(
          resource_name='backend service',
          completer=compute_completers.BackendServiceCompleter,
          regional_collection='compute.regionBackendServices',
          global_collection='compute.backendServices')
      _INSTANCE_GROUP_ARG = flags.ResourceArgument(
          resource_name='instance group',
          completer=compute_completers.InstanceGroupsCompleter,
          zonal_collection='compute.instanceGroups',)

      @staticmethod
      def Args(parser):
        MyCommand._BACKEND_SERVICE_ARG.AddArgument(parser)
        MyCommand._INSTANCE_GROUP_ARG.AddArgument(parser)

      def Run(args):
        api_resource_registry = resources.REGISTRY.CloneAndSwitch(
            api_tools_client)
        backend_service_ref = _BACKEND_SERVICE_ARG.ResolveAsResource(
            args, api_resource_registry, default_scope=flags.ScopeEnum.GLOBAL)
        instance_group_ref = _INSTANCE_GROUP_ARG.ResolveAsResource(
            args, api_resource_registry, default_scope=flags.ScopeEnum.ZONE)
        ...

    In the above example the following five arguments/flags will be defined:
      NAME - positional for backend service
      --region REGION to qualify backend service
      --global  to qualify backend service
      --instance-group INSTANCE_GROUP name for the instance group
      --instance-group-zone INSTANCE_GROUP_ZONE further qualifies instance group

    More generally this construct can simultaneously support global, regional
    and zonal qualifiers (or any combination of) for each resource.
  NFTc                    |xs d| _         || _        || _        || _        | j                   j	                  d      rkd| _        | j                   dd j                  dd      | _        | j                  t        j                  k(  rdn| j                   dd }t        |      | _        n"t        d      | _        | j                   | _        || _        || _        || _        || _        || _        |s|s|st#        j$                  d	      |r5| j                  j'                  t(        j*                  j,                  |
       |r5| j                  j'                  t(        j*                  j.                  |
       |r5| j                  j'                  t(        j*                  j0                  |
       |	| _        |
xs d| _        || _        || _        |xs d| _        || _        || _        tA        | j                  |      | _!        y)a
  Constructor.

    Args:
      name: str, argument name.
      resource_name: str, human readable name for resources eg "instance group".
      completer: completion_cache.Completer, The completer class type.
      plural: bool, whether to accept multiple values.
      required: bool, whether this argument is required.
      zonal_collection: str, include zone flag and use this collection
                             to resolve it.
      regional_collection: str, include region flag and use this collection
                                to resolve it.
      global_collection: str, if also zonal and/or regional adds global flag
                              and uses this collection to resolve as
                              global resource.
      global_help_text: str, if provided, global flag help text will be
                             overridden with this value.
      region_explanation: str, long help that will be given for region flag,
                               empty by default.
      region_help_text: str, if provided, region flag help text will be
                             overridden with this value.
      region_hidden: bool, Hide region in help if True.
      zone_explanation: str, long help that will be given for zone flag, empty
                             by default.
      zone_help_text: str, if provided, zone flag help text will be overridden
                           with this value.
      zone_hidden: bool, Hide zone in help if True.
      short_help: str, help for the flag being added, if not provided help text
                       will be 'The name[s] of the ${resource_name}[s].'.
      detailed_help: str, detailed help for the flag being added, if not
                          provided there will be no detailed help for the flag.
      custom_plural: str, If plural is True then this string will be used as
                          plural resource name.
      scope_flags_usage: ScopeFlagsUsage, when set to
                                  USE_EXISTING_SCOPE_FLAGS, already existing
                                  zone and/or region flags will be used for
                                  this argument,
                                  GENERATE_DEDICATED_SCOPE_FLAGS, new scope
                                  flags will be created,
                                  DONT_USE_SCOPE_FLAGS to not generate
                                  additional flags and use single argument for
                                  all scopes.

    Raises:
      exceptions.Error: if there some inconsistency in arguments.
    r]   r+   Tr   Nr*   rb   r   zAMust specify at least one resource type zonal, regional or globalr   r(   )"name_arg_short_help_detailed_helpscope_flags_usage
startswithis_flagr~   r]   r   r   r   ri   r   r.   r@   rA   re   r   Errorr   rn   ro   rp   ru   rw   _global_help_text_region_explanation_region_help_text_region_hidden_zone_explanation_zone_help_text_zone_hiddenr   _resource_resolver)rS   r]   r   r.   r@   re   zonal_collectionregional_collectionglobal_collectionglobal_help_textregion_explanationregion_help_textregion_hiddenzone_explanationzone_help_textzone_hiddenrB   detailed_helprA   r   r=   s                        r"   rP   zResourceArgument.__init__  s   H NFDM!D'D.D}}%dl--#++C5di!33'@@AT]]12&  &+>dk%$7dk--di&DDNDK&DDM 37H 2 3 3
kk=2277&6  8
kk=2299&9  ;
kk=2299&7  9-D17RD-D'D-3D)D#D.t{{MJDr!   c                    t        |r|n| j                  j                         | j                        }| j                  r| j                  |d<   n| j
                  r| j
                  |d<   ndj                  | j                  rdndt        j                  t        | j                        dz   | j                  xs d| j                        |      |d<   | j                  j                  d      r|dxx   dz  cc<   | j                  d	k(  r|d
k(  r|dxx   dz  cc<   | j                  j                  d      rF| j                  |d<   | j                  s||d<   | j                  rKt!        j"                  d      |d<   n1| j                  r| j                  rd|d<   n| j                  rdnd|d<    |xs |j$                  | j                  fi | | j&                  t(        j*                  k7  ryt-        | j.                        dkD  r|j1                  d||      }n|}t2        j4                  j6                  | j.                  v rdt9        || j.                  j:                  | j                  || j<                  | j>                  | j@                  | j                  | j                  	       t2        j4                  jB                  | j.                  v rdtE        || j.                  j:                  | j                  || jF                  | jH                  | jJ                  | j                  | j                  	       t2        j4                  jL                  | j.                  v rt-        | j.                        dkD  r| j                  sdj                  | j                        }	nO| j                  r(| j                  sdj                  | j                        }	ndj                  | j                        }	|j%                  | j.                  t2        j4                  jL                     jN                  dd| jP                  xs dj                  |	             yyy)z-Add this set of arguments to argparse parser.)metavarr.   r0   zName{} of the {} to {}.r   r(   r   instancez For details on valid instance names, refer to the criteria documented under the field 'name' at: https://cloud.google.com/compute/docs/reference/rest/v1/instances	DISK_NAMEcreatezy For details on the naming convention for this resource, refer to: https://cloud.google.com/compute/docs/naming-resourcesr+   re   category)
min_lengthtype+nargs*?NT)mutexr  re   )r=   r;   r<   r>   r?   r-   r@   rA   z{} isz{}s arez{} are
store_truezIf set, the {0} global.r/   defaultr0   ))dictr]   upperr.   r   r   r1   r@   r   r2   r3   r   rA   r   r   re   r	   ArgListr4   r   r   r   rN   ri   	add_grouprn   ro   rp   rD   r=   r   r   r   ru   rH   r   r   r   rw   rM   r   )
rS   r:   mutex_groupr<   cust_metavarr  scope_requiredr   r   resource_mentions
             r"   AddArgumentzResourceArgument.AddArgument  s     ,$))//2C..F
 **fVn			''fVn077#"
..$++"D$6$6$<"  " fVn 
		j	)v / 	0
 
k	!n&@v . 	/
 }}%==fZ]]%z	$,,:v	;;&/!%##w([F((A&A!O!OO
4;;!x.  e e##t{{2
kk--**',,((""**	, %%4
kk--**'..**$$**	, %%4T[[9IA9M[[">>$*<*<=;;t11$++D,>,>?#??4+=+=>
++m--44
5
:
:%% $)B6"#  % :N4r!   c                    | j                  |      }| j                  j                  |      \  }	}
|	>| j                  t        j
                  k(  r!| j                  j                  |d         \  }	}
|	|	j                  }	| j                  s}|s{| j                  j                  r1dj                  | j                  j                  |	j                        }nd|	z   }t        j                  dj                  || j                              | j                  j!                  ||	|
||||||	      }| j"                  r|S |r|d   S y)a  Resolve this resource against the arguments.

    Args:
      args: Namespace, argparse.Namespace.
      api_resource_registry: instance of core.resources.Registry.
      default_scope: ScopeEnum, ZONE, REGION, GLOBAL, or None when resolving
          name and scope was not specified use this as default. If there is
          exactly one possible scope it will be used, there is no need to
          specify default_scope.
      scope_lister: func(scope, underspecified_names), a callback which returns
        list of items (with 'name' attribute) for given scope.
      with_project: indicates whether or not project is associated. It should be
        False for flexible resource APIs.
      source_project: indicates whether or not a project is specified. It could
        be other projects. If it is None, then it will use the current project
        if with_project is true
      additional_params: Dict, additional parameters to pass in.
    Returns:
      Resource reference or list of references if plural.
    Nr   z	--{0}-{1}r+   z5Can't specify {0} without specifying resource via {1})r   r   r   )_GetResourceNamesri   r   r   r   r   r   r}   re   r=   r1   rC   r   r   r]   r   r   r@   )rS   r   r   r   r   r   r   r   r   r   r   rM   r   s                r"   ResolveAsResourcez"ResourceArgument.ResolveAsResource}  s<   8 ""4(E"&++"="=d"CNK""o&J&JJ$(KK$@$@q$J!nk!%00n]]5;;""##kk%%~'?'?A$ &$DKKdii!" 	" ""33!%+ 4 	-D {{k!Wnr!   c                     | j                   rt        || j                        S t        || j                        }||gS g S )z0Return list of resource names specified by args.)r@   r   r]   )rS   r   
name_values      r"   r%  z"ResourceArgument._GetResourceNames  s=    {{T499%%tyy)J\Ir!   )Nz
operate onNNFr   )
r   r   r   r   r   r   rP   r#  r&  r%  r    r!   r"   r   r     s    %R 'FF)jKb !f%V '+%)%)'+*.=~r!   r   c                 ,    | j                  ddd       y )Nz--regexpz-rz      A regular expression to filter the names of the results on. Any names
      that do not match the entire regular expression will be filtered out.
      r0   r4   r:   s    r"   AddRegexArgr-    s    $
  r!   c                 *    | j                  dd       y )Npolicy_filez2      JSON or YAML file containing the IAM policy.r*  r+  r,  s    r"   AddPolicyFileFlagr0    s    m +6 7r!   c                 J    | j                  dddj                  |             y )Nz--storage-locationLOCATIONz      Google Cloud Storage location, either regional or multi-regional, where
      {} content is to be stored. If absent, a nearby regional or
      multi-regional location is chosen automatically.
      )r  r0   r4   r1   r:   r   s     r"   AddStorageLocationFlagr5    s,    
 &
  r!   c                 d    dj                  |      }| j                  ddd|r|       y |       y )Nzd
  Create an application-consistent {} by informing the OS
  to prepare for the snapshot process.
  z--guest-flushr  Fr  )r1   r4   )r:   r   custom_helpr?   s       r"   AddGuestFlushFlagr8    sJ     fX  	%;	  6 ,5	  6r!   c                    | j                  dd       | j                  dt        j                         dd       | j                  dt        j                         d	d
       | j                  dt        j                         dd       y)z1Adds the initial state for Shielded instance arg.z--platform-key-filez      File path that points to an X.509 certificate in DER format or raw binary
      file. When you create a Shielded VM instance from this image, this
      certificate or raw binary file is used as the platform key (PK).
        r*  z--key-exchange-key-file	KEK_VALUEa         Comma-separated list of file paths that point to X.509 certificates in DER
      format or raw binary files. When you create a Shielded VM instance from
      this image, these certificates or files are used as key exchange keys
      (KEK).
        )r  r  r0   z--signature-database-fileDB_VALUEa        Comma-separated list of file paths that point to valid X.509 certificates
      in DER format or raw binary files. When you create a Shielded VM instance
      from this image, these certificates or files are  added to the signature
      database (db).
        z--forbidden-database-file	DBX_VALUEa        Comma-separated list of file paths that point to revoked X.509
      certificates in DER format or raw binary files. When you create a Shielded
      VM instance from this image, these certificates or files are added to the
      forbidden signature database (dbx).
        N)r4   r	   r  r,  s    r"   %AddShieldedInstanceInitialStateKeyArgr=    s       	 	  	 	! 	  	 	! 	  	r!   c                 2   | j                   sy| j                         }t        j                  |j                  |j
                        }t        j                  ||      j                  | j                   |      \  }}t        j                  d||       ||fS )aA  Rewrites args.filter into client and server filter expression strings.

  Usage:

    args.filter, request_filter = flags.RewriteFilter(args)

  Args:
    args: The parsed args namespace containing the filter expression args.filter
      and display_info.
    message: The response resource message proto for the request.
    frontend_fields: A set of dotted key names supported client side only.

  Returns:
    A (client_filter, server_filter) tuple of filter expression strings.
    None means the filter does not need to applied on the respective
    client/server side.
  r   )symbolsaliases)messagefrontend_fields)defaultsz!client_filter=%r server_filter=%r)filterGetDisplayInfor   ProjectionSpec
transformsr@  r   RewriterRewriter   info)r   rA  rB  display_inforC  client_filterserver_filters          r"   RewriteFilterrN    s    $ 
$$&,%44%%""$( "0!8!8"88?
++ 9@ 9* - ((.}M		%%r!   c                 r    t         t         d}| j                  dt        j                  |      ddd       y )N)diskzcsek-key-filez--source-disk-csek-key)specr   zPROPERTY=VALUEa  
              Customer-supplied encryption key of the disk attached to the
              source instance. Required if the source disk is protected by
              a customer-supplied encryption key. This flag can be repeated to
              specify multiple attached disks.

              *disk*::: URL of the disk attached to the source instance.
              This can be a full or   valid partial URL

              *csek-key-file*::: path to customer-supplied encryption key.
            )r  r/   r  r0   )strr4   r	   ArgDict)r:   rQ  s     r"   AddSourceDiskCsekKeyArgrT  4  s@    
$ 	D)
  r!   c                 N    | j                  ddddj                  |             y )Nz--erase-windows-vss-signaturer  Fz
              Specifies whether the disk restored from {resource} should
              erase Windows specific VSS signature.
              See https://cloud.google.com/sdk/gcloud/reference/compute/disks/snapshot#--guest-flush
           )r   r  r3  r4  s     r"   AddEraseVssSignaturerV  L  s1    % vxv(  	r!   r\   r   )Cr   
__future__r   r   r   r   enumrq   r   googlecloudsdk.api_lib.computer   &googlecloudsdk.api_lib.compute.regionsr   rv   $googlecloudsdk.api_lib.compute.zonesrs   googlecloudsdk.callioper   r	   "googlecloudsdk.command_lib.computer
   r   rn   r   googlecloudsdk.corer   r   r   r   googlecloudsdk.core.consoler   googlecloudsdk.core.resourcer   googlecloudsdk.core.utilr   r   r   r   r   ZONE_PROPERTY_EXPLANATION$ZONE_PROPERTY_EXPLANATION_NO_DEFAULTREGION_PROPERTY_EXPLANATION&REGION_PROPERTY_EXPLANATION_NO_DEFAULTEnumr   r   r$   r   r&   rD   rH   rJ   objectrZ   ry   r{   r   r   r   r-  r0  r5  r8  r=  rN  rT  rV  r    r!   r"   <module>rh     sd    : &  '    	 9 M I + / 9 E = * # * ) 2 A ) 
@  C >  *( $ ** &dii j.. : 
 DH5U$CF #9TuD CF
2*"2"2 
2!6 !$!v !", ,^Pv Pf
Ev EP
7
	6&R&>0
r!   