o
    k                     @   s   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	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!m"Z" ddl!m#Z# ddl!m$Z$ ddl%Z%dZ&dZ'G dd de(Z)G dd de(Z*d3ddZ+d d! Z,G d"d# d#e(Z-G d$d% d%ej.Z/ej0e'de/d&d'd(Z1G d)d* d*e(Z2G d+d, d,ej3Z4d-d. Z5d3d/d0Z6G d1d2 d2e(Z7dS )4zDThe calliope CLI/API is a framework for building library interfaces.    )absolute_import)division)unicode_literalsN)actions)backend)base)command_loading)
exceptions)parser_errors)parser_extensions)
argv_utils)config)log)metrics)
properties)yaml)named_configs)console_attr)encoding)files)pkg_resourcesz.pyz---flag-file-line-c                   @   s    e Zd ZdZdd Zdd ZdS )_FlagLocationz&--flags-file (file,line_col) location.c                 C   s   || _ |jd | _d S )N   )	file_nameline)selfr   line_col r   8/tmp/google-cloud-sdk/lib/googlecloudsdk/calliope/cli.py__init__<   s   z_FlagLocation.__init__c                 C   s   d | j| jS )Nz{}:{})formatr   r   r   r   r   r   __str__@   s   z_FlagLocation.__str__N)__name__
__module____qualname____doc__r   r"   r   r   r   r   r   9   s    r   c                   @   s*   e Zd ZdZd	ddZdd Zdd ZdS )
_ArgLocationsz"--flags-file (arg,locations) info.Nc                 C   s4   || _ |r|jd d  ng | _| jt|| d S N)arg	locationsappendr   )r   r)   r   r   r*   r   r   r   r   G   s   z_ArgLocations.__init__c                 C   s   d dd | jD S )N;c                 S      g | ]}t |qS r   )six	text_type).0locationr   r   r   
<listcomp>M       z)_ArgLocations.__str__.<locals>.<listcomp>)joinr*   r!   r   r   r   r"   L   s   z_ArgLocations.__str__c                    s   t  fdd| jD S )z4Returns True if file_name is in the locations stack.c                    s   g | ]} |j kqS r   r   )r0   xr5   r   r   r2   Q   r3   z-_ArgLocations.FileInStack.<locals>.<listcomp>)anyr*   )r   r   r   r5   r   FileInStackO   s   z_ArgLocations.FileInStackr(   )r#   r$   r%   r&   r   r"   r8   r   r   r   r   r'   D   s
    
r'   c              	   C   s  t jj}|r||rtd|||dkrtj	 }nt
j|s-td||t|}|s=td||tj|dd}t|trK|n|g}|D ]}t|jtsftd||jjd |t|jD ]i\}}	|	j}
t|	}||krt|	jtr|	jn|	jg}|D ]}t|||
|}t| || qqlt|td	tfrd
}nt|ttfrd}nd
}d||}| t | t|||
| | | |r| | qlqPd	S )z2Recursively append the flags file flags to inject.z{} recursive reference ({}).-z{} [{}] not found.z{} [{}] is empty.T)location_valuezJ{}:{}: {} file must contain a dictionary or list of dictionaries of flags.r   NFz{}={}) calliope_baseFLAGS_FILE_FLAGnamer8   r
   ArgumentErrorr    sysstdinreadospathexistsr   ReadFileContentsr   load
isinstancelistvaluedictlcr   r.   	iteritemsstrip_locationsr'   _AddFlagsFileFlagstypeboolr+   _FLAG_FILE_LINE_NAME)inject
flags_fileparent_locationsflagcontentsdatagroupmemberr)   objr   rI   	file_listrC   r*   separate_value_argr   r   r   rN   T   s^   







