def __setitem__(self, name, flag): """Registers a new flag variable.""" fl = self.FlagDict() if not isinstance(flag, _flag.Flag): raise exceptions.IllegalFlagValue(flag) if str is bytes and isinstance(name, unicode): # When using Python 2 with unicode_literals, allow it but encode it # into the bytes type we require. name = name.encode('utf-8') if not isinstance(name, type('')): raise exceptions.FlagsError('Flag name must be a string') if not name: raise exceptions.FlagsError('Flag name cannot be empty') if name in fl and not flag.allow_override and not fl[ name].allow_override: module, module_name = _helpers.GetCallingModuleObjectAndName() if (self.FindModuleDefiningFlag(name) == module_name and id(module) != self.FindModuleIdDefiningFlag(name)): # If the flag has already been defined by a module with the same name, # but a different ID, we can stop here because it indicates that the # module is simply being imported a subsequent time. return raise exceptions.DuplicateFlagError(name, self) short_name = flag.short_name if short_name is not None: if (short_name in fl and not flag.allow_override and not fl[short_name].allow_override): raise exceptions.DuplicateFlagError(short_name, self) fl[short_name] = flag if (name not in fl # new flag or fl[name].using_default_value or not flag.using_default_value): fl[name] = flag
def ExtractFilename(self, flagfile_str): """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: flagfile string. Returns: str filename from a flagfile_str of form -[-]flagfile=filename. Raises: FlagsError: when illegal --flagfile provided. """ if flagfile_str.startswith('--flagfile='): return os.path.expanduser( (flagfile_str[(len('--flagfile=')):]).strip()) elif flagfile_str.startswith('-flagfile='): return os.path.expanduser( (flagfile_str[(len('-flagfile=')):]).strip()) else: raise exceptions.FlagsError('Hit illegal --flagfile type: %s' % flagfile_str)
def GetValue(): # pylint: disable=cell-var-from-loop try: return next(args) if value is None else value except StopIteration: raise exceptions.FlagsError('Missing value for flag ' + arg)
def Serialize(self): if self.value is None: return '' if self.boolean: if self.value: return '--%s' % self.name else: return '--no%s' % self.name else: if not self.serializer: raise exceptions.FlagsError( 'Serializer not present for flag %s' % self.name) return '--%s=%s' % (self.name, self.serializer.Serialize(self.value))
def Serialize(self): if not self.serializer: raise exceptions.FlagsError( 'Serializer not present for flag %s' % self.name) if self.value is None: return '' s = '' multi_value = self.value for self.value in multi_value: if s: s += ' ' s += Flag.Serialize(self) self.value = multi_value return s
def _ParseArgs(self, args): """Helper 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: List of strings with the arguments to parse. 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. undefok: Set of flags that were given via --undefok. """ unknown_flags, unparsed_args, undefok = [], [], set() flag_dict = self.FlagDict() i = 0 while i < len(args): arg = args[i] i += 1 if not arg.startswith('-'): # A non-argument: default is break, GNU is skip. unparsed_args.append(arg) if self.IsGnuGetOpt(): continue else: break if arg == '--': break if '=' in arg: name, value = arg.lstrip('-').split('=', 1) else: name, value = arg.lstrip('-'), None if not name: # The argument is all dashes (including one dash). unparsed_args.append(arg) if self.IsGnuGetOpt(): continue else: break # --undefok is a special case. if name == 'undefok': if value is None: try: value = args[i] i += 1 except IndexError: raise exceptions.FlagsError( 'Missing value for flag %s' % arg) undefok.update(v.strip() for v in value.split(',')) undefok.update('no' + v.strip() for v in value.split(',')) continue if name in flag_dict: flag = flag_dict[name] if flag.boolean and value is None: # Boolean flags can take the form of --flag, with no value. value = True else: if value is None: # The value is the next argument. try: value = args[i] i += 1 except IndexError: raise exceptions.FlagsError( 'Missing value for flag %s' % arg) else: # Boolean flags can take the form of --noflag, with no value. noflag = None if name.startswith('no'): noflag = flag_dict.get(name[2:], None) if noflag and noflag.boolean: flag = noflag value = False else: unknown_flags.append((name, arg)) continue flag.Parse(value) flag.using_default_value = False unparsed_args.extend(args[i:]) return unknown_flags, unparsed_args, undefok