o
    )TiT                     @   s  U d Z ddlZddlZddlmZmZmZ ddlmZ ddl	m
Z
 ddlmZ ddlmZmZ dd	lmZmZmZmZmZ dd
lmZmZ ddlmZ ddlmZmZ ddlmZ ddlm Z  ddl!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z) g dZ*dede+fddZ,dd Z-eeefZ.dd Z/G dd deZ0edddZ1ee2d< e
dd Z3edd dZ4ee2d< G d!d" d"eZ5G d#d$ d$eZ6G d%d& d&eZ7G d'd( d(eZ8G d)d* d*eZ9G d+d, d,Z:dS )-z1Collection of useful actions to define arguments.    N)SUPPRESS_HelpAction_VersionAction)Action)contextmanager)
ContextVar)AnyOptional   )r   NonParsingActionis_subclassis_subclasses_disabledparser_context)get_loader_exceptions
load_value)	Namespace)_get_config_read_moderuamel_support)change_to_path_dir)ArgumentParser)Pathargument_errordefault_config_option_helpget_import_pathimport_objectindent_textiter_to_set_strparse_value_or_config)ActionConfigFile
ActionFailActionParserActionYesNoactionreturnc                 C   s(   | j dv st| j tr| j dkrdS dS )zChecks whether an action produces a list value.

    Args:
        action: An argparse action to check.

    Returns:
        bool: True if produces list otherwise False.
    >   *+r   TF)nargs
isinstanceintr"    r*   I/home/ubuntu/.local/lib/python3.10/site-packages/jsonargparse/_actions.py_is_action_value_list$   s    	r,   c                    s0    fdd}|| j  | jD ]}||j qd S )Nc                    s*    fdd| D }|D ]}|  | qd S )Nc                    s   g | ]	}t | r|qS r*   )r'   .0atypesr*   r+   
<listcomp>4       z2remove_actions.<locals>.remove.<locals>.<listcomp>)remove)actions
rm_actionsr"   r0   r*   r+   r4   3   s   zremove_actions.<locals>.remove)_actions_action_groups_group_actions)parserr1   r4   action_groupr*   r0   r+   remove_actions2   s
   

r<   c                 C   s*   t | trdd | D S dd |  D S )Nc                 S   s   g | ]	}t |ts|qS r*   r'   non_parsing_actionsr-   r*   r*   r+   r2   B   r3   z.filter_non_parsing_actions.<locals>.<listcomp>c                 S   s    i | ]\}}t |ts||qS r*   r=   )r.   kr/   r*   r*   r+   
<dictcomp>C        z.filter_non_parsing_actions.<locals>.<dictcomp>)r'   listitems)r5   r*   r*   r+   filter_non_parsing_actions@   s   
rD   c                       sd   e Zd ZdZ fddZdddZedd Zed	d
 Zedd Z	edddZ
dd Z  ZS )r   zVAction to indicate that an argument is a configuration file or a configuration string.c                    st   d|v r|    |d }t|dkr|d ndd |D d }d|v r'tdd	|vr/d
|d	< t jdi | dS )z*Initializer for ActionConfigFile instance.defaultoption_stringsr
   r   c                 S   s    g | ]}|d d dkr|qS )r      --r*   r.   xr*   r*   r+   r2   N   rA   z-ActionConfigFile.__init__.<locals>.<listcomp>.z,ActionConfigFile must be a top level option.helpzPath to a configuration file.Nr*   )set_default_errorlen
ValueErrorsuper__init__)selfkwargsopt_name	__class__r*   r+   rQ   I   s   &zActionConfigFile.__init__Nc                 C   s   |  ||| j| dS )zParses the given configuration and adds all the corresponding keys to the namespace.

        Raises:
            TypeError: If there are problems parsing the configuration.
        N)apply_configdest)rR   r:   cfgvaluesoption_stringr*   r*   r+   __call__U   s   zActionConfigFile.__call__c                   C   s   t d)NzEActionConfigFile does not accept a default, use default_config_files.)rO   r*   r*   r*   r+   rM   ]      z"ActionConfigFile.set_default_errorc                 C   s6   |dks	t |trtdd | jD rtdd S d S )Nconfigc                 s       | ]}t |tV  qd S N)r'   r   r-   r*   r*   r+   	<genexpr>c   s    