rN   c                    s   t jj  d t fdd| D s| S d}g }| D ])}|r(d}t|| q| kr/d}q|r@t||td  q|| q|S )a  Applies FLAGS_FILE_FLAG in args and returns the new args.

  The basic algorithm is arg list manipulation, done before ArgParse is called.
  This function reaps all FLAGS_FILE_FLAG args from the command line, and
  recursively from the flags files, and inserts them into a new args list by
  replacing the --flags-file=YAML-FILE flag by its constituent flags. This
  preserves the left-to-right precedence of the argument parser. Internal
  _FLAG_FILE_LINE_NAME flags are also inserted into args. This specifies the
  flags source file and line number for each flags file flag, and is used to
  construct actionable error messages.

  Args:
    args: The original args list.

  Returns:
    A new args list with all FLAGS_FILE_FLAG args replaced by their constituent
    flags.
  =c                    s   g | ]}| kp| qS r   
startswithr0   r)   rU   flag_eqr   r   r2      s    z#_ApplyFlagsFile.<locals>.<listcomp>FTN)r;   r<   r=   r7   rN   r_   lenr+   )argspeeknew_argsr)   r   ra   r   _ApplyFlagsFile   s    
rg   c                   @   s"   e Zd ZdZdddZdd ZdS )RunHookzEncapsulates a function to be run before or after command execution.

  The function should take **kwargs so that more things can be passed to the
  functions in the future.
  Nc                 C   s   || _ |r|nd| _|| _dS )aN  Constructs the hook.

    Args:
      func: function, The function to run.
      include_commands: str, A regex for the command paths to run.  If not
        provided, the hook will be run for all commands.
      exclude_commands: str, A regex for the command paths to exclude.  If not
        provided, nothing will be excluded.
    z.*N)_RunHook__func_RunHook__include_commands_RunHook__exclude_commands)r   funcinclude_commandsexclude_commandsr   r   r   r      s   

zRunHook.__init__c                 C   s:   t | j|s	dS | jrt | j|rdS | j|d dS )zRuns this hook if the filters match the given command.

    Args:
      command_path: str, The calliope command path for the command that was run.

    Returns:
      bool, True if the hook was run, False if it did not match.
    F)command_pathT)rematchrj   rk   ri   r   ro   r   r   r   Run   s   	zRunHook.RunNN)r#   r$   r%   r&   r   rs   r   r   r   r   rh      s    
rh   c                   @   s   e Zd ZdZdddZdS )_SetFlagsFileLinez$FLAG_INTERNAL_FLAG_FILE_LINE action.Nc                 C   s8   t |dst|dtt |j|j t	| d S )Nflags_locations)
hasattrsetattrcollectionsdefaultdictsetrv   r)   addr.   r/   )r   parser	namespacevaluesoption_stringr   r   r   __call__   s   
z_SetFlagsFileLine.__call__r(   )r#   r$   r%   r&   r   r   r   r   r   ru      s    ru   Tz;Internal *--flags-file* flag, line number, and source file.defaultactionhiddenhelpc                   @   s   e Zd ZdZedZ			d!ddZedd Z	d"d	d
Z
d"ddZdd Zdd Z	d#ddZ	d#ddZdd Zdd Zdd Z	d$ddZdd Zdd  ZdS )%	CLILoaderzBA class to encapsulate loading the CLI and bootstrapping the REPL.z(?:([\w\.]+)\.)?([^\.]+)FNc                 C   sr   || _ || _| jstd|| _|pt j| _|| _	|| _
|| _g | _g | _g | _tt| _i | _i | _dS )a  Initialize Calliope.

    Args:
      name: str, The name of the top level command, used for nice error
        reporting.
      command_root_directory: str, The path to the directory containing the main
        CLI module.
      allow_non_existing_modules: True to allow extra module directories to not
        exist, False to raise an exception if a module does not exist.
      logs_dir: str, The path to the root directory to store logs in, or None
        for no log files.
      version_func: func, A function to call for a top-level -v and
        --version flag. If None, no flags will be available.
      known_error_handler: f(x)->None, A function to call when an known error is
        handled. It takes a single argument that is the exception.
      yaml_command_translator: YamlCommandTranslator, An instance of a
        translator that will be used to load commands written as a yaml spec.

    Raises:
      backend.LayoutException: If no command root directory is given.
    z*You must specify a command root directory.N)_CLILoader__name"_CLILoader__command_root_directoryr   LayoutException&_CLILoader__allow_non_existing_modulesr   Pathslogs_dir_CLILoader__logs_dir_CLILoader__version_func_CLILoader__known_error_handler#_CLILoader__yaml_command_translator_CLILoader__pre_run_hooks_CLILoader__post_run_hooks_CLILoader__modulesry   rz   rH   _CLILoader__modules_by_parent_CLILoader__missing_components_CLILoader__release_tracks)r   r=   command_root_directoryallow_non_existing_modulesr   version_funcknown_error_handleryaml_command_translatorr   r   r   r      s"   
