B @`Åã@sdZddlmZddlmZddlmZddlZddlZddlZddlZddl Z ddl m Z ddl m Z ddl mZdd l mZddlZyddlZdd lmZmZWnek r¼dZYnXej ee jeƒ¡Gd d „d eƒZeƒZere d ¡ZejeZ neZ Gdd„de ƒZ!dS)z³Defines the FlagValues class - registry of 'Flag' objects. Do NOT import this module directly. Import the flags package and use the aliases defined at the package level instead. é)Úabsolute_import)Údivision)Úprint_functionN)Úminidom)Ú _exceptions)Ú_flag)Ú_helpers)ÚTextÚOptionalc@seZdZdZdd„Zdƒdd„Zdd„Zd d „Zd d „Zd d„Z dd„Z dd„Z dd„Z dd„Z dd„Zdd„Zdd„Zdd„Zd„d d!„Zd…d"d#„Zd$d%„Zd&d'„Zd(d)„Zd*d+„Zd,d-„Zd.d/„Zd0d1„Zd2d3„Zd4d5„Zd6d7„Zd8d9„Zd:d;„Zdd?„Z!d@dA„Z"dBdC„Z#dDdE„Z$dFdG„Z%d†dIdJ„Z&dKdL„Z'dMdN„Z(dOdP„Z)dQdR„Z*dSdT„Z+dUdV„Z,dWdX„Z-dYdZ„Z.d[d\„Z/d]d^„Z0d‡d`da„Z1dbdc„Z2dˆddde„Z3d‰dfdg„Z4dŠdhdi„Z5djdk„Z6dldm„Z7d‹dodp„Z8dqdr„Z9dsdt„Z:dudv„Z;dŒdwdx„Zd}d~„Z?dŽdd€„Z@dd‚„ZAdS)Ú FlagValuesa0Registry of 'Flag' objects. A 'FlagValues' can then scan command line arguments, passing flag arguments through to the 'Flag' objects that it owns. It also provides easy access to the flag values. Typically only one 'FlagValues' object is needed by an application: flags.FLAGS This class is heavily overloaded: 'Flag' objects are registered via __setitem__: FLAGS['longname'] = x # register a new flag The .value attribute of the registered 'Flag' objects can be accessed as attributes of this 'FlagValues' object, through __getattr__. Both the long and short name of the original 'Flag' objects can be used to access its value: FLAGS.longname # parsed flag value FLAGS.x # parsed flag value (short name) Command line arguments are scanned and passed to the registered 'Flag' objects through the __call__ method. Unparsed arguments, including argv[0] (e.g. the program name) are returned. argv = FLAGS(sys.argv) # scan command line arguments The original registered Flag objects can be retrieved through the use of the dictionary-like operator, __getitem__: x = FLAGS['longname'] # access the registered Flag object The str() operator of a 'FlagValues' object provides help for all of the registered 'Flag' objects. cCs†i|jd<tƒ|jd<i|jd<i|jd<i|jd<d|jd<d|jd<d|jd <tttƒƒ|jd <d |jd <d|jd <d|jd<dS)NÚ__flagsÚ __hiddenflagsÚ__flags_by_moduleÚ__flags_by_module_idÚ__key_flags_by_moduleFÚ__flags_parsedÚ__unparse_flags_calledÚ __set_unknownÚ__banned_flag_namesTÚ__use_gnu_getoptÚ__use_gnu_getopt_explicitly_setÚ__is_retired_flag_func)Ú__dict__ÚsetÚ frozensetÚdirr )Úself©rú:/tmp/pip-unpacked-wheel-01biqzia/absl/flags/_flagvalues.pyÚ__init__Ws          zFlagValues.__init__TcCs||jd<d|jd<dS)aSets whether or not to use GNU style scanning. GNU style allows mixing of flag and non-flag arguments. See http://docs.python.org/library/getopt.html#getopt.gnu_getopt Args: gnu_getopt: bool, whether or not to use GNU style scanning. rTrN)r)rÚ gnu_getoptrrrÚset_gnu_getopt…s zFlagValues.set_gnu_getoptcCs |jdS)Nr)r)rrrrÚ is_gnu_getopt‘szFlagValues.is_gnu_getoptcCs |jdS)Nr )r)rrrrÚ_flags”szFlagValues._flagscCs |jdS)z¹Returns the dictionary of module_name -> list of defined flags. Returns: A dictionary. Its keys are module names (strings). Its values are lists of Flag objects. r)r)rrrrÚflags_by_module_dict—szFlagValues.flags_by_module_dictcCs |jdS)z²Returns the dictionary of module_id -> list of defined flags. Returns: A dictionary. Its keys are module IDs (ints). Its values are lists of Flag objects. r)r)rrrrÚflags_by_module_id_dict sz"FlagValues.flags_by_module_id_dictcCs |jdS)zµReturns the dictionary of module_name -> list of key flags. Returns: A dictionary. Its keys are module names (strings). Its values are lists of Flag objects. r)r)rrrrÚkey_flags_by_module_dict©sz#FlagValues.key_flags_by_module_dictcCs| ¡}| |g¡ |¡dS)a#Records the module that defines a specific flag. We keep track of which flag is defined by which module so that we can later sort the flags by module. Args: module_name: str, the name of a Python module. flag: Flag, the Flag instance that is key to the module. N)r$Ú setdefaultÚappend)rÚ module_nameÚflagÚflags_by_modulerrrÚregister_flag_by_module²s z"FlagValues.register_flag_by_modulecCs| ¡}| |g¡ |¡dS)z²Records the module that defines a specific flag. Args: module_id: int, the ID of the Python module. flag: Flag, the Flag instance that is key to the module. N)r%r'r()rÚ module_idr*Zflags_by_module_idrrrÚregister_flag_by_module_id¿sz%FlagValues.register_flag_by_module_idcCs*| ¡}| |g¡}||kr&| |¡dS)zµSpecifies that a flag is a key flag for a module. Args: module_name: str, the name of a Python module. flag: Flag, the Flag instance that is key to the module. N)r&r'r()rr)r*Zkey_flags_by_moduleÚ key_flagsrrrÚregister_key_flag_for_moduleÉs z'FlagValues.register_key_flag_for_modulecCsH| ¡}|j}| |d¡|kr"dS|j}|dk rD| |d¡|krDdSdS)zèChecks whether a Flag object is registered under long name or short name. Args: flag_obj: Flag, the Flag instance to check for. Returns: bool, True iff flag_obj is registered under long name or short name. NTF)r#ÚnameÚgetÚ short_name)rÚflag_objÚ flag_dictr1r3rrrÚ_flag_is_registered×s zFlagValues._flag_is_registeredcCs^| |¡rdSxJ| ¡| ¡| ¡fD]0}x*t |¡D]}x||krP| |¡q [flags] dictionaries. If flag_obj is registered under either its long name or short name, it won't be removed from the dictionaries. Args: flag_obj: Flag, the Flag instance to clean up for. N)r6r$r%r&ÚsixÚ itervaluesÚremove)rr4r$Zflags_in_modulerrrÚ,_cleanup_unregistered_flag_from_module_dictsës  z7FlagValues._cleanup_unregistered_flag_from_module_dictscCs6t|tƒs|j}|dkr"tjd}t| ¡ |g¡ƒS)a1Returns the list of flags defined by a module. Args: module: module|str, the module to get flags from. Returns: [Flag], a new list of Flag instances. Caller may update this list as desired: none of those changes will affect the internals of this FlagValue instance. Ú__main__r)Ú isinstanceÚstrÚ__name__ÚsysÚargvÚlistr$r2)rÚmodulerrrÚget_flags_for_moduleÿs  zFlagValues.get_flags_for_modulecCs\t|tƒs|j}|dkr"tjd}| |¡}x*| ¡ |g¡D]}||kr>| |¡q>W|S)a2Returns the list of key flags for a module. Args: module: module|str, the module to get key flags from. Returns: [Flag], a new list of Flag instances. Caller may update this list as desired: none of those changes will affect the internals of this FlagValue instance. r;r) r<r=r>r?r@rCr&r2r()rrBr/r*rrrÚget_key_flags_for_modules   z#FlagValues.get_key_flags_for_moduleNcCsd| ¡ |¡}|dkr|SxDt | ¡¡D]2\}}x(|D] }|j|jkr8|j|jkr8|Sq8Wq*W|S)a~Return the name of the module defining this flag, or default. Args: flagname: str, name of the flag to lookup. default: Value to return if flagname is not defined. Defaults to None. Returns: The name of the module which registered the flag with this name. If no such module exists (i.e. no flag with this name exists), we return default. N)r#r2r7Ú iteritemsr$r1r3)rÚflagnameÚdefaultÚregistered_flagrBÚflagsr*rrrÚfind_module_defining_flag,s     z$FlagValues.find_module_defining_flagcCsd| ¡ |¡}|dkr|SxDt | ¡¡D]2\}}x(|D] }|j|jkr8|j|jkr8|Sq8Wq*W|S)azReturn the ID of the module defining this flag, or default. Args: flagname: str, name of the flag to lookup. default: Value to return if flagname is not defined. Defaults to None. Returns: The ID of the module which registered the flag with this name. If no such module exists (i.e. no flag with this name exists), we return default. N)r#r2r7rEr%r1r3)rrFrGrHr-rIr*rrrÚfind_module_id_defining_flagEs     z'FlagValues.find_module_id_defining_flagcCs||jd<dS)zÊAllow set default values for undefined flags. Args: setter: Method(name, value) to call to __setattr__ an unknown flag. Must raise NameError or ValueError for invalid name/value. rN)r)rÚsetterrrrÚ_register_unknown_flag_setter^sz(FlagValues._register_unknown_flag_setterc Csj|jd}|rZy|||ƒ|Sttfk rFt d ||¡¡‚Yntk rXYnXt ||¡‚dS)a Returns value if setting flag |name| to |value| returned True. Args: name: str, name of the flag to set. value: Value to set. Returns: Flag value on successful call. Raises: UnrecognizedFlagError IllegalFlagValueError rz"{1}" is not valid for --{0}N)rÚ TypeErrorÚ ValueErrorrÚIllegalFlagValueErrorÚformatÚ NameErrorÚUnrecognizedFlagError)rr1ÚvaluerLrrrÚ_set_unknown_flaggs  zFlagValues._set_unknown_flagc Cs`xZt | ¡¡D]H\}}||jkry |||<Wqtjk rVtjj|||d‚YqXqWdS)z™Appends flags registered in another FlagValues instance. Args: flag_values: FlagValues, the FlagValues instance from which to copy flags. )Zother_flag_valuesN)r7rEr#r1rÚDuplicateFlagErrorÚ from_flag)rÚ flag_valuesÚ flag_namer*rrrÚappend_flag_valuess  zFlagValues.append_flag_valuescCsx|D]}| |¡qWdS)z®Remove flags that were previously appended from another FlagValues. Args: flag_values: FlagValues, the FlagValues instance containing flags to remove. N)Ú __delattr__)rrXrYrrrÚremove_flag_values”s zFlagValues.remove_flag_valuesc Cs®| ¡}t|tjƒst |¡‚ttkr:t|tƒr:|  d¡}t|t dƒƒsRt  d¡‚|s`t  d¡‚d|krrt  d¡‚|  ||¡||krÔ|j sÔ||j sÔt ¡\}}| |¡|krÆt|ƒ| |¡krÆdStj ||¡‚|j}tƒ}|dk rD||kr|j s||j stj ||¡‚||kr<|||kr<| ||¡|||<||ksb||jsb|js||krˆ|||krˆ| ||¡|||<x|D]}| |¡q–WdS)zRegisters a new flag variable.zutf-8ÚzFlag name must be a stringzFlag name cannot be emptyú z Flag name cannot contain a spaceN)r#r<rÚFlagrrPr=ÚbytesÚunicodeÚencodeÚtypeÚErrorÚ_check_method_name_conflictsZallow_overriderZ"get_calling_module_object_and_namerJÚidrKrVrWr3rÚaddÚusing_default_valuer:) rr1r*ÚflrBr)r3Zflags_to_cleanupÚfrrrÚ __setitem__žsD            zFlagValues.__setitem__cCst|jdƒS)zœReturns list of names of all defined flags. Useful for TAB-completion in ipython. Returns: [str], a list of names of all defined flags. r )Úsortedr)rrrrÚ__dir__ÊszFlagValues.__dir__cCs | ¡|S)z,Returns the Flag object for the flag --name.)r#)rr1rrrÚ __getitem__ÔszFlagValues.__getitem__cCs|jd |¡dS)z Marks the flag --name as hidden.r N)rrg)rr1rrrÚ _hide_flagØszFlagValues._hide_flagcCsr| ¡}||krt|ƒ‚||jdkr.t|ƒ‚|jdsB||jrL||jSd|}tjrdt |¡t   |¡‚dS)z3Retrieves the 'value' attribute of the flag --name.r rz4Trying to access flag --%s before flags were parsed.N) r#ÚAttributeErrorrZpresentrTr7ÚPY2ÚloggingÚerrorrZUnparsedFlagAccessError)rr1riÚ error_messagerrrÚ __getattr__Üs  zFlagValues.__getattr__cCs|jf||iŽ|S)z.Sets the 'value' attribute of the flag --name.)Ú_set_attributes)rr1rTrrrÚ __setattr__ôszFlagValues.__setattr__cKs’| ¡}tƒ}xVt |¡D]H\}}||jdkr8t|ƒ‚||krV|||_| |¡q| ||¡qWx&|D]}|  ||j ¡d||_ qlWdS)zCSets multiple flag values together, triggers validators afterwards.r FN) r#rr7rErrprTrgrUÚ_assert_validatorsÚ validatorsrh)rÚ attributesriZ known_flagsr1rTrrrrvùs   zFlagValues._set_attributescCs8tƒ}x"t | ¡¡D]}| |j¡qW| |¡dS)zåVerifies whether all flags pass validation. Raises: AttributeError: Raised if validators work with a non-existing flag. IllegalFlagValueError: Raised if validation fails for at least one validator. N)rr7r8r#Úupdateryrx)rZall_validatorsr*rrrÚvalidate_all_flags szFlagValues.validate_all_flagsc Csrxlt|dd„dD]X}y| |¡Wqtjk rh}z$| |¡}t d|t|ƒf¡‚Wdd}~XYqXqWdS)aAsserts if all validators in the list are satisfied. It asserts validators in the order they were created. Args: validators: Iterable(validators.Validator), validators to be verified. Raises: AttributeError: Raised if validators work with a non-existing flag. IllegalFlagValueError: Raised if validation fails for at least one validator. cSs|jS)N)Zinsertion_index)Ú validatorrrrÚ$óz/FlagValues._assert_validators..)Úkeyz%s: %sN)rlÚverifyrZValidationErrorZprint_flags_with_valuesrPr=)rryr}ÚeÚmessagerrrrxs  zFlagValues._assert_validatorscCs4| ¡}||krt|ƒ‚||}||=| |¡dS)aDeletes a previously-defined flag from a flag object. This method makes sure we can delete a flag by using del FLAGS. E.g., flags.DEFINE_integer('foo', 1, 'Integer flag.') del flags.FLAGS.foo If a flag is also registered by its the other name (long name or short name), the other name won't be deleted. Args: flag_name: str, the name of the flag to be deleted. Raises: AttributeError: Raised when there is no registered flag named flag_name. N)r#rpr:)rrYrir4rrrr[+s zFlagValues.__delattr__cCsB| ¡}||kr | ||¡dS|| |¡| ||j¡dS)aæChanges the default value of the named flag object. The flag's current value is also updated if the flag is currently using the default value, i.e. not specified in the command line, and not set by FLAGS.name = value. Args: name: str, the name of the flag to modify. value: The new default value. Raises: UnrecognizedFlagError: Raised when there is no registered flag named name. IllegalFlagValueError: Raised when value is not valid. N)r#rUZ _set_defaultrxry)rr1rTrirrrÚ set_defaultIs  zFlagValues.set_defaultcCs || ¡kS)z3Returns True if name is a value (flag) in the dict.)r#)rr1rrrÚ __contains___szFlagValues.__contains__cCst|jdƒS)Nr )Úlenr)rrrrÚ__len__cszFlagValues.__len__cCs t| ¡ƒS)N)Úiterr#)rrrrÚ__iter__fszFlagValues.__iter__Fc Cs˜t |¡rtdƒ‚|stdƒ‚|d}|j|dd…dd}| ||¡\}}x0|D](\}}t |t|ƒ¡} tj ||| d‚qRW|  ¡|  ¡|g|S) aDParses flags from argv; stores parsed flags into this FlagValues object. All unparsed arguments are returned. Args: argv: a tuple/list of strings. known_only: bool, if True, parse and remove known flags; return the rest untouched. Unknown flags specified by --undefok are not returned. Returns: The list of arguments not parsed as options, including argv[0]. Raises: Error: Raised on any parsing error. TypeError: Raised on passing wrong type of arguments. ValueError: Raised on flag value parsing error. z (bool, bool), a function takes flag name as parameter, returns a tuple (is_retired, type_is_bool). rN)r)rZis_retired_flag_funcrrrÚ_set_is_retired_flag_func¡s z$FlagValues._set_is_retired_flag_funccsÒg}tƒ}|jd}| ¡}tˆƒ‰x2ˆD](‰d‰‡‡‡fdd„}ˆ d¡sl| dˆf¡| ¡rjq,nPˆdkrˆ|r†| dˆf¡Pˆ d¡r ˆdd…}n ˆdd…}d |krÆ| d d¡\} ‰n |d} ‰| sð| dˆf¡| ¡rîq,nP| d kr6|ƒ‰| d d „ˆ d ¡Dƒ¡| dd „ˆ d ¡Dƒ¡q,|  | ¡} | rf| j r^ˆdkr^d‰n|ƒ‰nX|  d¡r¾t | ƒdkr¾|  | dd…¡} | r¾| j r¾ˆdk r¶t ˆdƒ‚| } d‰|r0| s0|| ƒ\} } | s|  d¡r|| dd…ƒ\} } | o| } | r0| s"ˆdkr"|ƒt  d| ¡q,| rH|  ˆ¡d| _q,| | ˆf¡q,Wg}g}xX|D]P\} ‰| dkr†| ˆ¡n0| |kr–qhn |r¨| ˆ¡n| | ˆf¡qhW| tˆƒ¡||fS)aHelper function to do the main argument parsing. This function goes through args and does the bulk of the flag parsing. It will find the corresponding flag in our flag dictionary, and call its .parse() method on the flag value. Args: args: [str], a list of strings with the arguments to parse. known_only: bool, if True, parse and remove known flags; return the rest untouched. Unknown flags specified by --undefok are not returned. Returns: A tuple with the following: unknown_flags: List of (flag name, arg) for flags we don't know about. unparsed_args: List of arguments we did not parse. Raises: Error: Raised on any parsing error. ValueError: Raised on flag value parsing error. rNcs<yˆdkrtˆƒSˆStk r6t dˆ¡‚YnXdS)NzMissing value for flag )ÚnextÚ StopIterationrrdr)Úargr‘rTrrÚ get_valueËsz)FlagValues._parse_args..get_valueú-z--érŠú=Úundefokcss|]}| ¡VqdS)N)Ústrip)Ú.0Úvrrrú õsz)FlagValues._parse_args..ú,css|]}d| ¡VqdS)ÚnoN)r§)r¨r©rrrrªösÚtruer¬z does not take an argumentÚfalsezGFlag "%s" is retired and should no longer be specified. See go/totw/90.F)rrr#rˆÚ startswithr(r"Úsplitr{r2Úbooleanr†rOrrrsÚparserhÚextendrA)rr‘rZunparsed_names_and_argsr¦Zretired_flag_funcr5r¢Zarg_without_dashesr1r*ZnoflagZ is_retiredZis_boolr’r“r)r¡r‘rTrrŽ­s’                 zFlagValues._parse_argscCs |jdS)z"Returns whether flags were parsed.r)r)rrrrÚ is_parsed5szFlagValues.is_parsedcCsd|jd<dS)aExplicitly marks flags as parsed. Use this when the caller knows that this FlagValues has been parsed as if a __call__() invocation has happened. This is only a public method for use by things like appcommands which do additional command like parsing. TrN)r)rrrrr9szFlagValues.mark_as_parsedcCs@x| ¡ ¡D] }| ¡qWt d¡d|jd<d|jd<dS)zBUnparses all flags to the point before any FLAGS(argv) was called.z;unparse_flags() called; flags access will now raise errors.FrTrN)r#ÚvaluesZunparserrÚinfor)rrjrrrÚ unparse_flagsBs    zFlagValues.unparse_flagscCsdd„t | ¡¡DƒS)z9Returns a dictionary that maps flag names to flag values.cSsi|]\}}|j|“qSr)rT)r¨r1r*rrrú Nsz/FlagValues.flag_values_dict..)r7rEr#)rrrrÚflag_values_dictLszFlagValues.flag_values_dictcCs| ¡S)z*Returns a help string for all known flags.)Úget_help)rrrrÚ__str__PszFlagValues.__str__r]cCs’| ¡}|rHt|ƒ}tjd}||kr:| |¡|g|}| |||¡Sg}t | ¡¡}|rvt   |t t j  ¡¡¡}|  |||¡d |¡SdS)aReturns a help string for all known flags. Args: prefix: str, per-line output prefix. include_special_flags: bool, whether to include description of SPECIAL_FLAGS, i.e. --flagfile and --undefok. Returns: str, formatted help message. rÚ N)r$rlr?r@r9Ú_get_help_for_modulesr7r8r#Ú itertoolsÚchainrÚ SPECIAL_FLAGSÚ_render_flag_listÚjoin)rÚprefixÚinclude_special_flagsr+ÚmodulesZ main_moduleÚ output_linesrµrrrrºTs    zFlagValues.get_helpcCsJg}x|D]}| |||¡q W|r@| dt tj ¡¡||¡d |¡S)apReturns the help string for a list of modules. Private to absl.flags package. Args: modules: List[str], a list of modules to get the help string for. prefix: str, a string that is prepended to each generated help line. include_special_flags: bool, whether to include description of SPECIAL_FLAGS, i.e. --flagfile and --undefok. z absl.flagsr¼)Ú_render_our_module_flagsÚ_render_module_flagsr7r8rrÀr#rÂ)rrÅrÃrÄrÆrBrrrr½ss  z FlagValues._get_help_for_modulescCs8t|tƒs|j}| d||f¡| |||d¡dS)z)Returns a help string for a given module.z %s%s:z N)r<r=r>r(rÁ)rrBrIrÆrÃrrrrȉs zFlagValues._render_module_flagscCs"| |¡}|r| ||||¡dS)z)Returns a help string for a given module.N)rCrÈ)rrBrÆrÃrIrrrrÇs z#FlagValues._render_our_module_flagscCs"| |¡}|r| ||||¡dS)aJReturns a help string for the key flags of a given module. Args: module: module|str, the module to render key flags for. output_lines: [str], a list of strings. The generated help message lines will be appended to this list. prefix: str, a string that is prepended to each generated help line. N)rDrÈ)rrBrÆrÃr/rrrÚ_render_our_module_key_flags–s z'FlagValues._render_our_module_key_flagscCsg}| ||¡d |¡S)z·Describes the key flags of a module. Args: module: module|str, the module to describe the key flags for. Returns: str, describing the key flags of a module. r¼)rÉrÂ)rrBZhelplistrrrÚ module_help£s  zFlagValues.module_helpcCs| tjd¡S)zvDescribes the key flags of the main module. Returns: str, describing the key flags of the main module. r)rÊr?r@)rrrrÚmain_module_help°szFlagValues.main_module_helpú c CsH| ¡}tj ¡}dd„|Dƒ}| ¡i}x|D] \}}| |d¡|kr`| |d¡|kr`q4||krjq4d||<d} |jrŠ| d|j7} |jr | d|j7} n| d|j7} | d7} |jrÆ| |j7} tj | |d |d } |j r| d 7} | tj d |j |d d 7} |j j r6| d 7} | tj d|j j |d d 7} |  | ¡q4WdS)NcSsg|]}|j|f‘qSr)r1)r¨r*rrrú »sz0FlagValues._render_flag_list..rŠr]z-%s,z --[no]%s:z--%s:r^z )ÚindentZfirstline_indentr¼z (default: %s))rÎz(%s))r#rrÀÚsortr2r3r±r1ÚhelpZ text_wrapZdefault_as_strÚparserZsyntactic_helpr() rZflaglistrÆrÃriZ special_flZflagsetr1r*ZflaghelprrrrÁ¸s>    zFlagValues._render_flag_listcCs| |¡}|dk r|S|SdS)zæReturns the value of a flag (if not None) or a default value. Args: name: str, the name of a flag. default: Default value to use if the flag value is None. Returns: Requested flag value or default. N)ru)rr1rGrTrrrÚget_flag_valueßs zFlagValues.get_flag_valuecCsJt|tdƒƒrF| d¡rdS|dkr(dS| d¡r6dS|dkrBdSdSdS)z@Checks whether flag_string contain a --flagfile= directive.r]z --flagfile=rŠz --flagfilez -flagfile=z -flagfiler)r<rcr¯)rZ flag_stringrrrÚ_is_flag_file_directiveðs  z"FlagValues._is_flag_file_directivecCs^| d¡r&tj |tdƒd… ¡¡S| d¡rLtj |tdƒd… ¡¡St d|¡‚dS)a¸Returns filename from a flagfile_str of form -[-]flagfile=filename. The cases of --flagfile foo and -flagfile foo shouldn't be hitting this function, as they are dealt with in the level above this function. Args: flagfile_str: str, the flagfile string. Returns: str, the filename from a flagfile_str of form -[-]flagfile=filename. Raises: Error: Raised when illegal --flagfile is provided. z --flagfile=Nz -flagfile=zHit illegal --flagfile type: %s)r¯ÚosÚpathÚ expanduserr†r§rrd)rZ flagfile_strrrrÚ_extract_filenameÿs   zFlagValues._extract_filenamec Cs|sgS|dkrg}||kr2tj d|f¡gS| |¡g}g}yt|dƒ}Wn0tk r‚}zt d|¡‚Wdd}~XYnX|| ¡}WdQRXxh|D]`}|  ¡r°q¢|  d¡sÄ|  d¡rÆq¢|  |¡rô|  |¡}|j ||d} | | ¡q¢| | ¡¡q¢W| ¡|S)aäReturns the useful (!=comments, etc) lines from a file with flags. Args: filename: str, the name of the flag file. parsed_file_stack: [str], a list of the names of the files that we have recursively encountered at the current depth. MUTATED BY THIS FUNCTION (but the original value is preserved upon successfully returning from function call). Returns: List of strings. See the note below. NOTE(springer): This function checks for a nested --flagfile= tag and handles the lower file recursively. It returns a list of all the lines that _could_ contain command flags. This is EVERYTHING except whitespace lines and comments (lines starting with '#' or '//'). NzAWarning: Hit circular flagfile dependency. Ignoring flagfile: %s Úrz#ERROR:: Unable to open flagfile: %sú#z//)Úparsed_file_stack)r?ÚstderrÚwriter(ÚopenÚIOErrorrZCantOpenFlagFileErrorÚ readlinesÚisspacer¯rÓr×Ú_get_flag_file_linesr³r§Úpop) rÚfilenamerÚZ line_listZflag_line_listZfile_objZe_msgÚlineZ sub_filenameZincluded_flagsrrrrás>       zFlagValues._get_flag_file_linesc Cs,|}g}x |r|d}|dd…}| |¡rˆ|dks@|dkrl|sNt d¡‚tj |d¡}|dd…}n | |¡}| | |¡¡q |  |¡|dkrœP|  d¡s¸|s¶|j d s¶Pq d |kr |r |d  d¡s |  ¡}|  d¡}||kr ||js |d}|dd…}|  |¡q W|r(| |¡|S) aÏProcesses command line args, but also allow args to be read from file. Args: argv: [str], a list of strings, usually sys.argv[1:], which may contain one or more flagfile directives of the form --flagfile="./filename". Note that the name of the program (sys.argv[0]) should be omitted. force_gnu: bool, if False, --flagfile parsing obeys the FLAGS.is_gnu_getopt() value. If True, ignore the value and always follow gnu_getopt semantics. Returns: A new list which has the original list combined with what we read from any flagfile(s). Raises: IllegalFlagValueError: Raised when --flagfile is provided with no argument. This function is called by FLAGS(argv). It scans the input list for a flag that looks like: --flagfile=. Then it opens , reads all valid key and value pairs and inserts them into the input list in exactly the place where the --flagfile arg is found. Note that your application's flags are still defined the usual way using absl.flags DEFINE_flag() type functions. Notes (assuming we're getting a commandline of some sort as our input): --> For duplicate flags, the last one we hit should "win". --> Since flags that appear later win, a flagfile's settings can be "weak" if the --flagfile comes at the beginning of the argument sequence, and it can be "strong" if the --flagfile comes at the end. --> A further "--flagfile=" CAN be nested in a flagfile. It will be expanded in exactly the spot where it is found. --> In a flagfile, a line beginning with # or // is a comment. --> Entirely blank lines _should_ be ignored. rrŠNz --flagfilez -flagfilez--flagfile with no argumentz--r£rr¥)rÓrrPrÔrÕrÖr×r³rár(r¯rr#Úlstripr±) rr@r‹Z rest_of_argsZnew_argvZ current_argZ flag_filenamerir1rrrrYs>&          z FlagValues.read_flags_from_filescCsbt| ¡ ¡ƒ}d}xH|D]@\}}t|dd„d}x&|D]}|jdk r8|| ¡d7}q8WqW|S)aÂReturns a string with the flags assignments from this FlagValues object. This function ignores flags whose value is None. Each flag assignment is separated by a newline. NOTE: MUST mirror the behavior of the C++ CommandlineFlagsIntoString from https://github.com/gflags/gflags. Returns: str, the string with the flags assignments from this FlagValues object. The flags are ordered by (module_name, flag_name). r]cSs|jS)N)r1)rjrrrr~»rz.FlagValues.flags_into_string..)r€Nr¼)rlr$ÚitemsrTÚ serialize)rZ module_flagsÚsZunused_module_namerIr*rrrÚflags_into_string«s   zFlagValues.flags_into_stringc Cs(t|dƒ}| | ¡¡WdQRXdS)aAppends all flags assignments from this FlagInfo object to a file. Output will be in the format of a flagfile. NOTE: MUST mirror the behavior of the C++ AppendFlagsIntoFile from https://github.com/gflags/gflags. Args: filename: str, name of the file. ÚaN)rÝrÜré)rrãÚout_filerrrÚappend_flags_into_fileÁs z!FlagValues.append_flags_into_filec CsXt ¡}| d¡}| |¡| t |dtj t j d¡¡¡t j dj }|s^dt j d}n|  dt j d¡}| t |d|¡¡| t j d¡}| ¡}t| ¡ƒ}| ¡xV|D]N}dd „||Dƒ} |  ¡x.| D]&\} } | |k} | | j||| d ¡qÚWq¶W|pt j}tjr2| |jd d d ¡n| |jd d d  d ¡¡| ¡dS)aÍOutputs flag documentation in XML format. NOTE: We use element names that are consistent with those used by the C++ command-line flag library, from https://github.com/gflags/gflags. We also use a few new elements (e.g., ), but we do not interfere / overlap with existing XML elements used by the C++ library. Please maintain this consistency. Args: outfile: File object we write to. Default None means sys.stdout. ZAllFlagsÚprogramrr;z USAGE: %s [flags] z%sÚusagecSsg|]}|j|f‘qSr)r1)r¨rjrrrrÍôsz7FlagValues.write_help_in_xml_format..)Úis_keyz zutf-8)rÎÚencodingN)rÚDocumentÚ createElementÚ appendChildrZcreate_xml_dom_elementrÔrÕÚbasenamer?r@rÅÚ__doc__ÚreplacerDr$rAÚkeysrÏZ_create_xml_dom_elementÚstdoutr7rqrÜZ toprettyxmlÚdecodeÚflush) rÚoutfileÚdocZall_flagZ usage_docr/r+Zall_module_namesr)Z flag_listZunused_flag_namer*rïrrrÚwrite_help_in_xml_formatÏs@       z#FlagValues.write_help_in_xml_formatcCs`|jr dS|j}|dkr|hn||h}x4|D],}||jdkr,t dj|t|ƒjd¡‚q,WdS)NrzöCannot define a flag named "{name}". It conflicts with a method on class "{class_name}". To allow defining it, use allow_using_method_names and access the flag value with FLAGS['{name}'].value. FLAGS.{name} returns the method, not the flag value.)r1Ú class_name)Zallow_using_method_namesr3rrZ FlagNameConflictsWithMethodErrorrQrcr>)rr1r*r3Z flag_namesrYrrrres z'FlagValues._check_method_name_conflicts)T)N)N)F)r]T)r])r])r])rÌ)N)T)N)Br>Ú __module__Ú __qualname__rõrr!r"r#r$r%r&r,r.r0r6r:rCrDrJrKrMrUrZr\rkrmrnrorurwrvr|rxr[r„r…r‡r‰r”r•r–rržrŽr´rr·r¹r»rºr½rÈrÇrÉrÊrËrÁrÒrÓr×rárrérìrýrerrrrr 0s€.          ,   ,          ' C R 7r Ú_Tc@sReZdZdZddd„Zdd„Zdd„ZeZed d „ƒZ ed d „ƒZ ed d„ƒZ dS)Ú FlagHolderaqHolds a defined flag. This facilitates a cleaner api around global state. Instead of ``` flags.DEFINE_integer('foo', ...) flags.DEFINE_integer('bar', ...) ... def method(): # prints parsed value of 'bar' flag print(flags.FLAGS.foo) # runtime error due to typo or possibly bad coding style. print(flags.FLAGS.baz) ``` it encourages code like ``` FOO_FLAG = flags.DEFINE_integer('foo', ...) BAR_FLAG = flags.DEFINE_integer('bar', ...) ... def method(): print(FOO_FLAG.value) print(BAR_FLAG.value) ``` since the name of the flag appears only once in the source code. FcCs||_|j|_||_dS)aConstructs a FlagHolder instance providing typesafe access to flag. Args: flag_values: The container the flag is registered to. flag: The flag object for this flag. ensure_non_none_value: Is the value of the flag allowed to be None. N)Ú _flagvaluesr1Ú_nameÚ_ensure_non_none_value)rrXr*Zensure_non_none_valuerrrr=szFlagHolder.__init__cCs td t|ƒjt|ƒj¡ƒ‚dS)Nz^unsupported operand type(s) for ==: '{0}' and '{1}' (did you mean to use '{0}.value' instead?))rNrQrcr>)rÚotherrrrÚ__eq__PszFlagHolder.__eq__cCstd t|ƒj¡ƒ‚dS)Nz[bool() not supported for instances of type '{0}' (did you mean to use '{0}.value' instead?))rNrQrcr>)rrrrÚ__bool__VszFlagHolder.__bool__cCs|jS)N)r)rrrrr1^szFlagHolder.namecCs0t|j|jƒ}|jr,|dkr,t d|j¡‚|S)zôReturns the value of the flag. If _ensure_non_none_value is True, then return value is not None. Raises: UnparsedFlagAccessError: if flag parsing has not finished. IllegalFlagValueError: if value is None unexpectedly. Nz!Unexpected None value for flag %s)ÚgetattrrrrrrP)rÚvalrrrrTbs  zFlagHolder.valuecCs|j|jjS)z&Returns the default value of the flag.)rrrG)rrrrrGrszFlagHolder.defaultN)F) r>rÿrrõrrrÚ __nonzero__Úpropertyr1rTrGrrrrrs   r)"rõÚ __future__rrrr™r¾rrrÔr?Úxml.domrZ absl.flagsrrrr7Útypingr r Ú ImportErrorZdisclaim_module_idsrgrfrÅr>r—r ÚFLAGSÚTypeVarrÚGenericZ_BaserrrrrÚsF        o