zBActionConfigFile._ensure_single_config_argument.<locals>.<genexpr>z<A parser is only allowed to have a single 'config' argument.)r   r   anyr7   rO   	containerr"   r*   r*   r+   _ensure_single_config_argumenta   s
   z/ActionConfigFile._ensure_single_config_argumentc                 C   s^   t |tr+t| dd d ur-d| jv r| j|j | _| jds!J | j| jtd d S d S d S )N_print_configz%srH   r)   )r'   r   getattrrf   rX   
startswithadd_argument_ActionPrintConfigrc   r*   r*   r+   _add_print_config_argumenth   s   
z+ActionConfigFile._add_print_config_argumentr#   c                 C   s  ddl m} tdd t| |  ddddd}z	t|t d}W nE tyj } z9ztt|t	r7|d }| j
|fi |}W n ttft  y_ }	 ztd| d	|	 |	d }	~	ww W Y d }~nd }~ww | j|fi |}| ||}
|j|
j ||d u rg ||< || | W d    n1 sw   Y  W d    n1 sw   Y  W d    d S W d    d S 1 sw   Y  d S )
Nr
   )skip_apply_linksF)single_subcommandT)envdefaults_skip_validation_fail_no_subcommand)modeParser key "z": )_link_argumentsrl   r   previous_config_contextr   r   	TypeErrorr'   r   strparse_stringrO   r   
parse_pathmerge_config__dict__updategetappend)r:   rY   rX   valuerl   rS   cfg_pathex_pathcfg_fileex_str
cfg_mergedr*   r*   r+   rW   p   s6   	P zActionConfigFile.apply_configc                 K   s&   ddl m} | }t||fi |S )Nr
   )get_files_completer)_completionsr   sorted)rR   prefixrS   r   files_completerr*   r*   r+   	completer   s   zActionConfigFile.completerr`   )r#   N)__name__
__module____qualname____doc__rQ   r\   staticmethodrM   re   rk   rW   r   __classcell__r*   r*   rU   r+   r   F   s    



r   previous_config)rE   c              	   c   s0    t | }zd V  W t | d S t | w r`   )r   setreset)rY   tokenr*   r*   r+   ru      s
   
ru   print_config_skipFc                       sT   e Zd Zeef fdd	ZdddZeedd Zedd	 Z	ed
d Z
  ZS )rj   c                    s(   t  j|||dddtrdnd d d S )Nr
   z	[=flags]zPrint the configuration after applying all other arguments and exit. The optional flags customizes the output and are one or more keywords separated by comma. The supported flags are:%s skip_default, skip_null.z
 comments, )rF   rX   rE   r&   metavarrL   )rP   rQ   r   )rR   rF   rX   rE   rU   r*   r+   rQ      s   

z_ActionPrintConfig.__init__Nc           	         s   |d ddd}d ddd t rd d< |d urI|d d	} fd
d|D }t|dkr9td|d  d| dd |D D ]}d| | < q@t|drj|d d u rW|jn|jd |d  |d< |j}t|dsN||_d S )NF)	subparserkey	skip_noneskip_validationskip_defaultr   )r   r   	skip_nullwith_commentscommentsr   ,c                    s   g | ]}| vr|qS r*   r*   r.   fvalid_flagsr*   r+   r2          z/_ActionPrintConfig.__call__.<locals>.<listcomp>zInvalid option "z" for c                 S   s   g | ]}|d kr|qS )r   r*   r   r*   r*   r+   r2      r   Tparent_parserr   rK   )r   splitrN   r   hasattr
subcommandr   print_config)	rR   r:   	namespacer   r[   rS   flagsinvalid_flagsflagr*   r   r+   r\      s    
(

z_ActionPrintConfig.__call__c               	   c   s0    t d} zd V  W t |  d S t |  w )NT)r   r   r   )tr*   r*   r+   skip_print_config   s
   
