o
    
c                     @   s0  d 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
Z
ejdkr4ddlmZ nddlmZ ejejejejejgZejdkrVeej dd Znd	d ZeeZi Zd$d
dZd$ddZG dd dejejejZG dd deZ G dd de!Z"G dd de Z#G dd de Z$G dd de Z%dZ&dZ'dZ(dZ)G dd dej*Z*d d! Z+d"d# Z,ej-j+ej-_.e+ej-_+ej/Z/ejZejZejZej0Z0ej1Z1ej2Z2ej3Z3ej4Z4ej5Z5ej6Z6ej7Z7ej8Z8ej9Z9eZ:eZ;eZ<eZ=eZ>eZ?e*Z@e*ZAej-j+ej-_Bej-j+ej-_Ce*jDe*_Ee*jFe*_GeZHeZIeZJdS )%z
A drop-in replacement for `argparse` that allows options to also be set via config files and/or environment variables.

:see: `configargparse.ArgumentParser`, `configargparse.add_argument`
    N)OrderedDict)   r   )StringIO)r   	   c                 C   s   t | tjS N)
isinstanceargparseBooleanOptionalActionaction r   ;/opt/certbot/lib/python3.10/site-packages/configargparse.py<lambda>   s    r   c                 C   s   dS )NFr   r
   r   r   r   r      s    c                 K   sX   | du rd} | t v rtd| t |  f |dtj |dd tdi |t | < dS )zCreates a global ArgumentParser instance with the given name,
    passing any args other than "name" to the ArgumentParser constructor.
    This instance can then be retrieved using get_argument_parser(..)
    Ndefaultzbkwargs besides 'name' can only be passed in the first time. '%s' ArgumentParser already exists: %sformatter_classconflict_handlerresolver   )_parsers
ValueError
setdefaultr   ArgumentDefaultsHelpFormatterArgumentParsernamekwargsr   r   r   init_argument_parser&   s   r   c                 K   s8   | du rd} t |dks| tvrt| fi | t|  S )a  Returns the global ArgumentParser instance with the given name. The 1st
    time this function is called, a new ArgumentParser instance will be created
    for the given name, and any args other than "name" will be passed on to the
    ArgumentParser constructor.
    Nr   r   )lenr   r   r   r   r   r   get_argument_parser9   s
   r   c                   @      e Zd ZdZdS ) ArgumentDefaultsRawHelpFormatterzCHelpFormatter that adds default values AND doesn't do line-wrappingN__name__
__module____qualname____doc__r   r   r   r   r   H   s    r   c                   @   (   e Zd ZdZdd Zdd Zdd ZdS )	ConfigFileParserzRThis abstract class can be extended to add support for new config file
    formatsc                 C      t d)z3Returns a string describing the config file syntax.z*get_syntax_description(..) not implementedNotImplementedErrorselfr   r   r   get_syntax_descriptionT   s   z'ConfigFileParser.get_syntax_descriptionc                 C   r'   )aH  Parses the keys and values from a config file.

        NOTE: For keys that were specified to configargparse as
        action="store_true" or "store_false", the config file value must be
        one of: "yes", "no", "true", "false". Otherwise an error will be raised.

        Args:
            stream (IO): A config file input stream (such as an open file object).

        Returns:
            OrderedDict: Items where the keys are strings and the
            values are either strings or lists (eg. to support config file
            formats like YAML which allow lists).
        zparse(..) not implementedr(   )r+   streamr   r   r   parseX   s   zConfigFileParser.parsec                 C   r'   )a  Does the inverse of config parsing by taking parsed values and
        converting them back to a string representing config file contents.

        Args:
            items: an OrderedDict of items to be converted to the config file
                format. Keys should be strings, and values should be either strings
                or lists.

        Returns:
            Contents of config file as a string
        zserialize(..) not implementedr(   )r+   itemsr   r   r   	serializei   s   zConfigFileParser.serializeNr!   r"   r#   r$   r,   r.   r0   r   r   r   r   r&   P   s
    r&   c                   @   r   )ConfigFileParserExceptionz'Raised when config file parsing failed.Nr    r   r   r   r   r2   x   s    r2   c                   @   r%   )	DefaultConfigFileParsera  
    Based on a simplified subset of INI and YAML formats. Here is the
    supported syntax

    .. code::

        # this is a comment
        ; this is also a comment (.ini style)
        ---            # lines that start with --- are ignored (yaml style)
        -------------------
        [section]      # .ini-style section names are treated as comments

        # how to specify a key-value pair (all of these are equivalent):
        name value     # key is case sensitive: "Name" isn't "name"
        name = value   # (.ini style)  (white space is ignored, so name = value same as name=value)
        name: value    # (yaml style)
        --name value   # (argparse style)

        # how to set a flag arg (eg. arg which has action="store_true")
        --name
        name
        name = True    # "True" and "true" are the same

        # how to specify a list arg (eg. arg which has action="append")
        fruit = [apple, orange, lemon]
        indexes = [1, 12, 35 , 40]

    c                 C      d}|S )NzrConfig file syntax allows: key=value, flag=true, stuff=[a,b,c] (for details, see syntax at https://goo.gl/R74nmi).r   r+   msgr   r   r   r,         z.DefaultConfigFileParser.get_syntax_descriptionc                 C   s@  t  }t|D ]\}}| }|r|d dv s|drqtd|}|r|d}|d}|d}|d}	|d u rH|d urH|d	krHd
}n|d u rNd}|dr|drzt	|}W n  t
y }
 zdd |dd dD }W Y d }