zCLILoader.__init__c                 C      | j S r(   )r   r!   r   r   r   r   *     z!CLILoader.yaml_command_translatorc                 C   s    |j std||f| j|< dS )a  Adds a release track to this CLI tool.

    A release track (like alpha, beta...) will appear as a subgroup under the
    main entry point of the tool.  All groups and commands will be replicated
    under each registered release track.  You can implement your commands to
    behave differently based on how they are called.

    Args:
      release_track: base.ReleaseTrack, The release track you are adding.
      path: str, The full path the directory containing the root of this group.
      component: str, The name of the component this release track is in, if
        you want calliope to auto install it for users.

    Raises:
      ValueError: If an invalid track is registered.
    zLYou may only register alternate release tracks that have a different prefix.N)prefix
ValueErrorr   )r   release_trackrC   	componentr   r   r   AddReleaseTrack.  s   zCLILoader.AddReleaseTrackc                 C   s   | j |||f dS )a  Adds a module to this CLI tool.

    If you are making a CLI that has subgroups, use this to add in more
    directories of commands.

    Args:
      name: str, The name of the group to create under the main CLI.  If this is
        to be placed under another group, a dotted name can be used.
      path: str, The full path the directory containing the commands for this
        group.
      component: str, The name of the component this command module is in, if
        you want calliope to auto install it for users.
    N)r   r+   )r   r=   rC   r   r   r   r   	AddModuleD  s   zCLILoader.AddModulec                 C   r   )z'Returns modules added to this CLI tool.)r   r!   r   r   r   
GetModulesT  r   zCLILoader.GetModulesc                 C   r   )a  Returns info about added modules (if any) for each parent command group.

    Returns:
      {str: [(str, bool, str)]}, Mapping of parent group to list of
        (module_name, module_is_command, module_impl_path) tuples for each
        additional module.
    )r   r!   r   r   r   GetModulesByParentX  s   zCLILoader.GetModulesByParentc                 C      t |||}| j| dS )a  Register a function to be run before command execution.

    Args:
      func: function, The function to run.  See RunHook for more details.
      include_commands: str, A regex for the command paths to run.  If not
        provided, the hook will be run for all commands.
      exclude_commands: str, A regex for the command paths to exclude.  If not
        provided, nothing will be excluded.
    N)rh   r   r+   r   rl   rm   rn   hookr   r   r   RegisterPreRunHookb     zCLILoader.RegisterPreRunHookc                 C   r   )a  Register a function to be run after command execution.

    Args:
      func: function, The function to run.  See RunHook for more details.
      include_commands: str, A regex for the command paths to run.  If not
        provided, the hook will be run for all commands.
      exclude_commands: str, A regex for the command paths to exclude.  If not
        provided, nothing will be excluded.
    N)rh   r   r+   r   r   r   r   RegisterPostRunHookp  r   zCLILoader.RegisterPostRunHookc                    s$   d |  fddt| jD S )zGets the components that need to be installed to run the given command.

    Args:
      command_path: [str], The path of the command being run.

    Returns:
      [str], The component names of the components that should be installed.
    .c                    s*   g | ]\}} |ks  |d  r|qS )r   r^   )r0   rC   r   path_stringr   r   r2     s
    z9CLILoader.ComponentsForMissingCommand.<locals>.<listcomp>)r4   r.   rL   r   rr   r   r   r   ComponentsForMissingCommand~  s   
	