z$_ActionPrintConfig.skip_print_configc                 C   s   t | drKt sM| jd}| jd}|d ur|| }tdd tj|j	|fi | j W d    n1 s;w   Y  t
| d |   d S d S d S )Nr   r   r   T)lenient_check)r   r   r}   r   popr   sysstdoutwritedumpdelattrexit)r:   rY   r   r   r*   r*   r+   print_config_if_requested   s   
z,_ActionPrintConfig.print_config_if_requestedc                 C   s&   | rt | dr	dS t| dd } | sdS )Nr   Tr   F)r   rg   )r:   r*   r*   r+   is_print_config_requested   s   
z,_ActionPrintConfig.is_print_config_requestedr`   )r   r   r   r   rQ   r\   r   r   r   r   r   r   r*   r*   rU   r+   rj      s    

rj   c                       s@   e Zd Zddee f fddZdd Zdd Zd	d
 Z  Z	S )_ActionConfigLoadNbasetypec                    sR   t |dkr|| _d S |dd | _d|d< t|d< t|d< t jdi | d S )Nr   	_basetypeCONFIGr   rL   rE   r*   )rN   r   r   r   r   r   rP   rQ   )rR   r   rS   rU   r*   r+   rQ      s   
z_ActionConfigLoad.__init__c                 O   s   t |dkr| j|d< tdi |S |d d \}}}| ||}t|| jtr@|t| j|it| j|| j i| j }||| j< d S )Nr   r      r*   )	rN   r   r   _load_configr'   r}   rX   r   rz   )rR   argsrS   r:   r   r   loaded_valuer*   r*   r+   r\      s   

z_ActionConfigLoad.__call__c              
   C   s   z8t |\}}t|tstd| j d| dt| |j|| jd}W d    |W S 1 s1w   Y  |W S  tft  y^ } ztd| }td| j d|d| |d }~ww )Nrs   z": Unable to load config "")
parent_keyz- z":
Unable to load config 
)	r   r'   dictrv   rX   r   _apply_actionsr   r   )rR   r   r:   rY   r   exstr_exr*   r*   r+   r      s   


z_ActionConfigLoad._load_configc                 C   s   |  ||S r`   )r   )rR   r   r:   r*   r*   r+   
check_type  s   z_ActionConfigLoad.check_typer`   )
r   r   r   r	   typerQ   r\   r   r   r   r*   r*   rU   r+   r      s
    
r   c                       sj   e Zd ZU i Zeeef ed< ede	e
 fddZd fdd	Zdd	 Zd
d Zdd Zdd Z  ZS )_ActionHelpClassPathsub_add_kwargsr#   c                 C   s   ddl m} ||dddS )Nr
   )get_subclass_or_closed_typesT)typehint
also_listscallable_return)
_typehintsr   )clsr   r   r*   r*   r+   get_help_types  s   z#_ActionHelpClassPath.get_help_typesNc                    s2   |d ur	|| _ d S | | t jdi | d S )Nr*   )	_typehintupdate_init_kwargsrP   rQ   )rR   r   rS   rU   r*   r+   rQ     s   

z_ActionHelpClassPath.__init__c                    s   ddl m  |d| _| | j| _| jr tdd | jD s"J t| jdko/t| jd | _	t
dd | jD | _t| jdkrL| j	rHdnd|d	< | j	rRd
}nd|d< d| _t fdd| jD rhd| _d| j d}t|d< d| | j d|d< d S )Nr
   is_protocolr   c                 s   r_   r`   )r'   r   r.   br*   r*   r+   ra     s    z:_ActionHelpClassPath.update_init_kwargs.<locals>.<genexpr>r   c                 s   s    | ]}|j V  qd S r`   )r   )r.   r   r*   r*   r+   ra   !  s    ?r&   r   CLASS_PATH_OR_NAMEr   zsubclass ofc                 3   s    | ]} |V  qd S r`   r*   r   r   r*   r+   ra   +  s    z#subclass or implementer of protocolz
the given  rE   zShow the help for z
 and exit.rL   )r   r   r   r   r   _help_typesallrN   r   _single_classr   	_basename_kindrb   r   )rR   rS   msgr*   r   r+   r     s"   z'_ActionHelpClassPath.update_init_kwargsc                 O   s2   t |dkr| j|d< t| di |S | |S )Nr   r   r*   )rN   r   r   
print_help)rR   r   rS   r*   r*   r+   r\   2  s   

z_ActionHelpClassPath.__call__c              
      s  ddl m}m m} |\}}}}z| jdks| jdkr%|d u r%| jd nt|| j|W n tyD } z
t| d| |d }~ww t	 fdd| jD sct| d| d	| j
 d
