From 141e949fa9f09e5f54acdfa90f609895236a8ac0 Mon Sep 17 00:00:00 2001 From: Florian Dold Date: Thu, 29 Aug 2019 23:08:26 +0200 Subject: make pretty --- talersurvey/talerconfig.py | 112 ++++++++++++++++++++++++++++++++------------- 1 file changed, 79 insertions(+), 33 deletions(-) (limited to 'talersurvey/talerconfig.py') diff --git a/talersurvey/talerconfig.py b/talersurvey/talerconfig.py index 4a44c97..1a33294 100644 --- a/talersurvey/talerconfig.py +++ b/talersurvey/talerconfig.py @@ -38,17 +38,20 @@ try: except ImportError: pass + ## # Exception class for a any configuration error. class ConfigurationError(Exception): pass + ## # Exception class for malformed strings having with parameter # expansion. class ExpansionSyntaxError(Exception): pass + ## # Do shell-style parameter expansion. # Supported syntax: @@ -80,7 +83,7 @@ def expand(var: str, getter: Callable[[str], str]) -> str: end += 1 if balance != 0: raise ExpansionSyntaxError("unbalanced parentheses") - piece = var[start+2:end-1] + piece = var[start + 2:end - 1] if piece.find(":-") > 0: varname, alt = piece.split(":-", 1) replace = getter(varname) @@ -93,9 +96,9 @@ def expand(var: str, getter: Callable[[str], str]) -> str: replace = var[start:end] else: end = start + 2 - while end < len(var) and var[start+1:end+1].isalnum(): + while end < len(var) and var[start + 1:end + 1].isalnum(): end += 1 - varname = var[start+1:end] + varname = var[start + 1:end] replace = getter(varname) if replace is None: replace = var[start:end] @@ -104,6 +107,7 @@ def expand(var: str, getter: Callable[[str], str]) -> str: return result + var[pos:] + ## # A configuration entry. class Entry: @@ -164,11 +168,16 @@ class Entry: if self.value is None: if warn: if default is not None: - LOGGER.warning("Configuration is missing option '%s' in section '%s',\ - falling back to '%s'", self.option, self.section, default) + LOGGER.warning( + "Configuration is missing option '%s' in section '%s',\ + falling back to '%s'", self.option, + self.section, default + ) else: - LOGGER.warning("Configuration ** is missing option '%s' in section '%s'", - self.option.upper(), self.section.upper()) + LOGGER.warning( + "Configuration ** is missing option '%s' in section '%s'", + self.option.upper(), self.section.upper() + ) return default return self.value @@ -190,6 +199,7 @@ class Entry: except ValueError: raise ConfigurationError("Expected number for option '%s' in section '%s'" \ % (self.option.upper(), self.section.upper())) + ## # Fetch value to substitute to expansion variables. # @@ -231,6 +241,7 @@ class Entry: return "" return "%s:%s" % (self.filename, self.lineno) + ## # Represent a section by inheriting from 'defaultdict'. class OptionDict(collections.defaultdict): @@ -280,6 +291,7 @@ class OptionDict(collections.defaultdict): def __setitem__(self, chunk: str, value: Entry) -> None: super().__setitem__(chunk.lower(), value) + ## # Collection of all the (@a OptionDict) sections. class SectionDict(collections.defaultdict): @@ -313,6 +325,7 @@ class SectionDict(collections.defaultdict): def __setitem__(self, chunk: str, value: OptionDict) -> None: super().__setitem__(chunk.lower(), value) + ## # One loaded taler configuration, including base configuration # files and included files. @@ -323,7 +336,7 @@ class TalerConfig: # # @param self the object itself. def __init__(self) -> None: - self.sections = SectionDict() # just plain dict + self.sections = SectionDict() # just plain dict ## # Load a configuration file, instantiating a config object. @@ -362,7 +375,8 @@ class TalerConfig: # a error occurs). def value_string(self, section, option, **kwargs) -> str: return self.sections[section][option].value_string( - kwargs.get("default"), kwargs.get("required"), kwargs.get("warn")) + kwargs.get("default"), kwargs.get("required"), kwargs.get("warn") + ) ## # Get a value from the config that should be a filename. @@ -377,7 +391,8 @@ class TalerConfig: # a error occurs). def value_filename(self, section, option, **kwargs) -> str: return self.sections[section][option].value_filename( - kwargs.get("default"), kwargs.get("required"), kwargs.get("warn")) + kwargs.get("default"), kwargs.get("required"), kwargs.get("warn") + ) ## # Get a integer value from the config. @@ -391,7 +406,8 @@ class TalerConfig: # a error occurs). def value_int(self, section, option, **kwargs) -> int: return self.sections[section][option].value_int( - kwargs.get("default"), kwargs.get("required"), kwargs.get("warn")) + kwargs.get("default"), kwargs.get("required"), kwargs.get("warn") + ) ## # Load default values from canonical locations. @@ -465,36 +481,59 @@ class TalerConfig: if line.startswith("@INLINE@"): pair = line.split() if 2 != len(pair): - LOGGER.error("invalid inlined config filename given ('%s')" % line) - continue + LOGGER.error( + "invalid inlined config filename given ('%s')" % + line + ) + continue if pair[1].startswith("/"): self.load_file(pair[1]) else: - self.load_file(os.path.join(os.path.dirname(filename), pair[1])) + self.load_file( + os.path.join( + os.path.dirname(filename), pair[1] + ) + ) continue if line.startswith("["): if not line.endswith("]"): - LOGGER.error("invalid section header in line %s: %s", - lineno, repr(line)) + LOGGER.error( + "invalid section header in line %s: %s", lineno, + repr(line) + ) section_name = line.strip("[]").strip().strip('"') current_section = section_name continue if current_section is None: - LOGGER.error("option outside of section in line %s: %s", lineno, repr(line)) + LOGGER.error( + "option outside of section in line %s: %s", lineno, + repr(line) + ) continue pair = line.split("=", 1) if len(pair) != 2: - LOGGER.error("invalid option in line %s: %s", lineno, repr(line)) + LOGGER.error( + "invalid option in line %s: %s", lineno, repr(line) + ) key = pair[0].strip() value = pair[1].strip() if value.startswith('"'): value = value[1:] if not value.endswith('"'): - LOGGER.error("mismatched quotes in line %s: %s", lineno, repr(line)) + LOGGER.error( + "mismatched quotes in line %s: %s", lineno, + repr(line) + ) else: value = value[:-1] - entry = Entry(self.sections, current_section, key, - value=value, filename=filename, lineno=lineno) + entry = Entry( + self.sections, + current_section, + key, + value=value, + filename=filename, + lineno=lineno + ) sections[current_section][key] = entry except FileNotFoundError: # not logging here, as this interests the final user mostly. @@ -503,23 +542,22 @@ class TalerConfig: ## # Dump the textual representation of a config object. - # + # # Format: - # + # # [section] # option = value # FIXME (what is location?) # # @param self the object itself, that will be dumped. def dump(self) -> None: for kv_section in self.sections.items(): - print("[%s]" % (kv_section[1].section_name,)) + print("[%s]" % (kv_section[1].section_name, )) for kv_option in kv_section[1].items(): print("%s = %s # %s" % \ (kv_option[1].option, kv_option[1].value, kv_option[1].location())) - ## # Return a whole section from this object. # @@ -538,14 +576,22 @@ if __name__ == "__main__": import argparse PARSER = argparse.ArgumentParser() - PARSER.add_argument("--section", "-s", dest="section", - default=None, metavar="SECTION") - PARSER.add_argument("--option", "-o", dest="option", - default=None, metavar="OPTION") - PARSER.add_argument("--config", "-c", dest="config", - default=None, metavar="FILE") - PARSER.add_argument("--filename", "-f", dest="expand_filename", - default=False, action='store_true') + PARSER.add_argument( + "--section", "-s", dest="section", default=None, metavar="SECTION" + ) + PARSER.add_argument( + "--option", "-o", dest="option", default=None, metavar="OPTION" + ) + PARSER.add_argument( + "--config", "-c", dest="config", default=None, metavar="FILE" + ) + PARSER.add_argument( + "--filename", + "-f", + dest="expand_filename", + default=False, + action='store_true' + ) ARGS = PARSER.parse_args() TC = TalerConfig.from_file(ARGS.config) -- cgit v1.2.3