z%CLILoader.ComponentsForMissingCommandc                 C   s   t |dk rg S tj|d }|r|| jvrd}|d }|r%|dd n|dd }|s/g S t }| jD ]}|g|jg | ||< q5|rQ||= |g| |tjj< |S )a  Finds other release tracks this command could be in.

    The returned values are not necessarily guaranteed to exist because the
    commands could be disabled for that particular release track.  It is up to
    the caller to determine if the commands actually exist before attempting
    use.

    Args:
      command_path: [str], The path of the command being run.

    Returns:
      {ReleaseTrack: [str]}, A mapping of release track to command path of other
      places this command could be found.
       r   Nr   )rc   r;   ReleaseTrack
FromPrefixr   rJ   r   GA)r   ro   trackrootsub_pathresultstr   r   r   %ReplicateCommandPathForAllOtherTracks  s    
z/CLILoader.ReplicateCommandPathForAllOtherTracksc              	   C   s  | j D ]}\}}}|t}|r|dtt  }tj|}|dd\}}| j|| j	d}t
jjg| jD ]I}	|rad| jg|	jrF|	jgng  |rQ|ddgng  }
| j|
 |||f q6|rd| jg|	jro|	jgng  |ddg }|| j|< q6q| j| jdd}t|g| jgt
jjt j| d}| | td	d
 | j D }t| jD ]6\}	\}}| j|| j	d}|r|g|j |	j< |j!|	jd|	d}|j"||d q|r|| j| j d|	j < q| #|}|S )zoUses the registered information to generate the CLI tool.

    Returns:
      CLI, The generated CLI tool.
    Nr   r   )r   r   _r9   Fc                 s   s    | ]}|j V  qd S r(   )r   )r0   r   r   r   r   	<genexpr>  s    z%CLILoader.Generate.<locals>.<genexpr>T)allow_emptyrelease_track_override)ignore)$r   endswith_COMMAND_SUFFIXrc   r   PATH_RErq   rX   &_CLILoader__ValidateCommandOrGroupInfor   r;   r   r   r   r4   r   r   replacer   r+   r   r   r   CommandGroupuuiduuid4hex!_CLILoader__AddBuiltinGlobalFlagsr{   keysr.   rL   _groups_to_loadLoadSubElementCopyAllSubElementsTo_CLILoader__MakeCLI)r   module_dot_pathmodule_dir_pathr   
is_commandrq   r   cmd_or_grp_name	impl_pathr   parent_group_name
group_name	top_grouptrack_names
module_dirtrack_groupclir   r   r   Generate  sl   




zCLILoader.Generatec                 C   s8   t j|\}}t||s|rdS td||S )a  Generates the information necessary to be able to load a command group.

    The group might actually be loaded now if it is the root of the SDK, or the
    information might be saved for later if it is to be lazy loaded.

    Args:
      impl_path: str, The file path to the command implementation for this
        command or group.
      allow_non_existing_modules: True to allow this module directory to not
        exist, False to raise an exception if this module does not exist.

    Raises:
      LayoutException: If the module directory does not exist and
      allow_non_existing is False.

    Returns:
      impl_path or None if the module directory does not exist and
      allow_non_existing is True.
    Nz.The given module directory does not exist: {0})rB   rC   splitr   IsImportabler   r   r    )r   r   r   module_rootmoduler   r   r   __ValidateCommandOrGroupInfo  s   z&CLILoader.__ValidateCommandOrGroupInfoc              	   C   sv  t j|j t j|j t j|j | jdur+|jjdddt jt	
