o
    X                     @   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	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G dd deZdd Zdd Zdd Zdd Zdd Z	 	 dd Zd(ddZdd Zd(ddZd d! d"d! d#d$d%dfd&d'ZdS ))z'argparse Actions for use with calliope.    )absolute_import)division)unicode_literalsN)base)parser_errors)log)metrics)
properties)
console_ioc                   @   s   e Zd ZdZdd ZdS )_AdditionalHelpz=Simple class for passing additional help messages to Actions.c                 C   s   || _ || _d S N)labelmessage)selfr   r    r   </tmp/google-cloud-sdk/lib/googlecloudsdk/calliope/actions.py__init__'   s   
z_AdditionalHelp.__init__N)__name__
__module____qualname____doc__r   r   r   r   r   r   $   s    r   c                 C   s8   t jddddd}|d| }|du rtd| |S )a  Get an argparse.Action from a string.

  This function takes one of the supplied argparse.Action strings (see below)
  and returns the corresponding argparse.Action class.

  This "work around" is (e.g. hack) is necessary due to the fact these required
  action mappings are only exposed through subclasses of
  argparse._ActionsContainer as opposed to a static function or global variable.

  Args:
    action: string, one of the following supplied argparse.Action names:
      'store', 'store_const', 'store_false', 'append', 'append_const', 'count',
      'version', 'parsers'.

  Returns:
    argparse.Action, the action class to use.

  Raises:
    ValueError: For unknown action string.
  Nerror)descriptionprefix_charsargument_defaultconflict_handleractionzunknown action "{0}")argparse_ActionsContainer_registry_get
ValueErrorformat)r   fake_actions_container
action_clsr   r   r   GetArgparseBuiltInAction,   s   r$   c                       G  fdddt j  S )zGet an argparse.Action that runs the provided function, and exits.

  Args:
    func: func, the function to execute.

  Returns:
    argparse.Action, the action to use.
  c                       s0   e Zd ZdZ fddZdfdd	Z  ZS )z"FunctionExitAction.<locals>.Actionz*The action created for FunctionExitAction.c                    s"   d|d< t  | jdi | d S Nr   nargsr   superr   r   kwargsAction	__class__r   r   r   b   s   z+FunctionExitAction.<locals>.Action.__init__Nc                    s*   t |j| t     td d S )Nr   )r   
LogCommandprogr   Loadedsysexitr   parser	namespacevaluesoption_stringfuncr   r   __call__f   s   z+FunctionExitAction.<locals>.Action.__call__r   r   r   r   r   r   r;   __classcell__r   r-   r:   r.   r   r-   _   s    r-   r   r-   r9   r   r>   r   FunctionExitActionU   s   
rA   c                    r%   )a  Get an argparse action that stores a value in a property.

  Also stores the value in the namespace object, like the default action. The
  value is stored in the invocation stack, rather than persisted permanently.

  Args:
    prop: properties._Property, The property that should get the invocation
      value.

  Returns:
    argparse.Action, An argparse action that routes the value correctly.
  c                       s<   e Zd ZdZddfZ fddZdfdd	Z  ZS )zStoreProperty.<locals>.Actionz%The action created for StoreProperty.Nc                    s\   t  | j|i | |d}|r|d }nd }tjd | dtjv r,tj	| _
d S d S )Noption_stringsr   _ARGCOMPLETE)r)   r   getr	   VALUESSetInvocationValueosenvironr   _StoreAction_orig_classr   argsr+   rB   r8   r-   r.   propr   r   r      s   


z&StoreProperty.<locals>.Action.__init__c                    s"   t j || t|| j| d S r   r	   rE   rF   setattrdestr4   rN   r   r   r;         z&StoreProperty.<locals>.Action.__call__r   r   r   r   r   store_propertyr   r;   r=   r   r-   rN   r?   r   r-   }   s
    
r-   r@   rR   r   rV   r   StorePropertyo   s   rW   c                    r%   )a  Get an argparse action that stores a value in a Boolean property.

  Handles auto-generated --no-* inverted flags by inverting the value.

  Also stores the value in the namespace object, like the default action. The
  value is stored in the invocation stack, rather than persisted permanently.

  Args:
    prop: properties._Property, The property that should get the invocation
      value.

  Returns:
    argparse.Action, An argparse action that routes the value correctly.
  c                       s<   e Zd ZdZddfZ fddZdfdd	Z  ZS )	z$StoreBooleanProperty.<locals>.Actionz,The action created for StoreBooleanProperty.boolNc                    s   t |}d|vrd|d< |d}|r|d }nd }|r1|dr1d| _d|d< d |d< d |d< nd| _t | j|i | tjd | d	t	j