~
nd }
~
ww |	r|	 dd   }	|||< qtd|t|dd||S )Nr   )#;[z---zn^(?P<key>[^:=;#\s]+)\s*(?:(?P<equal>[:=\s])\s*([\'"]?)(?P<value>.+?)?\3)?\s*(?:\s[;#]\s*(?P<comment>.*?)\s*)?$keyequalvaluecomment  truer:   ]c                 S      g | ]}|  qS r   strip.0elemr   r   r   
<listcomp>       z1DefaultConfigFileParser.parse.<locals>.<listcomp>   ,zUnexpected line {} in {}: {}r   r-   )r   	enumeraterE   
startswithrematchgroupendswithjsonloads	Exceptionsplitr2   formatgetattr)r+   r-   r/   ilinerQ   r;   r<   r=   r>   er   r   r   r.      s>   



(
zDefaultConfigFileParser.parsec                 C   sT   t  }| D ]\}}t|trddtt| d }|d|| q|	 S )Nr:   , rB   z{} = {}
)
r   r/   r   listjoinmapstrwriterX   getvalue)r+   r/   rr;   r=   r   r   r   r0      s   
z!DefaultConfigFileParser.serializeNr1   r   r   r   r   r3   |   s
    $r3   c                   @   r%   )	ConfigparserConfigFileParserz,parses INI files using pythons configparser.c                 C   r4   )Na  Uses configparser module to parse an INI file which allows multi-line
        values.

        Allowed syntax is that for a ConfigParser with the following options:

            allow_no_value = False,
            inline_comment_prefixes = ("#",)
            strict = True
            empty_lines_in_values = False

        See https://docs.python.org/3/library/configparser.html for details.

        Note: INI file sections names are still treated as comments.
        r   r5   r   r   r   r,      s   z3ConfigparserConfigFileParser.get_syntax_descriptionc              
   C   s   dd l }ddlm} |jddddddd}z	||  W n ty0 } ztd| d }~ww t }|	 D ]:}|| 
 D ]1\}}	|	d	d
dd
}
d|
v rmd|
v rm|
dd }d|vrh||
||< q@|
||< q@|
||< q@q8|S )Nr   )literal_eval)=:F)r8   r9   T)
delimitersallow_no_valuecomment_prefixesinline_comment_prefixesstrictempty_lines_in_valuesCouldn't parse config file: %s
r?   r:   rB   {)configparserastrf   ConfigParserread_stringreadrV   r2   r   sectionsr/   replacerW   )r+   r-   rs   rf   configr\   resultsectionkvmultiLine2SingleLineprelist_stringr   r   r   r.      s8   