| jdd |jjddt jd	tjd
 |jjdt tjt jdt	tjjjd |jjddt	tjjjdd |jjddt	tjjjdd |jjddt	tjjjddd |jjddt	tjjjddd |jjdt	tjjjddd |jjddt	tjjjddd t|j dS )aG  Adds in calliope builtin global flags.

    This needs to happen immediately after the top group is loaded and before
    any other groups are loaded.  The flags must be present so when sub groups
    are loaded, the flags propagate down.

    Args:
      top_element: backend._CommandCommon, The root of the command tree.
    Nz-vz	--versionTzTPrint version information and exit. This flag is only available at the global level.)do_not_propagatecategoryr   r   z--configurationCONFIGURATIONa+          File name of the configuration to use for this command invocation.
        For more information on how to use configurations, run:
        `gcloud topic configurations`.  You can also use the {0} environment
        variable to set the equivalent of this flag for a terminal
        session.)metavarr   r   z--verbosityz0Override the default verbosity for this command.)choicesr   r   r   r   z--user-output-enabledz*Print user intended output to the console.)r   r   r   z
--log-httpz5Log all HTTP server requests and responses to stderr.z--authority-selectorzTHIS ARGUMENT NEEDS HELP TEXT.r   z--authorization-token-filez--credential-file-override)r   r   r   z--http-timeout)r;   r<   AddToParseraiFLATTEN_FLAGFORMAT_FLAGr   add_argumentCOMMONLY_USED_FLAGSr   FunctionExitActionr    r   CLOUDSDK_ACTIVE_CONFIG_NAMEr   OrderedVerbosityNamesDEFAULT_VERBOSITY_STRINGStorePropertyr   VALUEScore	verbosityStoreBooleanPropertyuser_output_enabledlog_httpauthauthority_selectorauthorization_token_filecredential_file_overridehttp_timeoutFLAG_INTERNAL_FLAG_FILE_LINE)r   top_elementr   r   r   __AddBuiltinGlobalFlags  s   


	z!CLILoader.__AddBuiltinGlobalFlagsc                 C   s~   dt jvs
dt jv r$t| j tt jd}|r$tj|}t	| t
jjj r1|jdd t| j|| j| j| j}|S )zGenerate a CLI object from the given data.

    Args:
      top_element: The top element of the command tree
        (that extends backend.CommandCommon).

    Returns:
      CLI, The generated CLI tool.
    _ARGCOMPLETE_ARGCOMPLETE_TRACET)	recursive)rB   environr   AddFileLoggingr   r   GetEncodedValueVALID_VERBOSITY_STRINGSgetSetVerbosityr   r   r   disable_command_lazy_loadingGetBoolLoadAllSubElementsCLIr   r   r   r   )r   r   verbosity_stringr   r   r   r   r   	__MakeCLIo  s   
zCLILoader.__MakeCLI)FNNNNr(   rt   )F)r#   r$   r%   r&   rp   compiler   r   propertyr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r      s0    

.




/=
Zr   c                       s0   e Zd ZdZ fddZdd Zdd Z  ZS )_CompletionFinderzCalliope overrides for argcomplete.CompletionFinder.

  This makes calliope ArgumentInterceptor and actions objects visible to the
  argcomplete monkeypatcher.
  c                    s*   | j }|j| _ tt|  }|r|| _ |S r(   )_parserr}   superr  _patch_argument_parser)r   r   active_parsers	__class__r   r   r    s   z(_CompletionFinder._patch_argument_parserc                 C   sx   |   }t }d| _z| jj|dd  |d W n	 ty"   Y nw d| _| |||dd }| |}| 	|||S )NTr   )r~   Fc                  W      d S r(   r   )r   r   r   r   <lambda>  s    z4_CompletionFinder._get_completions.<locals>.<lambda>)
r  r   	Namespace
completingr  parse_known_argsBaseExceptioncollect_completionsfilter_completionsquote_completions)r   
comp_wordscword_prefixcword_prequotelast_wordbreak_posr  parsed_argscompletionsr   r   r   _get_completions  s    
z"_CompletionFinder._get_completionsc                    s   d}d}d}d}d}|srfdd|D }|}	n	|dkr!|}	n|}	t tjd	|v r/d
}	n|dkr<d
}	dd |D }|	D ]  fdd|D }q>t| ddrj|}
t|dkrj|d d |
vrj|sj|d  d7  < |S )a  Returns the completion (less aggressively) quoted for the shell.

    If the word under the cursor started with a quote (as indicated by a
    nonempty ``cword_prequote``), escapes occurrences of that quote character
    in the completions, and adds the quote to the beginning of each completion.
    Otherwise, escapes *most* characters that bash splits words on
    (``COMP_WORDBREAKS``), and removes portions of completions before the first
    colon if (``COMP_WORDBREAKS``) contains a colon.

    If there is only one completion, and it doesn't end with a
    **continuation character** (``/``, ``:``, or ``=``), adds a space after
    the completion.

    Args:
      completions: The current completion strings.
      cword_prequote: The current quote character in progress, '' if none.
      last_wordbreak_pos: The index of the last wordbreak.

    Returns:
      The completions quoted for the shell.
    z\();<>|&$* 	
