a 2i!@sdZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl m Z ddlZddlmZejejejejejgZe jdkreejddZnddZeeZiZd7d d Zd8d d ZGd ddejej ej!Z"Gddde#Z$Gddde%Z&Gddde$Z'Gddde$Z(Gddde$Z)e *dZ+e j*de j,dZ-ej.dddd9dd Z/d:d!d"Z0d#d$Z1d%d&Z2Gd'd(d(e$Z3Gd)d*d*e$Z4Gd+d,d,e$Z5d-Z6d.Z7d/Z8d0Z9Gd1d2d2ej:Z:d3d4Z;d5d6Ze;ej=_;ej?Z?ejZej@Z@ejAZAejBZBejCZCejDZDejEZEej!Z!ej Z ejFZFejGZGejHZHejIZIejJZJejKZKeZLeZMeZNeZOeZPeZQe:ZRe:ZSej=j;ej=_Tej=j;ej=_Ue:jVe:_We:jXe:_Ye!ZZeZ[e"Z\dS);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)StringIO cCs t|tjSN) isinstanceargparseBooleanOptionalActionactionr 2/usr/lib/python3.9/site-packages/configargparse.py srcCsdS)NFr r r r rr$cKsX|dur d}|tvr(td|t|f|dtj|ddtfi|t|<dS)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(..) Ndefaultzbkwargs besides 'name' can only be passed in the first time. '%s' ArgumentParser already exists: %sformatter_classconflict_handlerresolve)_parsers ValueError setdefaultr ArgumentDefaultsHelpFormatterArgumentParsernamekwargsr r rinit_argument_parser-s  rcKs8|dur d}t|dks |tvr0t|fi|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. Nrr)lenrrrr r rget_argument_parserDs rc@seZdZdZdS) ArgumentDefaultsRawHelpFormatterzCHelpFormatter that adds default values AND doesn't do line-wrappingN__name__ __module__ __qualname____doc__r r r rr Ssr c@s(eZdZdZddZddZddZdS) ConfigFileParserzRThis abstract class can be extended to add support for new config file formatscCs tddS)z3Returns a string describing the config file syntax.z*get_syntax_description(..) not implementedNNotImplementedErrorselfr r rget_syntax_descriptionasz'ConfigFileParser.get_syntax_descriptioncCs tddS)a\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", "on", "off", "true", "false". Otherwise an error will be raised. Args: stream (io.IOBase): 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). zparse(..) not implementedNr')r*streamr r rparseeszConfigFileParser.parsecCs tddS)aDoes 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 zserialize(..) not implementedNr'r*itemsr r r serializevs zConfigFileParser.serializeNr"r#r$r%r+r-r0r r r rr&]sr&c@seZdZdZdS)ConfigFileParserExceptionz'Raised when config file parsing failed.Nr!r r r rr2sr2c@s(eZdZdZddZddZddZdS) 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] cCsd}|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 rr+sz.DefaultConfigFileParser.get_syntax_descriptionc Cs4t}t|D]\}}|}|r|ddvs|dr[^:=;#\s]+)\s*(?:(?P[:=\s])\s*([\'"]?)(?P.+?)?\3)?\s*(?:\s[;#]\s*(?P.*?)\s*)?$keyequalvaluecomment truer8]cSsg|] }|qSr strip.0elemr r r rz1DefaultConfigFileParser.parse..,zUnexpected line {} in {}: {}rr,)r enumeraterB startswithrematchgroupendswithjsonloads Exceptionsplitr2formatgetattr) r*r,r/ilinerMr9r:r;r<er r rr-s<    2 zDefaultConfigFileParser.parsecCsTt}|D]<\}}t|tr8ddtt|d}|d||q| S)Nr8, r@z{} = {} ) rr/rlistjoinmapstrwriterTgetvalue)r*r/rr9r;r r rr0s  z!DefaultConfigFileParser.serializeNr1r r r rr3s(r3c@s(eZdZdZddZddZddZdS) ConfigparserConfigFileParserz,parses INI files using pythons configparser.cCsd}|S)NaUses 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 r4r r rr+sz3ConfigparserConfigFileParser.get_syntax_descriptionc Cs0tjddddddd}z||Wn0tyX}ztd|WYd}~n d}~00t}|D]}||D]\}}| dd d d}d |vr d |vr | d d } d | vrzt |||<Wn@t tfy}z"tdt|d|WYd}~n d}~00n|||<qx|||<qxqh|S)N)=:F)r6r7T)Z delimitersallow_no_valueZcomment_prefixesinline_comment_prefixesstrictempty_lines_in_valuesCouldn't parse config file: %s r= r8r@r{Error evaluating list: ;. Put quotes around your text if it's meant to be a string.) configparser ConfigParser read_stringreadrRr2rsectionsr/replacerSast literal_evalr SyntaxErrorr]) r*r,configrXresultsectionkvZmultiLine2SingleLineZprelist_stringr r rr-sD"    z"ConfigparserConfigFileParser.parsecCsFtjddddd}d|i}||t}|||d|S)NF)r6T)rdrerfrgDEFAULTr)rnroZ read_dictrr^seekrq)r*r/rwr,r r rr0s   z&ConfigparserConfigFileParser.serializeNr1r r r rras(rac@s2eZdZdZddZddZddZd d d Zd S) YAMLConfigFileParserzdParses YAML config files. Depends on the PyYAML module. https://pypi.python.org/pypi/PyYAML cCsd}|S)NzThe config file uses YAML syntax and must represent a YAML 'mapping' (for details, see http://learn.getgrav.org/advanced/yaml).r r4r r rr+2sz+YAMLConfigFileParser.get_syntax_descriptioncCszz ddl}Wnty&tdYn0zddlm}ddlm}Wn*tynddlm}ddlm}Yn0|||fS)zjlazy-import PyYAML so that configargparse doesn't have to depend on it unless this parser is used.rNzJCould not import yaml. It can be installed by running 'pip install PyYAML') CSafeLoader)CDumper) SafeLoader)Dumper)yaml ImportErrorr2rrrr)r*rrrr r r _load_yaml9s      zYAMLConfigFileParser._load_yamlc Cs|\}}}z|j||d}Wn0tyP}ztd|WYd}~n d}~00t|tsztdt|ddt|jft }| D]2\}} t| t r| ||<q| durqt | ||<q|S)N)LoaderrhzThe config file doesn't appear to contain 'key: value' pairs (aka. a YAML mapping). yaml.load('%s') returned type '%s' instead of 'dict'.rr,) rloadrRr2rdictrUtyper"rr/rZr]) r*r,rr_Z parsed_objrXrxr9r;r r rr-Ms&"   zYAMLConfigFileParser.parseFcCs&|\}}}t|}|j|||dS)N)default_flow_styler)rrdump)r*r/rrrrr r rr0iszYAMLConfigFileParser.serializeN)F)r"r#r$r%r+rr-r0r r r rr~-s r~z1(^\"(?:\\.|[^\"\\])*\"$)|(^\'(?:\\.|[^\'\\])*\'$)z(^\"\"\"(\s+)?(([^\"]|\"([^\"]|\"[^\"]))*(\"\"?)?)?(\s+)?(?:\\.|[^\"\\])?\"\"\"$)|(^\'\'\'(\s+)?(([^\']|\'([^\']|\'[^\']))*(\'\'?)?)?(\s+)?(?:\\.|[^\'\\])?\'\'\'$))flagsT)maxsizetypedcCs tt|p|ott|S)zt Detect whether a string is a quoted representation. :param triple: Also match tripple quoted strings. )bool_QUOTED_STR_REGEXrM_TRIPLE_QUOTED_STR_REGEX)texttripler r r is_quotedsrc Cslt||drhzt|}t|ts&JWn:tyb}z"td|d||WYd}~n d}~00|S|S)a Unquote a maybe quoted string representation. If the string is not detected as being a quoted representation, it returns the same string as passed. It supports all kinds of python quotes: ``"""``, ``'''``, ``"`` and ``'``. :param triple: Also unquote tripple quoted strings. :raises ValueError: If the string is detected as beeing quoted but literal_eval() fails to evaluate it as string. This would be a bug in the regex. rz+Error trying to unquote the quoted string: : N)rrtrurr]rRr)rrsrXr r r unquote_strs  rcCsBg}tj|gddD]$}|D]}|t|ddqqt|S)u Parse a TOML section name to a sequence of strings. The following names are all valid: .. python:: "a.b.c" # this is best practice -> returns ("a", "b", "c") " d.e.f " # same as [d.e.f] -> returns ("d", "e", "f") " g . h . i " # same as [g.h.i] -> returns ("g", "h", "i") ' j . "ʞ" . "l" ' # same as [j."ʞ"."l"], double or simple quotes here are supported. -> returns ("j", "ʞ", "l") .)Z delimiterFr)csvreaderappendrrBtuple) section_nameryrowar r rparse_toml_section_names rcCs\t|trt|n|}||d}|s,dS|dd}|rFt||St|tsTdS|SdS)z Given some TOML data (as loaded with toml.load()), returns the requested section of the data. Returns ``None`` if the section is not found. rNrG)rr]rgetget_toml_sectionr)dataryrrZitemdatar r rrs   rcs@eZdZdZfddZddZddZdd Zd d ZZ S) TomlConfigParsera9 Create a TOML parser bounded to the list of provided sections. Example:: # this is a comment [tool.my-software] # TOML section table. # how to specify a key-value pair format-string = "restructuredtext" # strings must be quoted # how to set an arg which has action="store_true" warnings-as-errors = true # how to set an arg which has action="count" or type=int verbosity = 1 # how to specify a list arg (eg. arg which has action="append") repeatable-option = ["https://docs.python.org/3/objects.inv", "https://twistedmatrix.com/documents/current/api/objects.inv"] # how to specify a multiline text: multi-line-text = ''' Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus tortor odio, dignissim non ornare non, laoreet quis nunc. Maecenas quis dapibus leo, a pellentesque leo. ''' Note that the config file fragment above is also valid for the `IniConfigParser` class and would be parsed the same manner. Thought, any valid TOML config file will not be necessarly parsable with `IniConfigParser` (INI files must be rigorously indented whereas TOML files). See the `TOML specification `_ for details. cst||_dS)zO :param sections: The section names bounded to the new parser. N)super__init__rr)r*rr __class__r rrs zTomlConfigParser.__init__cCs|Srr r)r r r__call__szTomlConfigParser.__call__c Cs(zhddl}z*|}t|tr(|d}||}Wn0tyd}ztd|WYd}~n d}~00WnZtyddl }z| |}Wn0ty}ztd|WYd}~n d}~00Yn0t }|j D]R}t ||} | r| D]6\} } t| tr| || <q| durqt| || <qq|S)z3Parses the keys and values from a TOML config file.rNzutf-8zCouldn't parse TOML file: %s)tomllibrqrbytesdecoderQrRr2rtomlrrrrrr/rZr]) r*r,rZcontentrwrXrrxryrr9r;r r rr- s4  & (     zTomlConfigParser.parsecCsdS)NzConfig file syntax is Tom's Obvious, Minimal Language. See https://github.com/toml-lang/toml/blob/v0.5.0/README.md for details.r r)r r rr+4sz'TomlConfigParser.get_syntax_descriptionc Csz ddl}Wnty&tdYn0|js<|t|S|jd}t|}i}|}t|ddD]\}}i||<||}qft|||d<||S)zSerialize items to TOML format with section support. Note: Requires the 'toml' package for serialization (pip install toml). Python 3.11's tomllib only supports reading, not writing. rNzXThe 'toml' package is required for TOML serialization. Install it with: pip install tomlrH)rrr2rrdumpsrrrJ) r*r/rrrrrxcurrentrVryr r rr0:s"     zTomlConfigParser.serialize r"r#r$r%rrr-r+r0 __classcell__r r rrrs  +rcs@eZdZdZfddZddZddZdd Zd d ZZ S) IniConfigParsera} Create a INI parser bounded to the list of provided sections. Optionaly convert multiline strings to list. Example (if split_ml_text_to_list=False):: # this is a comment ; also a comment [my-software] # how to specify a key-value pair format-string: restructuredtext # white space are ignored, so name = value same as name=value # this is why you can quote strings quoted-string = ' hello mom... ' # how to set an arg which has action="store_true" warnings-as-errors = true # how to set an arg which has action="count" or type=int verbosity = 1 # how to specify a list arg (eg. arg which has action="append") repeatable-option = ["https://docs.python.org/3/objects.inv", "https://twistedmatrix.com/documents/current/api/objects.inv"] # how to specify a multiline text: multi-line-text = Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus tortor odio, dignissim non ornare non, laoreet quis nunc. Maecenas quis dapibus leo, a pellentesque leo. Example (if split_ml_text_to_list=True):: # the same rules are applicable with the following changes: [my-software] # how to specify a list arg (eg. arg which has action="append") repeatable-option = # Just enter one value per line (the list literal format can also be used) https://docs.python.org/3/objects.inv https://twistedmatrix.com/documents/current/api/objects.inv # how to specify a multiline text (you have to quote it): multi-line-text = ''' Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus tortor odio, dignissim non ornare non, laoreet quis nunc. Maecenas quis dapibus leo, a pellentesque leo. ''' cst||_||_dS)z :param sections: The section names bounded to the new parser. :param split_ml_text_to_list: Whether to convert multiline strings to list N)rrrrsplit_ml_text_to_list)r*rrrrr rrs zIniConfigParser.__init__cCs|Srr r)r r rrszIniConfigParser.__call__c Cst}z||Wn0tyJ}ztd|WYd}~n d}~00t}|tjgD]j}||jvrtqb|| D]J\}}| }|sq| dr| drzt |||<Wn@ttfy}z"tdt|d|WYd}~n d}~00qt|rXzt|||<Wn4tyT}ztt||WYd}~n d}~00q|jrd|dvrzdd |dD||<Wn4ty}ztt||WYd}~n d}~00q|||<qqb|S) z3Parses the keys and values from an INI config file.zCouldn't parse INI file: %sNr8r@rlrmricSsg|]}|rt|qSr )r)rDrVr r rrFsz)IniConfigParser.parse..)rnrorprqrRr2rrr DEFAULTSECTr/rBrKrOrtrurrvr]rrrrstriprS) r*r,rwrXrxryrzr{Zstrip_vr r rr-sP"  && zIniConfigParser.parsecCsd}|jr|d7}|S)NzUses configparser module to parse an INI file which allows multi-line values. See https://docs.python.org/3/library/configparser.html for details. This parser includes support for quoting strings literal as well as python list syntax evaluation. z{Alternatively lists can be constructed with a plain multiline string, each non-empty line will be converted to a list item.)rr4r r rr+sz&IniConfigParser.get_syntax_descriptionc Cst}|jr|jdnd}|dkr8|tjkr8|||D]b\}}t|tr|jr|| ||dd dd|Dq| ||t |q@| ||t |q@t }| ||d|S)z3Serialize items to INI format with section support.rr|ricss|]}t|VqdSr)r])rDr{r r r rz,IniConfigParser.serialize..)rnrorrrZ add_sectionr/rrZrsetr[r]rr^r}rq)r*r/rwrr9r;r,r r rr0s     zIniConfigParser.serializerr r rrr]s + 3 rcs@eZdZdZfddZddZddZdd Zd d ZZ S) CompositeConfigParserz Create a config parser composed by other ConfigFileParser instances. The composite parser will successively try to parse the file with each parser, until it succeeds, else raise exception with all encountered errors. cstdd|D|_dS)NcSsg|] }|qSr r )rDpr r rrFrz2CompositeConfigParser.__init__..)rrparsers)r*Zconfig_parser_typesrr rrs zCompositeConfigParser.__init__cCs|Srr r)r r rrszCompositeConfigParser.__call__c Csg}t|jD]\}}z||WSty}zj|||t|jdkrz|dWn2ttfyt d|j j d|d|Yn0WYd}~qd}~00qt dd dd |DdS) NrGrzError parsing config with rz?. Cannot try additional parsers because stream is not seekable.zError parsing config: rYcss|]}tt|VqdSr)reprr])rDrXr r rrrz.CompositeConfigParser.parse..) rJrr-rRrrr}AttributeErrorOSErrorr2rr"r[)r*r,errorsrVrrXr r rr-s$  zCompositeConfigParser.parsec CsPdd}d}t|jD]4\}}|d|dd||jjd|d7}q|S) NcSs6|ddddddd}|r2|SdS)Nrparserr>rwfilez??)lowerrBrsupper)Z classnamerBr r rguess_format_nameszGCompositeConfigParser.get_syntax_description..guess_format_namez2Uses multiple config parser settings (in order): r8rGz] rz )rJrrr"r+)r*rr5rVrr r rr+s  .z,CompositeConfigParser.get_syntax_descriptioncCs|jstd|jd|S)z8Serialize items using the first parser in the composite.z.No parsers configured in CompositeConfigParserr)rr2r0r.r r rr0*s zCompositeConfigParser.serializerr r rrrs  rZ command_lineZenvironment_variables config_filedefaultsc@seZdZdZddZddZdddejfddZdddejd fd d Z d d Z d ddZ ddZ ddZ ddZddZddZddZejfddZddZdS)!rzDrop-in replacement for `argparse.ArgumentParser` that adds support for environment variables and ``.ini`` or ``.yaml-style`` config files. cOs2|dd}|dd}|dd}|dg}|dd}|d t}|d g} |d d} |d d } |dg} |dd} |dt}d|fd | fd| ffD]>\}}t|ttfst|trd|nd}td|||fqt|std|f||_ ||_ ||_ ||_ d|vrf|d}t|t rft|tjsfd|f}t|tr^|d7}t|tjj|g|Ri||durt|_nDt|tr||_n0t|t rt|tr||_ntd|f||_||_| r|j| d| | dd| r|j| dd| ddtjdkr.d|_dS) aZ Supports args of the `argparse.ArgumentParser` constructor as \*\*kwargs, as well as the following additional args. Keyword 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_helpTadd_env_var_helpauto_env_var_prefixNdefault_config_filesignore_unknown_config_file_keysFconfig_file_parser_classargs_for_setting_config_pathconfig_arg_is_requiredconfig_arg_help_messagezconfig 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 exitsconfig_file_open_funcz (e.g. ['%s'])r>z%s must be a list%s. Got: %rz/config_file_open_func must be callable. Got: %rrzFformatter_class must be a subclass of argparse.HelpFormatter. Got: %r.z3 Perhaps you meant to use config_file_parser_class?zconfig_file_parser_class must be a subclass of ConfigFileParser (such as DefaultConfigFileParser, YAMLConfigFileParser, etc.). Got: %r. Perhaps you meant to use formatter_class?r)destrequiredhelpis_config_file_argZ"write_out_config_file_to_this_pathZCONFIG_OUTPUT_PATH)rmetavarris_write_out_config_file_argr)popr3openrrZrr] TypeErrorcallable_config_file_open_func_add_config_file_help_add_env_var_help_auto_env_var_prefixr issubclassr HelpFormatterr&rr_config_file_parser_default_config_files _ignore_unknown_config_file_keys add_argumentsys version_info exit_on_error)r*argsrrrrrrrrrrrrrrr;hintZfcr5r r rr@s9               zArgumentParser.__init__cCsd|vr|dSd}|jD]>}t|tjr|jrt|D]\}}||jvr:|}qVq:q\q|durh|Sd}t|D] \}}|t|j rt|}qqt|dur|St dd|jDrdSt |S)aZFind the right index to insert config/env var args into the command line. Inserts before the ``--`` separator if present, before a subparser command so the parent parser sees injected args first, before the first optional arg, or at position 0 when a REMAINDER positional exists. Falls back to appending. z--Ncss |]}|jo|jtjkVqdSr)is_positional_argnargsr REMAINDERrDrr r rrsz7ArgumentParser._find_insertion_index..r) index_actionsrr _SubParsersActionchoicesrJrKr prefix_charsanyr)r*rZ subcmd_indexr rVargZ first_optr r r_find_insertion_indexs0   z$ArgumentParser._find_insertion_indexNcCsJ|j||||dd\}}|rFdd|}|jr<||n td||S)aSupports 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 namespaceconfig_file_contentsenv_varsignore_help_argszunrecognized arguments: %sr=N)parse_known_argsr[rerror ArgumentError)r*rrrrargvr5r r r parse_args s   zArgumentParser.parse_argsFc sdurtjddnttr,ntjD]}|j |_q:|r\ddDt _ rdtf}d|ij t <j durjD]j} |}|r|js|js|js|jst|tjst|tjs|dj} j | dd|_qg} fd djD} | D]} | j} | }|dkrF| jrFq| js\t| tjr|d r|d rzt|}Wn0tyd d|dd dD}Yn0| | | |7} q }d|| |d| rt fdd| Dj t!<t"ddjD}|o.r>r-rcs6g|].}|js|jr|jvrt|jjs|qSr )renv_varalready_on_command_lineoption_stringsrr)rrr*r rrFjs  r8r@cSsg|] }|qSr rArCr r rrFrrHrIcs g|]}|j||jffqSr )rr)rr rrFscss|]}t|tjr|VqdSr)rr _HelpActionrr r rrsz2ArgumentParser.parse_known_args..rrcs"i|]}|D] }||qqSr )get_possible_config_keys)rDr Z config_keyr)r r sz3ArgumentParser.parse_known_args..z method argclosez%s|%s)rrcs&g|]}t|ddrt|jdqS)rFN)rUrr)rr rrFs cSsg|]}|dur|qSrr rr r rrFrT) exit_after)Nr)rr/rrr rrrrrUrrrr]rrrKrr) r*Zsource_to_settingsr)Zconfig_file_itemssourcesettingsrZexisting_command_line_argsr rr;r9r r rr&@sN            z/ArgumentParser.get_items_for_config_file_outputc Cs2g}|dur||}nt|s*|jd}|durt|trt|tsNJd|dvrt|sn||q||jdn`|dvrt|sq||jdn8t|tj r||jdgt |7}n| d||fnJt|t r|duoD|j duoDt|tjs"t|tjoD|j d vpDt|j t oD|j dk}|dus^t|tjr|D]T}|rt|t r|||D]}|t|qn|d |t|fqbn>|r|||D]}|t|qn| d ||fn4t|tr|d ||fntd t|||S) aConverts 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 NrHzCconfig parser should convert anything that is not a list to string.)r?ZyesZon1r)ZfalsenoZoff0rGz^Unexpected value for %s: '%s'. Expecting 'true', 'false', 'yes', 'no', 'on', 'off', '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: {})ris_boolean_optional_actionrrrr]rrr _CountActionintrrZr _StoreActionrrrTr) r*r r9r;rr+Zaccepts_list_and_has_nargsZ list_elemZsub_elemr r rrssz              z/ArgumentParser.convert_item_to_command_line_argcsPg}t|ddr|S|jD]0tfdd|jDr|ddg7}q|S)aThis 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 rNc3s|]}d|VqdS)r*N)rK)rDcrr rrrz:ArgumentParser.get_possible_config_keys..r*)rUrrr)r*r keysr r8rr s  z'ArgumentParser.get_possible_config_keysc Csrg}ttjttjj|jD]}|D]}|||q$qdd|jD}|sT|S|D]}t j |j dd}| |dd}t |||_|j|d} | sqX| \} } t| |jd} | sqXtj| } z|| } Wnty`}zpt|jd kr|j\}}nt|}|D](}z |Wnty4Yn0q|d | |fWYd}~n d}~00|| g7}qX|S) aTries 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.IOBase]: open config files cSsg|]}t|ddr|qSrFrUrr r rrFsz5ArgumentParser._open_config_files..F)radd_helpcSsdSrr )r*messager r r error_methodsz7ArgumentParser._open_config_files..error_method)rNr*z)Unable to open config file: %s. Error: %s)r\globospath expanduserrrrrr rr _add_actiontypes MethodTyperrrUrrRrrr]r )r*Zcommand_line_argsZ config_filesfilesfZuser_config_file_arg_actionsr Z arg_parserr>Z parsed_argrrZuser_config_filer,rXerrnor5rr r rrsX         z!ArgumentParser._open_config_filescCstdtdtdtdi}t}|jD]\}}|d}||dt|dd}| ||D]`\}\}}|r| d |d |qdt |t r| d |qdt |t rd| d d |qdq$|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 zCommand Line Args: zEnvironment Variables: zConfig File (%s): z Defaults: |rrGNz {:<19}{} rcz %s r=)rrrrrrr/rSrr^rTrr]rZr[r_)r*Zsource_key_to_display_value_mapr`r,r-r9r r;r r r format_values6s*    zArgumentParser.format_valuescCs||dS)zBPrints the format_values() string (to sys.stdout or another file).N)r^rJ)r*rr r r print_valuesWszArgumentParser.print_valuesc sd}d}d}jr҈j}djd}fddjD}ddjD}|r|sV|rd_d}|d |7}d d d |D}|rd |}|s|r|dd ttt|ttd|g7}|dj 7}j r>ddjD} | D]N\} } | j t krqd| } | j sd| _ | | j vr| j | 7_ d}d_ q|sJ|rdg} |r`dg| } |rpdg| } |dd| 7}tjd}t||}tj|dkrd|ndS)Nr>Fr*rcs@g|]8}|jD],}|r|jdks|js|js||fqqS)r)rr rrr)rDrrr)r rrFbs   z.ArgumentParser.format_help..cSsg|]}t|ddr|qSr:r;rr r rrFmsTz:Args that start with '%s' can also be set in a config filez or css|]}|jr|jdVqdS)rN)rrr r rrxsz-ArgumentParser.format_help..zspecified via z (%s).r=cSs"g|]}t|ddr|j|fqS)rN)rUrrr r rrFsz [env var: %s]rzconfig file valueszenvironment variablesz- In general, command-line values override %s.z which override z {} )rrrrr[rr\r]filterrr+rrrmax_get_formatter_widthtextwrapfillr r format_helprT)r*r5Zadded_config_file_helpZadded_env_var_helprZccZconfig_settable_argsZconfig_path_actionsZconfig_arg_stringZenv_var_actionsrrZenv_var_help_stringZ value_sources text_widthr r)rrS[sv             zArgumentParser.format_help)F)r"r#r$r%rrr@environrrr#rrr&rr rrJrstdoutrKrSr r r rr;s.#)  Y 3_P!rcOs|dd}|ddp"|dd}|dd}|j|i|}|j |_||_||_||_|jrn|rntd|jrt|t j std|jrd}t|t j st|d |rt|d |S) aL This method supports the same args as ArgumentParser.add_argument(..) as well as the additional args below. Keyword 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 rNrZis_config_filerz*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 zmust have action='store'z'can't also have is_config_file_arg=True) roriginal_add_argument_methodrrrrrrrr r6)r*rrrrrr Z error_prefixr r rrs.      rcsbg|D]B}|r@|d|vr@d|vr@|dd\}}|q|qtfdd|DS)zUtility method for checking if any of the potential_command_line_args is already present in existing_args. Returns: bool: already on command line? rrbrGc3s|]}|vVqdSrr )rDZ potential_arg arg_namesr rrsz*already_on_command_line..)rSrr)Zexisting_args_listZpotential_command_line_argsr arg_string option_string explicit_argr rXrrs    r)N)N)T)T)]r%r rtrnr functoolsrPr?r@rLrrD collectionsrrQior_StoreTrueAction_StoreFalseActionr4_StoreConstAction_AppendConstActionrrrr r3rrrrrRawTextHelpFormatterRawDescriptionHelpFormatterr objectr&rRr2r3rar~compilerDOTALLr lru_cacherrrrrrrrrrrrrr_ActionsContainerrWActionrArgumentTypeErrorFileTyperMetavarTypeHelpFormatter Namespace ONE_OR_MORErPARSERrrrZinitArgumentParserZgetArgumentParserZ getArgParserZ getParserZget_arg_parserZ get_parserZ ArgParserZParserZadd_argaddrr-rZ parse_knownZ RawFormatterZDefaultsFormatterZDefaultsRawFormatterr r r rs         (XL`   |@p8