z"ConfigparserConfigFileParser.parsec                 C   sX   dd l }dd l}|jddddd}d|i}|| | }|| |d | S )Nr   F)r8   T)rj   rl   rm   rn   DEFAULT)rs   ioru   	read_dictr   rb   seekrw   )r+   r/   rs   r   rz   r-   r   r   r   r0     s   


z&ConfigparserConfigFileParser.serializeNr1   r   r   r   r   re      s
    #re   c                   @   s2   e Zd ZdZdd Zdd Zdd Zdd	d
ZdS )YAMLConfigFileParserzdParses YAML config files. Depends on the PyYAML module.
    https://pypi.python.org/pypi/PyYAML
    c                 C   r4   )NzThe config file uses YAML syntax and must represent a YAML 'mapping' (for details, see http://learn.getgrav.org/advanced/yaml).r   r5   r   r   r   r,     r7   z+YAMLConfigFileParser.get_syntax_descriptionc                 C   s&   zddl }W |S  ty   tdw )zjlazy-import PyYAML so that configargparse doesn't have to depend
        on it unless this parser is used.r   NzJCould not import yaml. It can be installed by running 'pip install PyYAML')yamlImportErrorr2   )r+   r   r   r   r   
_load_yaml!  s   
zYAMLConfigFileParser._load_yamlc              
   C   s   |   }z||}W n ty } ztd| d }~ww t|ts2tdt|ddt|jf t	 }|
 D ]\}}t|trG|||< q9|d u rLq9t|||< q9|S )Nro   zThe config file doesn't appear to contain 'key: value' pairs (aka. a YAML mapping). yaml.load('%s') returned type '%s' instead of 'dict'.r   r-   )r   	safe_loadrV   r2   r   dictrY   typer!   r   r/   r^   ra   )r+   r-   r   
parsed_objr\   r{   r;   r=   r   r   r   r.   ,  s(   


zYAMLConfigFileParser.parseFc                 C   s   |   }t|}|j||dS )N)default_flow_style)r   r   dump)r+   r/   r   r   r   r   r   r0   F  s   zYAMLConfigFileParser.serializeNF)r!   r"   r#   r$   r,   r   r.   r0   r   r   r   r   r     s    r   command_lineenvironment_variablesconfig_filedefaultsc                   @   s   e Zd ZdZdd ZdddejfddZdddejdfdd	Zd
d Z	dddZ
dd Zdd Zdd Zdd Zdd Zdd ZejfddZdd ZdS )r   zDrop-in replacement for `argparse.ArgumentParser` that adds support for
    environment variables and ``.ini`` or ``.yaml-style`` config files.
    c                 O   s   | dd}| dd}| dd}| dg }| dd}| d	t}| d