`"'z\`"$\z=/:)tcshfishzshc                    s   g | ]
}| d  d qS )r   Nr   r0   c)r#  r   r   r2         z7_CompletionFinder.quote_completions.<locals>.<listcomp>"_ARGCOMPLETE_SHELL 'c                 S   s   g | ]}| d dqS )r1  z'\''r   r+  r   r   r   r2     s    c                    s   g | ]
}|  d   qS )r'  r2  r+  )charr   r   r2     r-  append_spaceFr   r    )r   r  rB   r  getattrrc   )r   r%  r"  r#  no_quote_specialdouble_quote_specialsingle_quote_specialcontinuation_specialno_escaping_shellsspecial_charscontinuation_charsr   )r3  r#  r   r    s:   z#_CompletionFinder.quote_completions)r#   r$   r%   r&   r  r&  r  __classcell__r   r   r  r   r    s
    r  c                 K   s   dt jvrdS d}d}z5tjj}tjtj_dt jv r$tj}dd }|t_t }|| fddi| W |r8|tj_|r?|t_dS dS |rG|tj_|rL|t_w )zARuns argcomplete.autocomplete on a calliope argument interceptor.r   Nr   c                   S   r  r(   r   r   r   r   r   _DisableMuteStderr
  s   z(_ArgComplete.<locals>._DisableMuteStderralways_complete_optionsF)rB   r  argcompleteargparser  r   mute_stderrr  )r   kwargsrD  r~   r@  	completerr   r   r   _ArgComplete  s8   



rG  c           	      C   s   ~|d }|dd }| j tjurt|| j | z| j| }W n ty;   |d| jf}td| }t| |w |	||\}}|rZt
|tjg  t|tj| dS dS )z>argparse._SubParsersAction.__call__ version 1.2.1 MonkeyPatch.r   r   Nz, zunknown parser %r (choices: %s))destrC  SUPPRESSrx   _name_parser_mapKeyErrorr4   r   r>   r  vars
setdefault_UNRECOGNIZED_ARGS_ATTRr7  extend)	r   r}   r~   r   r   parser_namearg_stringstupmsgr   r   r   _SubParsersActionCall  s"   rT  c                   @   sR   e Zd ZdZdd Zdd Zedd Zedd	 Zd
d Z	dddZ
dd ZdS )r  zA generated command line tool.c                 C   s*   || _ |j| _|| _|| _|| _|| _d S r(   )
_CLI__namer  _CLI__parser_CLI__top_element_CLI__pre_run_hooks_CLI__post_run_hooks_CLI__known_error_handler)r   r=   r   pre_run_hookspost_run_hooksr   r   r   r   r   ?  s   
zCLI.__init__c                 C   r   r(   rW  r!   r   r   r   _TopElementI  s   zCLI._TopElementc                 C   r   r(   )rU  r!   r   r   r   r=   L  r   zCLI.namec                 C   r   r(   r]  r!   r   r   r   r   P  r   zCLI.top_elementc                 C   s   | j |S )zChecks if given command exists.

    Args:
      cmd: [str], The command path not including any arguments.

    Returns:
      True, if the given command exist, False otherwise.
    )rW  IsValidSubPath)r   cmdr   r   r   IsValidCommandT  s   	zCLI.IsValidCommandNTc           
   
      sR  t |tjr
tdtjt_tjdkrttj	_
|rtjj |s)t dd }tj| tj  j dtjrCdd |D n|}d}d}z>zʈjt|}|jdur^|j  | }d|  |  |j!durw|j!"  t#$d}t#%d}t&tj' dkrtjj(j)*  tj+tjj(j) d j,D ]}|-  q|j-|d	j.D ]}|-  qt t/j0r fd
d}| W W tj1  tj2  |durt#$| |durt#%| S S t(3 t4j5 W W tj1  tj2  |dur
t#$| |durt#%| S S  t6j7yL }	 z)|	j8W  Y d}	~	W tj1  tj2  |dur<t#$| |durGt#%| S S d}	~	w t9ye }	 z:|	  W Y d}	~	nd}	~	ww W tj1  tj2  |dur{t#$| |durt#%| dS dS tj1  tj2  |durt#$| |durt#%| w w )am  Execute the CLI tool with the given arguments.

    Args:
      args: [str], The arguments from the command line or None to use sys.argv
      call_arg_complete: Call the _ArgComplete function if True

    Returns:
      The result of executing the command determined by the command
      implementation.

    Raises:
      ValueError: for ill-typed arguments.
    z5Execute expects an iterable of strings, not a string.z1.1r   Nc                 S   r-   r   )r   Decoder`   r   r   r   r2     r3   zCLI.Execute.<locals>.<listcomp>r   r   )r   rd   c               
   3   sN    zD ]} | V  qW dS  t y& } z|  W Y d}~dS d}~ww )zActivates generator exceptions.N)	Exception_HandleAllErrors)resourceexccommand_path_string	resourcesr   specified_arg_namesr   r   _Yield  s   zCLI.Execute.<locals>._Yield);rG   r.   string_typesr   r/   rC  str__version__rT  _SubParsersActionr   rG  rW  r   r   GetDecodedArgvr   FLAG_OVERRIDE_STACKPushFromArgsr   r   PushInvocationValuesrU  PY2rV  
