def _SetUnknownFlag(self, name, value): """Returns value if setting flag |name| to |value| returned True. Args: name: Name of the flag to set. value: Value to set. Returns: Flag value on successful call. Raises: UnrecognizedFlagError IllegalFlagValueError """ setter = self.__dict__['__set_unknown'] if setter: try: setter(name, value) return value except (TypeError, ValueError): # Flag value is not valid. raise exceptions.IllegalFlagValueError( '"{1}" is not valid for --{0}'.format(name, value)) except NameError: # Flag name is not valid. pass raise exceptions.UnrecognizedFlagError(name, value)
def __call__(self, argv, known_only=False): """Parses flags from argv; stores parsed flags into this FlagValues object. All unparsed arguments are returned. Args: argv: argument list. Can be of any type that may be converted to a list. known_only: parse and remove known flags, return rest untouched. Returns: The list of arguments not parsed as options, including argv[0]. Raises: Error: on any parsing error. ValueError: on flag value parsing error. """ if not argv: # Unfortunately, the old parser used to accept an empty argv, and some # users rely on that behaviour. Allow it as a special case for now. self.MarkAsParsed() self._AssertAllValidators() return [] # This pre parses the argv list for --flagfile=<> options. program_name = argv[0] args = self.ReadFlagsFromFiles(argv[1:], force_gnu=False) # Parse the arguments. unknown_flags, unparsed_args, undefok = self._ParseArgs( args, known_only) # Handle unknown flags by raising UnrecognizedFlagError. # Note some users depend on us raising this particular error. for name, value in unknown_flags: if name in undefok: continue suggestions = _helpers.GetFlagSuggestions(name, self.RegisteredFlags()) raise exceptions.UnrecognizedFlagError(name, value, suggestions=suggestions) self.MarkAsParsed() self._AssertAllValidators() return [program_name] + unparsed_args
def _RemoveAllFlagAppearances(self, name): """Removes flag with name for all appearances. A flag can be registered with its long name and an optional short name. This method removes both of them. This is different than __delattr__. Args: name: Either flag's long name or short name. Raises: UnrecognizedFlagError: When flag name is not found. """ flag_dict = self.FlagDict() if name not in flag_dict: raise exceptions.UnrecognizedFlagError(name) flag = flag_dict[name] names_to_remove = {name} names_to_remove.add(flag.name) if flag.short_name: names_to_remove.add(flag.short_name) for n in names_to_remove: self.__delattr__(n)
def GetFlag(self, name): """Same as __getitem__, but raises a specific error.""" res = self.FlagDict().get(name) if res is None: raise exceptions.UnrecognizedFlagError(name) return res