g }	| dd}
| dd}| dg }| dd}| dt| _|| _|| _|| _tjj	| g|R i | |du rht | _
n| | _
|| _|| _|	r| j|	d|
|dd |r| j|dd|dd dS dS )aR  Supports args of the `argparse.ArgumentParser` constructor
        as \*\*kwargs, as well as the following additional args.

        Arguments:
            add_config_file_help: Whether to add a description of config file
                syntax to the help message.
            add_env_var_help: Whether to add something to the help message for
                args that can be set through environment variables.
            auto_env_var_prefix: If set to a string instead of None, all config-
                file-settable options will become also settable via environment
                variables whose names are this prefix followed by the config
                file key, all in upper case. (eg. setting this to ``foo_`` will
                allow an arg like ``--my-arg`` to also be set via the FOO_MY_ARG
                environment variable)
            default_config_files: When specified, this list of config files will
                be parsed in order, with the values from each config file
                taking precedence over previous ones. This allows an application
                to look for config files in multiple standard locations such as
                the install directory, home directory, and current directory.
                Also, shell \* syntax can be used to specify all conf files in a
                directory. For example::

                    ["/etc/conf/app_config.ini",
                    "/etc/conf/conf-enabled/*.ini",
                    "~/.my_app_config.ini",
                    "./app_config.txt"]

            ignore_unknown_config_file_keys: If true, settings that are found
                in a config file but don't correspond to any defined
                configargparse args will be ignored. If false, they will be
                processed and appended to the commandline like other args, and
                can be retrieved using parse_known_args() instead of parse_args()
            config_file_open_func: function used to open a config file for reading
                or writing. Needs to return a file-like object.
            config_file_parser_class: configargparse.ConfigFileParser subclass
                which determines the config file format. configargparse comes
                with DefaultConfigFileParser and YAMLConfigFileParser.
            args_for_setting_config_path: A list of one or more command line
                args to be used for specifying the config file path
                (eg. ["-c", "--config-file"]). Default: []
            config_arg_is_required: When args_for_setting_config_path is set,
                set this to True to always require users to provide a config path.
            config_arg_help_message: the help message to use for the
                args listed in args_for_setting_config_path.
            args_for_writing_out_config_file: A list of one or more command line
                args to use for specifying a config file output path. If
                provided, these args cause configargparse to write out a config
                file with settings based on the other provided commandline args,
                environment variants and defaults, and then to exit.
                (eg. ["-w", "--write-out-config-file"]). Default: []
            write_out_config_file_arg_help_message: The help message to use for
                the args in args_for_writing_out_config_file.
        add_config_file_helpTadd_env_var_helpauto_env_var_prefixNdefault_config_filesignore_unknown_config_file_keysFconfig_file_parser_classargs_for_setting_config_pathconfig_arg_is_requiredconfig_arg_help_messagezconfig file path args_for_writing_out_config_file&write_out_config_file_arg_help_messagezftakes the current command line args and writes them out to a config file at the given path, then exitsconfig_file_open_funcr   )destrequiredhelpis_config_file_arg"write_out_config_file_to_this_pathCONFIG_OUTPUT_PATH)r   metavarr   is_write_out_config_file_arg)popr3   open_config_file_open_func_add_config_file_help_add_env_var_help_auto_env_var_prefixr   r   __init___config_file_parser_default_config_files _ignore_unknown_config_file_keysadd_argument)r+   argsr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   ]  s\   :
zArgumentParser.__init__Nc                 C   s4   | j ||||dd\}}|r| dd|  |S )a  Supports all the same args as the `argparse.ArgumentParser.parse_args()`,
        as well as the following additional args.

        Arguments:
            args: a list of args as in argparse, or a string (eg. "-x -y bla")
            config_file_contents: String. Used for testing.
            env_vars: Dictionary. Used for testing.

        Returns:
            argparse.Namespace: namespace
        F)r   	namespaceconfig_file_contentsenv_varsignore_help_argszunrecognized arguments: %sr?   )parse_known_argserrorr_   )r+   r   r   r   r   argvr   r   r   
parse_args  s   
zArgumentParser.parse_argsFc                    s   du rt jdd  nt tr   nt  jD ]}|j |_q|r.dd  D  t	 _
 rAdt f}d|ij
t< jdurjD ]5}|}|r~|js~|js~|js~|js~t|tjs~t|tjs~|d j}	j|	 dd |_qIg }
d	} fd
djD }|D ]F}|j}| }|jst|tjrd}|dr|drzt|}W n ty   dd |dd dD }Y nw |
|||7 }
q|r߈ |
  n|
   |