parse_argsrg   CONCEPT_ARGSParseConcepts_GetCommandr4   GetPathGetSpecifiedArgNamesCONCEPTSResetr   SetUserOutputEnabledr  rc   GetInvocationStackr   command_nameSetSetInvocationValuerX  rs   rY  typesGeneratorTypePopInvocationValuesPopCommandsr   CLOUD_SDK_VERSIONr	   DryRunErrorrequestrc  rd  )
r   rd   call_arg_completeargvold_user_output_enabledold_verbositycalliope_commandr   rk  rf  r   rg  r   Execute_  s   

































zCLI.Executec                 C   s   dt jv rt jd dkr|dt|ddi}tt|dddd}|dur(||d	< tj|tj||j|d
 tj||j||d t	
||| j dS )a@  Handle all errors.

    Args:
      exc: Exception, The exception that was raised.
      command_path_string: str, The '.' separated command path.
      specified_arg_names: [str], The specified arg named scrubbed for metrics.

    Raises:
      exc or a core.exceptions variant that does not produce a stack trace.
    CLOUDSDK_CORE_DRY_RUN1
error_code	exit_coder   payloadNstatus_codehttp_status_code)errorerror_extra_info)r  )rB   r  r7  r   r  r   r  r  Errorr	   HandleErrorrZ  )r   rf  rh  rj  r  r  r   r   r   rd    s"   
zCLI._HandleAllErrors)NT)r#   r$   r%   r&   r   r^  r  r=   r   ra  r  rd  r   r   r   r   r  <  s    



zr  r(   )8r&   
__future__r   r   r   rC  ry   rB   rp   r?   r  r   rB  googlecloudsdk.callioper   r   r   r;   r   r	   r
   r   googlecloudsdk.corer   r   r   r   r   r   "googlecloudsdk.core.configurationsr   googlecloudsdk.core.consoler   googlecloudsdk.core.utilr   r   r   r.   r   rQ   objectr   r'   rN   rg   rh   Actionru   Argumentr   r   CompletionFinderr  rG  rT  r  r   r   r   r   <module>   sl   
?*'	   m
$ 