| j tdd| j}	t|d| dt d}
ttd}|| j|\}}|r|| jd< |
j|	fi | j d|
_t|
tttf | |j}|r|
| td| d|
  |  d S )Nr
   )adapt_partial_callable_classimplements_protocolresolve_class_path_by_namer   r   z: c                 3   s$    | ]}t |p |V  qd S r`   )r   r   r   	val_classr*   r+   ra   H  s   " z2_ActionHelpClassPath.print_help.<locals>.<genexpr>z	: Class "z" is not a r   z\.help$r   z	Help for =)description)
class_pathskipTz(Expected a nested --*.help option, got: rK   ) r   r   r   r   r&   r   r   	Exceptionrv   rb   r   r   resubrX   r   r   r   r   r   add_class_arguments_inner_parserr<   r   rj   r   get_args_after_optr   
parse_argsr   r   r   )rR   	call_argsr   r   r:   _r   r[   r   rX   r   valpartial_skip_argsr   r*   r   r+   r   8  s8   "

z_ActionHelpClassPath.print_helpc                 C   s\   | j d }t|D ]\}}|dd}|d |kr%t|dkr#|d7 } nq	||d d  S )Nr   r   r
   )rF   	enumerater   rN   )rR   r   opt_strnumargpartsr*   r*   r+   r   [  s   
z'_ActionHelpClassPath.get_args_after_optr`   )r   r   r   r   r   rw   r   __annotations__classmethodr	   tupler   rQ   r   r\   r   r   r   r*   r*   rU   r+   r   
  s   
 #r   c                       s0   e Zd ZdZddef fddZdd Z  ZS )	r   z4Action that always fails parsing with a given error.option unavailablemessagec                    s\   t |dkr|| _d	S |d| _t|d< d|d< |d g kr#d|d< t jd
i | d	S )zInitializer for ActionFail instance.

        Args:
            message: Text for the error to show. Use ``%(option)s``/``%(value)s`` to include the option and/or value.
        r   _messagerE   FrequiredrF   r   r&   Nr*   )rN   r  r   r   rP   rQ   )rR   r  rS   rU   r*   r+   rQ   i  s   
zActionFail.__init__c                 O   sJ   t |dkr| j|d< tdi |S |\}}}}|| j||d  dS )z Always fails with given message.r   r  )r   optionNr*   )rN   r  r   error)rR   r   rS   r:   r   r   r  r*   r*   r+   r\   y  s
   
zActionFail.__call__)r  )r   r   r   r   rw   rQ   r\   r   r*   r*   rU   r+   r   f  s    r   c                       sX   e Zd ZdZddedef fddZdd	 Zd
d Zdd Ze	dd Z
dd Z  ZS )r!   zePaired options ``--[yes_prefix]opt``, ``--[no_prefix]opt`` to set ``True`` or ``False`` respectively.r   no_
yes_prefix	no_prefixc                    sr  t |dkr|| _|| _dS d|v r|dnd| _d|v r#|dnd| _t |d dkr=tt| j d|d  d	|d d }|d
| j sTtd| j d| jdurm|d  t	d| j d
| j |g7  < | jdu rd|v r|d dkrtdd|v r|d dv rd|d< |d dkrd|d< nd|d< d|d< d|vrd|d< t
j|d< t jdi | dS )zInitializer for ActionYesNo instance.

        Args:
            yes_prefix: Prefix for yes option.
            no_prefix: Prefix for no option.

        Raises:
            ValueError: If a parameter is invalid.
        r   _yes_prefixr   
_no_prefixr  rF   z) not intended for positional arguments  (rX   z).rH   z(Expected option string to start with "--z".N^--r&   r
   z6ActionYesNo with no_prefix=None only supports nargs=1.>   r
   r   z{true,yes,false,no}r   rE   Fr   r*   )rN   r
  r  r   rO   r   r   rh   r   r   r!   _boolean_typerP   rQ   )rR   r  r	  rS   rT   rU   r*   r+   rQ     s2   


(
zActionYesNo.__init__c                 O   s   t |dkr| j|d< | j|d< td
i |S t|d tr"|d nd}| jdur?|d d| j r?t|d	 | j|  dS t|d	 | j| dS )zPSets the corresponding key to True or False depending on the option string used.r   r
  r  rG   TNr   rH   r
   r*   )	rN   r
  r  r!   r'   boolrh   setattrrX   )rR   r   rS   r   r*   r*   r+   r\     s   