rt	fdd|D j
t < t!dd jD }|od v pd v }fddjD }g }|dur%t"|}d|_#|g}n|s-$ }t%|D ]}z-zj&'|}W n t(yT } z)| W Y d}~nd}~ww W t*|dr`|+  nt*|drl|+  w w g }d	}|, D ]`\}}||v r|| }t- |jj}nd}j.pt- /|gj}|s||||7 }dt0|j#f }|j
vrt	 j
|< ||fj
| |< |r|jst|tjrd}qu|r߈ |  q1|   q1t	 }jD ]E}|j p|jt1t2fv }t- |jjs|r|j3du s|j3t4kst|t5rq|jr#|jd }n|j6}|t|j3f||< q|r9|j
t7< tj8j9 d\}fddjD }dd |D }j:|dd |fS )a  Supports all the same args as the `argparse.ArgumentParser.parse_args()`,
        as well as the following additional args.

        Arguments:
            args: a list of args as in argparse, or a string (eg. "-x -y bla")
            config_file_contents (str). Used for testing.
            env_vars (dict). Used for testing.
            ignore_help_args (bool): This flag determines behavior when user specifies ``--help`` or ``-h``. If False,
                it will have the default behavior - printing help and exiting. If True, it won't do either.

        Returns:
            tuple[argparse.Namespace, list[str]]: tuple namescpace, unknown_args
        NrK   c                 S   s   g | ]}|d vr|qS ))-h--helpr   )rG   argr   r   r   rI         z3ArgumentParser.parse_known_args.<locals>.<listcomp>r@   r   -_Fc                    s6   g | ]}|j s|jr|jv rt |jjs|qS r   )is_positional_argenv_varalready_on_command_lineoption_stringsprefix_charsrG   a)r   r   r+   r   r   rI     s    
Tr:   rB   c                 S   rC   r   rD   rF   r   r   r   rI   )  rJ   rL   rM   c                    s    g | ]}|j | |j  ffqS r   )r   r   )r   r   r   rI   4  s    c                 s   s     | ]}t |tjr|V  qd S r   )r   r   _HelpActionr   r   r   r   	<genexpr>8  s    
z2ArgumentParser.parse_known_args.<locals>.<genexpr>r   r   c                    s"   i | ]}  |D ]}||q	qS r   )get_possible_config_keys)rG   r   
config_keyr*   r   r   
<dictcomp>>  s
    z3ArgumentParser.parse_known_args.<locals>.<dictcomp>z
method argclosez%s|%s)r   r   c                    s&   g | ]}t |d drt  |jdqS )r   FN)rY   r   r   )r   r   r   rI     s    
c                 S   s   g | ]}|d ur|qS r   r   r   r   r   r   rI     r   )
exit_after);sysr   r   ra   rW   r^   _actionsr   r   r   _source_to_settings_COMMAND_LINE_SOURCE_KEYr   r   r   r   r   r   _VersionActionr   rE   r   ry   uppernargs_AppendActionrO   rS   rT   rU   rV    convert_item_to_command_line_arg_ENV_VAR_SOURCE_KEYanyr   r   _open_config_filesreversedr   r.   r2   r   hasattrr   r/   r   r   4get_command_line_key_for_unknown_config_file_setting_CONFIG_FILE_SOURCE_KEYOPTIONALZERO_OR_MOREr   SUPPRESS#ACTION_TYPES_THAT_DONT_NEED_A_VALUEr   _DEFAULTS_SOURCE_KEYr   r   write_config_file)r+   r   r   r   r   r   r   a_v_pairconfig_file_keysstripped_config_file_keyenv_var_argsr   actions_with_env_var_valuesr   r;   r=   supports_help_argskip_config_file_parsingknown_config_keysconfig_streamsr-   config_itemsr\   config_argsdiscard_this_key
source_keydefault_settingscares_about_default_valueunknown_argsoutput_file_pathsr   )r   r   r   r+   r   r     s(  







 













zArgumentParser.parse_known_argsc                 C   s   | j S )ar  
        If called after `parse_args()` or `parse_known_args()`, returns a dict that contains up to 4 keys corresponding
        to where a given option's value is coming from:
        - "command_line"
        - "environment_variables"
        - "config_file"
        - "defaults"
        Each such key, will be mapped to another dictionary containing the options set via that method. Here the key
        will be the option name, and the value will be a 2-tuple of the form (`argparse.Action` obj, `str` value).

        Returns:
            dict[str, dict[str, tuple[argparse.Action, str]]]: source to settings dict
        )r   r*   r   r   r   get_source_to_settings_dict  s   z*ArgumentParser.get_source_to_settings_dictc           	      C   s   |D ].}z|  |d}W d   n1 sw   Y  W q ty0 } ztd||d}~ww |rr| | j|}| j|}|D ]}|  |d}|| W d   n1 sZw   Y  qBt	dd