v rRtj| _d S d S )
Nr'   r   rB   z--no-TconstchoicesFrC   )dictrD   
startswith	_invertedr)   r   r	   rE   rF   rG   rH   r   rI   rJ   rK   rM   r   r   r      s$   



z-StoreBooleanProperty.<locals>.Action.__init__c                    sL   | j r|dg fv rd}n	d}n|g krd}tj || t|| j| d S )Ntruefalse)r]   r	   rE   rF   rP   rQ   r4   rR   r   r   r;      s   z-StoreBooleanProperty.<locals>.Action.__call__r   rT   r   rV   r?   r   r-      s
    
r-   r@   rR   r   rV   r   StoreBooleanProperty   s   *r`   c                       G  fdddt j  S )a  Get an argparse action that stores a constant in a property.

  Also stores the constant in the namespace object, like the store_true action.
  The const is stored in the invocation stack, rather than persisted
  permanently.

  Args:
    prop: properties._Property, The property that should get the invocation
      value.
    const: str, The constant that should be stored in the property.

  Returns:
    argparse.Action, An argparse action that routes the value correctly.
  c                       s<   e Zd ZdZdfZ fddZdfdd	Z  ZS )	z"StoreConstProperty.<locals>.Actionz*The action created for StoreConstProperty.valuec                    s@   t |}d|d< t | j|i | dtjv rtj| _d S d S )Nr   r'   rC   )r[   r)   r   rG   rH   r   _StoreConstActionrJ   )r   rL   r+   r,   r   r   r      s   
z+StoreConstProperty.<locals>.Action.__init__Nc                    s"   t j | t|| j  d S r   rO   r4   )rY   rN   r   r   r;      rS   z+StoreConstProperty.<locals>.Action.__call__r   rT   r   r-   rY   rN   r?   r   r-      s
    
r-   r@   )rN   rY   r   rd   r   StoreConstProperty   s   re   c                    s    fdd}t |S )zGet an argparse.Action that prints a short help.

  Args:
    command: calliope._CommandCommon, The command object that we're helping.

  Returns:
    argparse.Action, the action to use.
  c                      s"   t  jd tj   d S )Nz-h)r   Helpdotted_namer   outwriteGetUsager   commandr   r   Func  s   zShortHelpAction.<locals>.Func)rA   )rl   rm   r   rk   r   ShortHelpAction  s   
rn   c                    ra   )a  Get an argparse.Action that renders a help document from markdown.

  Args:
    command: calliope._CommandCommon, The command object that we're helping.
    default_style: str, The default style if not specified in flag value.

  Returns:
    argparse.Action, The action to use.
  c                       s4   e Zd ZdZ fddZdfdd	Z  ZS )z$RenderDocumentAction.<locals>.Actionz,The action created for RenderDocumentAction.c                    s&   rd|d< t  | jdi | d S r&   r(   r*   )r-   r.   default_styler   r   r     s   z-RenderDocumentAction.<locals>.Action.__init__Nc              	      sR  ddl m} ddlm} t|j| rt  }d}d}	|D ](}
t	
|
D ] \}}|dkr3|}q(|dkr:|}q(|dkrA|}	q(td|q!|	du rQ j}	t j| |d	v r^d
}t| }tjddrpt nd}|dkr{t }nd}|dkr }nd}|j|||ptj||	||d t  |rt|  td dS )a<  Render a help document according to the style in values.

      Args:
        parser: The ArgParse object.
        namespace: The ArgParse namespace.
        values: The --document flag ArgDict() value:
          style=STYLE
            The output style. Must be specified.
          title=DOCUMENT TITLE
            The document title.
          notes=SENTENCES
            Inserts SENTENCES into the document NOTES section.
        option_string: The ArgParse flag string.

      Raises:
        parser_errors.ArgumentError: For unknown flag value attribute name.
      r   )markdownrender_documentNnotesstyletitlez Unknown document attribute [{0}])z--helphelptopictextT)outputlinterdevsite)rh   rs   ru   command_metadatacommand_node)googlecloudsdk.callioperp   &googlecloudsdk.core.document_renderersrr   r   r/   r0   r   r1   six	iteritemsr   ArgumentErrorr!   rg   rf   ioStringIOMarkdownr
   IsInteractiveGetCommandMetaDataRenderDocumentr   rh   RanMoregetvaluer2   r3   )r   r5   r6   r7   r8   rp   rr   rt   rs   ru   
attributesnamerb   mdrh   	meta_datar}   rl   ro   r   r   r;     s\   
	z-RenderDocumentAction.<locals>.Action.__call__r   r<   r   r-   rl   ro   r?   r   r-     s    r-   r@   r   r   r   r   RenderDocumentAction  s   Wr   c                 C   s^   ddl m} | }|  D ]}|jD ]}|j| t|tj	r'|j
| qq| j|_|S )Nr   rq   )r   rr   CommandMetaDataGetAllAvailableFlagsrB   flagsappend
isinstancer   rc   
bool_flagsis_group)rl   rr   r|   argarg_namer   r   r   r     s   
r   c                    sP   t stdttjsttjstdG  fdddtj  S )a(  Allows an function hook to be injected before an Action executes.

  Wraps an Action in another action that can execute an arbitrary function on
  the argument value before passing invocation to underlying action.
  This is useful for:
  - Chaining actions together at runtime.
  - Adding additional pre-processing or logging to an argument/flag
  - Adding instrumentation to runtime execution of an flag without changing the
  underlying intended behavior of the flag itself

  Args:
    action: action class to be wrapped. Either a subclass of argparse.Action or
      a string representing one of the built in arg_parse action types. If None,
      argparse._StoreAction type is used as default.
    func: callable, function to be executed before invoking the __call__ method
      of the wrapped action. Takes value from command line.
    additional_help: _AdditionalHelp, Additional help (label, message) to be
      added to action help

  Returns:
    argparse.Action, wrapper action to use.

  Raises:
    TypeError: If action or func are invalid types.
  z1func should be a callable of the form func(value)zwaction should be either a subclass of argparse.Action or a string representing one of the default argparse Action Typesc                       sH   e Zd ZdZZedd Zdd Z fddZdd	d
Z	  Z
S )z_PreActionHook.<locals>.ActionzAction Wrapper Class.c                 S   s
   || _ d S r   )wrapped_action)clsr   r   r   r   SetWrappedAction.  s   
z/_PreActionHook.<locals>.Action.SetWrappedActionc                 S   s&   t | jtjrt| j}|S | j}|S r   )r   r   r   string_typesr$   )r   r#   r   r   r   _GetActionClass4  s
   
z._PreActionHook.<locals>.Action._GetActionClassc                    s   r| dd }dj|j|d< |  |i || _| _| jj|d< | jj	|d< | jj
|d< | jj|d< t | j|i | d S )Nrv    z{0} {1}
+
{2}r'   rY   rZ   rB   )rD   rstripr!   r   r   r   _wrapped_actionr:   r'   rY   rZ   rB   r)   r   )r   rL   r+   original_help)r-   r.   additional_helpr:   r   r   r   ;  s   
z'_PreActionHook.<locals>.Action.__init__Nc                 S   sb   t || jd }t|trt|dk r| | n|s"| | jj n| | | |||| d S )N   )getattrrQ   r   listlenr:   r   rY   )r   r5   r6   rb   r8   
flag_valuer   r   r   r;   O  s   


z'_PreActionHook.<locals>.Action.__call__r   )r   r   r   r   r   classmethodr   r   r   r;   r=   r   r-   r   r   r:   r?   r   r-   )  s    
r-   )callable	TypeErrorr   r   r   
issubclassr   r-   )r   r:   r   r   r   r   _PreActionHook  s   4r   c                 C      dS NTr   _r   r   r   <lambda>b      r   c                 C   r   r   r   r   r   r   r   r   c  r   zFlag {flag_name} is deprecated.z"Flag {flag_name} has been removed.Fc                    s^   rt d|j| d n	t d|j| d |sd} fdd}|r)t|| S t||dS )a4  Prints a warning or error message for a flag that is being deprecated.

  Uses a _PreActionHook to wrap any existing Action on the flag and
  also adds deprecation messaging to flag help.

  Args:
    flag_name: string, name of flag to be deprecated
    show_message: callable, boolean function that takes the argument value as
      input, validates it against some criteria and returns a boolean. If true
      deprecation message is shown at runtime. Deprecation message will always
      be appended to flag help.
    show_add_help: boolean, whether to show additional help in help text.
    warn: string, warning message, 'flag_name' template will be replaced with
      value of flag_name parameter
    error: string, error message, 'flag_name' template will be replaced with
      value of flag_name parameter
    removed: boolean, if True warning message will be printed when show_message
      fails, if False error message will be printed
    action: argparse.Action, action to be wrapped by this action

  Returns:
    argparse.Action, deprecation action to use.
  z	(REMOVED))	flag_namez(DEPRECATED)storec                    s,   | rrt  jt j d S d S r   )r   r   r   r   warning)rb   add_helpremovedshow_messager   r   DeprecationFunc  s
   z*DeprecationAction.<locals>.DeprecationFuncN)r   r!   r   )r   r   show_add_helpwarnr   r   r   r   r   r   r   DeprecationAction`  s    r   r   )r   
__future__r   r   r   r   r   rG   r2   r~   r   r   googlecloudsdk.corer   r   r	   googlecloudsdk.core.consoler
   r   objectr   r$   rA   rW   r`   re   rn   r   r   r   r   r   r   r   r   <module>   sD   )'=&m
e
_