zActionYesNo.__call__c                 C   s~   |d | j  | _ td| j d| j | d | jd | jd< | jd ur=td| j d| j | d | jd | jd< d S d S )NrK   r  rH   r   )rX   r   r   r
  rF   r  )rR   r   r*   r*   r+   _add_dest_prefix  s    

 zActionYesNo._add_dest_prefixc                 C   s
   t |S r`   )r!   r  )rR   r   r*   r*   r+   _check_type  s   
zActionYesNo._check_typec                 C   sP   t | tr|  dv r|  dv rd} | S d} | S t | ts&td|  d| S )N>   noyestruefalse>   r  r  TFzValue not boolean: rK   )r'   rw   lowerr  rv   )rJ   r*   r*   r+   r    s   
zActionYesNo._boolean_typec                 K   s   g dS )z;Used by argcomplete to support tab completion of arguments.)r  r  r  r  r*   )rR   rS   r*   r*   r+   r     r]   zActionYesNo.completer)r   r  )r   r   r   r   rw   rQ   r\   r  r  r   r  r   r   r*   r*   rU   r+   r!     s    %

r!   c                   @   s<   e Zd ZdZdefddZedefddZedd	 Z	d
S )r    zXAction to parse option with a given parser optionally loading from file if string value.r:   c                 C   s"   || _ t| j tdstddS )zInitializer for ActionParser instance.

        Args:
            parser: A parser to parse the option with.

        Raises:
            ValueError: If the parser parameter is invalid.
        zjsonargparse.ArgumentParserz9Expected parser keyword argument to be an ArgumentParser.N)_parserr'   r   rO   )rR   r:   r*   r*   r+   rQ     s   zActionParser.__init__r#   c                 C   s$   t |tsdS |j| krtddS )NFz0Parser cannot be added as a subparser of itself.T)r'   r    r  rO   )r:   r"   r*   r*   r+   _is_valid_action_parser  s
   

z$ActionParser._is_valid_action_parserc                    s,  | dj}| d| dd }| d|j}t|dkr&tdt| t|dkr3|d ds:td	| |d d
d  fdd fdd|jD }i }t|j	
 D ]
\}}	|	| |< q[t|t| j	}
t|
dkr}td|
 g }dd}t|jD ]%}	t|	tr|	 n|d |	j |	_ fdd|	jD |	_||	 q|jd }||_|d ur||_| |_t|j|_t|j|_|jd
d  }|D ]}|jd ur|d |j |_q| j|d td | j| | j	| | j| | j|g|  i |_	g |_g |_|S )Nr"   titlerL   r   r   z7ActionParser does not accept the following parameters: r
   rH   z8ActionParser only accepts a single optional key but got rG   c                    s   t dd  d | S )Nr  rH   rK   )r   r   )r   r   r*   r+   
add_prefix  s   z5ActionParser._move_parser_actions.<locals>.add_prefixc                    s   h | ]} d  | qS )rK   r*   rI   r  r*   r+   	<setcomp>  r   z4ActionParser._move_parser_actions.<locals>.<setcomp>zActionParser conflicting keys: -r   rK   c                    s   g | ]} |qS r*   r*   )r.   r   )r  r*   r+   r2     s    z5ActionParser._move_parser_actions.<locals>.<listcomp>r)   )r   r  r   rN   rO   r   rh   required_argsrD   _option_string_actionsrC   intersectionreplacer7   r'   r!   r  rX   rF   r~   r8   r  r:   r9   ri   r   r|   extend)r:   r   rS   r   r  r   r  option_string_actionsr   r"   isectr5   rX   base_action_groupextra_action_groupsgroupr*   )r  r   r+   _move_parser_actions  sZ   


z!ActionParser._move_parser_actionsN)
r   r   r   r   r   rQ   r   r  r  r)  r*   r*   r*   r+   r      s    
r    );r   r   r   argparser   r   r   r   ArgparseAction
contextlibr   contextvarsr   typingr   r	   _commonr   r   r   r   _loaders_dumpersr   r   
_namespacer   
_optionalsr   r   _pathsr   _type_checkingr   _utilr   r   r   r   r   r   r   r   __all__r  r,   r<   r>   rD   r   r   r   ru   r   rj   r   r   r   r!   r    r*   r*   r*   r+   <module>   s>    (
I
D(\O