|  |rt| d dS dS dS )a4  Write the given settings to output files.

        Args:
            parsed_namespace: namespace object created within parse_known_args()
            output_file_paths: any number of file paths to write the config to
            exit_after: whether to exit the program after writing the config files
        wNz Couldn't open {} for writing: {}zWrote config file to r]   r   )r   IOErrorr   rX    get_items_for_config_file_outputr   r   r0   rb   printr_   exit)	r+   parsed_namespacer   r   output_file_pathoutput_filer\   r   file_contentsr   r   r   r     s6   
z ArgumentParser.write_config_filec                 C   s"   | | j}| jd d | }|S )aM  Compute a commandline arg key to be used for a config file setting
        that doesn't correspond to any defined configargparse arg (and so
        doesn't have a user-specified commandline arg key).

        Args:
            key: The config file key that was being set.

        Returns:
            str: command line key
        r      )rE   r   )r+   r;   key_without_prefix_charscommand_line_keyr   r   r   r     s   zCArgumentParser.get_command_line_key_for_unknown_config_file_settingc                 C   sb  t  }| D ]\}}|tkrJ|d \}}| jD ]0}| |}	|	rH|jsHt||j| jrHt	||j
d}
|
durHt|
trBt|
 }
|
||	d < qq|tkrr| D ]\}\}}
| |}	|	rpt	||j
d}
|
durp|
||	d < qRq|tr| D ]
\}\}}
|
||< q{q|tkr| D ]\}\}}
| |}	|	rt	||j
d}
|
dur|
||	d < qq|S )a  Converts the given settings back to a dictionary that can be passed
        to ConfigFormatParser.serialize(..).

        Args:
            source_to_settings: the dictionary described in parse_known_args()
            parsed_namespace: namespace object created within parse_known_args()
        Returns:
            OrderedDict: where keys are strings and values are either strings
            or lists
        r@   Nr   )r   r/   r   r   r   r   r   r   r   rY   r   r   boolra   lowerr   rO   r   r   )r+   source_to_settingsr   config_file_itemssourcesettingsr   existing_command_line_argsr   r   r=   r;   r   r   r   r     sR   







z/ArgumentParser.get_items_for_config_file_outputc           	         s:  g }|du r|  |}n	t|s|jd }|durt|tr| dv r9t|s/|| |S ||jd  |S | dv rPt|sF	 |S ||jd  |S t|tjrw|D ] t	 fdd|jD rhd}qX||jd gt
| 7 }|S | d	||f  |S t|tr|duo|jduot|tjpt|tjo|jd
v pt|jt
o|jdk}|du st|tjr|D ]&}|rt|tr|| |D ]	}|t| qq|d|t|f  q|S |r|| |D ]	}|t| q|S | d||f  |S t|tr|d||f  |S tdt||)a  Converts a config file or env var key + value to a list of
        commandline args to append to the commandline.

        Args:
            action: The argparse Action object for this setting, or None if this
                config file setting doesn't correspond to any defined
                configargparse arg.
            key: string (config file key or env var name)
            value: parsed value of type string or list

        Returns:
            list[str]: args
        NrL   )rA   yes1r   )falseno0rK   c                    s   g | ]}  |qS r   rO   )rG   sr   r   r   rI   *  s    zCArgumentParser.convert_item_to_command_line_arg.<locals>.<listcomp>zQUnexpected value for %s: '%s'. Expecting 'true', 'false', 'yes', 'no', '1' or '0')+*z%s=%szp%s can't be set to a list '%s' unless its action type is changed to 'append' or nargs is set to '*', '+', or > 1z&Unexpected value type {} for value: {})r   is_boolean_optional_actionr   r   r   r  appendr   _CountActionr   intr   r^   r   _StoreActionr   ra   r   rX   r   )	r+   r   r;   r=   r   r  accepts_list_and_has_nargs	list_elemsub_elemr   r  r   r     sx   

/,(% 


z/ArgumentParser.convert_item_to_command_line_argc                    sP   g }t |ddr
|S |jD ] t fdd| jD r%| dd  g7 }q|S )a  This method decides which actions can be set in a config file and
        what their keys will be. It returns a list of 0 or more config keys that
        can be used to set the given action's value in a config file.

        Returns:
            list[str]: keys
        r   Nc                 3   s    | ]
}  d | V  qdS )r  Nr  )rG   cr  r   r   r   ]  s    z:ArgumentParser.get_possible_config_keys.<locals>.<genexpr>r  )rY   r   r   r   )r+   r   keysr   r  r   r   N  s   
z'ArgumentParser.get_possible_config_keysc                 C   sf  g }t tjt tjj| jD ]}|D ]
}|| | qqdd | jD }|s*|S |D ]}t	j
| jdd}|| dd }t|||_|j|d}	|	sOq,|	\}
}t|
|jd}|s]q,tj|}z| |}W n@ ty } z4t|jd	kr|j\}}nt|}|D ]}z|  W q ty   Y qw | d
||f  W Y d}~nd}~ww ||g7 }q,|S )a  Tries to parse config file path(s) from within command_line_args.
        Returns a list of opened config files, including files specified on the
        commandline as well as any default_config_files specified in the
        constructor that are present on disk.

        Args:
            command_line_args: List of all args
        
        Returns:
            list[IO]: open config files
        c                 S      g | ]
}t |d dr|qS r   FrY   r   r   r   r   rI   v  s
    z5ArgumentParser._open_config_files.<locals>.<listcomp>F)r   add_helpc                 S   s   d S r   r   )r+   messager   r   r   error_method  s   z7ArgumentParser._open_config_files.<locals>.error_method)r   Nr  z)Unable to open config file: %s. Error: %s)r`   globospath
expanduserr   r  r   r   r   r   r   _add_actiontypes
MethodTyper   r   rY   r   rV   r   r   ra   r   )r+   command_line_argsconfig_filesfilesfuser_config_file_arg_actionsr   
arg_parserr$  
parsed_argr   r   user_config_filer-   r\   errnor6   r   r   r   r   r   b  sZ   
z!ArgumentParser._open_config_filesc                 C   s   t dtdtdtdi}t }| j D ]Q\}}|d}||d  t|dd  }|	| | D ]0\}\}}|rF|	d	
|d
 | q2t|trS|	d|  q2t|trb|	dd|  q2q| S )zReturns a string with all args and settings and where they came from
        (eg. commandline, config file, environment variable or default)

        Returns:
            str: source to settings string
        zCommand Line Args: zEnvironment Variables:
zConfig File (%s):
z
Defaults:
|r   rK   Nz  {:<19}{}
rh   z  %s
r?   )r   r   r   r   r   r   r/   rW   tuplerb   rX   r   ra   r^   r_   rc   )r+   source_key_to_display_value_maprd   r  r	  r;   r   r=   r   r   r   format_values  s(   



	zArgumentParser.format_valuesc                 C   s   | |   dS )zBPrints the format_values() string (to sys.stdout or another file).N)rb   r8  )r+   filer   r   r   print_values  s   zArgumentParser.print_valuesc              	      s  d}d}d} j rl j}d jd  } fdd jD }dd  jD }|rl|s+|rld _ d}|d	||d d f 7 }d
dd |D }|rLd| }|sP|rc|dd
t|ttd |g  7 }|d j  7 } j	rdd  jD }	|	D ]%\}
}|j
tkrqyd|
 }|j
sd|_
||j
vr| j
|7  _
d}d _	qy|s|rdg}|rdg| }|rdg| }|dd| 7 }t  jd}t||}tj |dkrd| S d S )Nr@   Fr  r   c                    s@   g | ]}|j D ]} |r|jd ks|js|js||fqqS )r   )r   r   r   r   r   )rG   r   r   r*   r   r   rI     s    z.ArgumentParser.format_help.<locals>.<listcomp>c                 S   r  r   r!  r   r   r   r   rI     s    

TzCArgs that start with '%s' (eg. %s) can also be set in a config filez or c                 s   s     | ]}|j r|j d  V  qdS )r   N)r   r   r   r   r   r     s    z-ArgumentParser.format_help.<locals>.<genexpr>zspecified via z (%s).r?   c                 S   s"   g | ]}t |d dr|j|fqS )r   N)rY   r   r   r   r   r   rI     s    
z   [env var: %s]r   zconfig file valueszenvironment variableszT If an arg is specified in more than one place, then commandline values override %s.z which override    z
{}
)r   r   r   r   r_   r6  filterr   r,   r   r   r   max_get_formatter_widthtextwrapfillr   r   format_helprX   )r+   r6   added_config_file_helpadded_env_var_helpr   ccconfig_settable_argsconfig_path_actionsconfig_arg_stringenv_var_actionsr   r   env_var_help_stringvalue_sources
text_widthr   r*   r   rB    sr   






zArgumentParser.format_helpr   )r!   r"   r#   r$   r   r&  environr   r   r   r   r   r   r   r   r   r8  r   stdoutr:  rB  r   r   r   r   r   X  s.    j

 6
/LKr   c                 O   s   | dd}| ddp| dd}| dd}| j|i |}|j |_||_||_||_|jr7|r7td|jrDt|t	j
sDtd|jr]d}t|t	j
sUt|d	 |r]t|d
 |S )aH  
    This method supports the same args as ArgumentParser.add_argument(..)
    as well as the additional args below.

    Arguments:
        env_var: If set, the value of this environment variable will override
            any config file or default values for this arg (but can itself
            be overridden on the commandline). Also, if auto_env_var_prefix is
            set in the constructor, this env var name will be used instead of
            the automatic name.
        is_config_file_arg: If True, this arg is treated as a config file path
            This provides an alternative way to specify config files in place of
            the ArgumentParser(fromfile_prefix_chars=..) mechanism.
            Default: False
        is_write_out_config_file_arg: If True, this arg will be treated as a
            config file path, and, when it is specified, will cause
            configargparse to write all current commandline args to this file
            as config options and then exit.
            Default: False
    
    Returns:
        argparse.Action: the new argparse action
    r   Nr   is_config_filer   z*env_var can't be set for a positional arg.z9arg with is_config_file_arg=True must have action='store'z+arg with is_write_out_config_file_arg=True zmust have action='store'z'can't also have is_config_file_arg=True)r   original_add_argument_methodr   r   r   r   r   r   r   r   r  )r+   r   r   r   r   r   r   error_prefixr   r   r   r     s6   

r   c                    sb   g  | D ]!}|r |d |v r d|v r | dd\}} | q | qt fdd|D S )zUtility method for checking if any of the potential_command_line_args is
    already present in existing_args.

    Returns:
        bool: already on command line?
    r   rg   rK   c                 3   s    | ]}| v V  qd S r   r   )rG   potential_arg	arg_namesr   r   r   T  s    
z*already_on_command_line.<locals>.<genexpr>)rW   r  r   )existing_args_listpotential_command_line_argsr   
arg_stringoption_stringexplicit_argr   rS  r   r   E  s   r   r   )Kr$   r   rT   r%  r&  rP   r   r*  collectionsr   r@  version_infor   r   _StoreTrueAction_StoreFalseActionr  _StoreConstAction_AppendConstActionr   r  r	   r  r6  r   r   r   r   RawTextHelpFormatterRawDescriptionHelpFormatterr   objectr&   rV   r2   r3   re   r   r   r   r   r   r   r   r   _ActionsContainerrP  HelpFormatterArgumentErrorArgumentTypeErrorActionFileType	NamespaceONE_OR_MOREr   	REMAINDERr   r   initArgumentParsergetArgumentParsergetArgParser	getParserget_arg_parser
get_parser	ArgParserParseradd_argaddr   r.   r   parse_knownRawFormatterDefaultsFormatterDefaultsRawFormatterr   r   r   r   <module>   s    





(RI;     99