[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[GNUnet-SVN] [taler-bank] 02/02: linting talerconfig
From: |
gnunet |
Subject: |
[GNUnet-SVN] [taler-bank] 02/02: linting talerconfig |
Date: |
Wed, 22 Nov 2017 13:08:04 +0100 |
This is an automated email from the git hooks/post-receive script.
marcello pushed a commit to branch master
in repository bank.
commit 8ea1eda49f644c9f049901651438b7ff52f185f0
Author: Marcello Stanisci <address@hidden>
AuthorDate: Wed Nov 22 13:07:42 2017 +0100
linting talerconfig
---
talerbank/talerconfig.py | 158 +++++++++++++++++++++++++----------------------
1 file changed, 83 insertions(+), 75 deletions(-)
diff --git a/talerbank/talerconfig.py b/talerbank/talerconfig.py
index d72e15f..e27caeb 100644
--- a/talerbank/talerconfig.py
+++ b/talerbank/talerconfig.py
@@ -28,15 +28,15 @@ import weakref
import sys
import re
-logger = logging.getLogger(__name__)
+LOGGER = logging.getLogger(__name__)
__all__ = ["TalerConfig"]
-taler_datadir = None
+TALER_DATADIR = None
try:
# not clear if this is a good idea ...
- from talerpaths import taler_datadir as t
- taler_datadir = t
+ from talerpaths import TALER_DATADIR as t
+ TALER_DATADIR = t
except ImportError:
pass
@@ -47,7 +47,7 @@ class ExpansionSyntaxError(Exception):
pass
-def expand(s, getter):
+def expand(var, getter):
"""
Do shell-style parameter expansion.
Supported syntax:
@@ -58,18 +58,18 @@ def expand(s, getter):
pos = 0
result = ""
while pos != -1:
- start = s.find("$", pos)
+ start = var.find("$", pos)
if start == -1:
break
- if s[start:].startswith("${"):
+ if var[start:].startswith("${"):
balance = 1
end = start + 2
- while balance > 0 and end < len(s):
- balance += {"{": 1, "}": -1}.get(s[end], 0)
+ while balance > 0 and end < len(var):
+ balance += {"{": 1, "}": -1}.get(var[end], 0)
end += 1
if balance != 0:
raise ExpansionSyntaxError("unbalanced parentheses")
- piece = s[start+2:end-1]
+ piece = var[start+2:end-1]
if piece.find(":-") > 0:
varname, alt = piece.split(":-", 1)
replace = getter(varname)
@@ -79,20 +79,20 @@ def expand(s, getter):
varname = piece
replace = getter(varname)
if replace is None:
- replace = s[start:end]
+ replace = var[start:end]
else:
end = start + 2
- while end < len(s) and s[start+1:end+1].isalnum():
+ while end < len(var) and var[start+1:end+1].isalnum():
end += 1
- varname = s[start+1:end]
+ varname = var[start+1:end]
replace = getter(varname)
if replace is None:
- replace = s[start:end]
+ replace = var[start:end]
result = result + replace
pos = end
- return result + s[pos:]
+ return result + var[pos:]
class OptionDict(collections.defaultdict):
@@ -101,9 +101,9 @@ class OptionDict(collections.defaultdict):
self.section_name = section_name
super().__init__()
def __missing__(self, key):
- e = Entry(self.config(), self.section_name, key)
- self[key] = e
- return e
+ entry = Entry(self.config(), self.section_name, key)
+ self[key] = entry
+ return entry
def __getitem__(self, slice):
return super().__getitem__(slice.lower())
def __setitem__(self, slice, value):
@@ -114,9 +114,9 @@ class SectionDict(collections.defaultdict):
def __init__(self):
super().__init__()
def __missing__(self, key):
- v = OptionDict(self, key)
- self[key] = v
- return v
+ value = OptionDict(self, key)
+ self[key] = value
+ return value
def __getitem__(self, slice):
return super().__getitem__(slice.lower())
def __setitem__(self, slice, value):
@@ -133,47 +133,51 @@ class Entry:
self.config = weakref.ref(config)
def __repr__(self):
- return "<Entry section=%s, option=%s, value=%s>" % (self.section,
self.option, repr(self.value),)
+ return "<Entry section=%s, option=%s, value=%s>" \
+ % (self.section, self.option, repr(self.value),)
def __str__(self):
return self.value
def value_string(self, default=None, required=False, warn=False):
if required and self.value is None:
- raise ConfigurationError("Missing required option '%s' in section
'%s'" % (self.option.upper(), self.section.upper()))
+ raise ConfigurationError("Missing required option '%s' in section
'%s'" \
+ % (self.option.upper(),
self.section.upper()))
if self.value is None:
if warn:
if default is not None:
- logger.warn("Configuration is missing option '%s' in
section '%s', falling back to '%s'",
- self.option, self.section, default)
+ LOGGER.warn("Configuration is missing option '%s' in
section '%s',\
+ falling back to '%s'", self.option,
self.section, default)
else:
- logger.warn("Configuration ** is missing option '%s' in
section '%s'", self.option.upper(), self.section.upper())
+ LOGGER.warn("Configuration ** is missing option '%s' in
section '%s'",
+ self.option.upper(), self.section.upper())
return default
return self.value
def value_int(self, default=None, required=False, warn=False):
- v = self.value_string(default, warn, required)
- if v is None:
+ value = self.value_string(default, warn, required)
+ if value is None:
return None
try:
- return int(v)
+ return int(value)
except ValueError:
- raise ConfigurationError("Expected number for option '%s' in
section '%s'" % (self.option.upper(), self.section.upper()))
+ raise ConfigurationError("Expected number for option '%s' in
section '%s'" \
+ % (self.option.upper(),
self.section.upper()))
def _getsubst(self, key):
- x = self.config()["paths"][key].value
- if x is not None:
- return x
- x = os.environ.get(key)
- if x is not None:
- return x
+ value = self.config()["paths"][key].value
+ if value is not None:
+ return value
+ value = os.environ.get(key)
+ if value is not None:
+ return value
return None
def value_filename(self, default=None, required=False, warn=False):
- v = self.value_string(default, warn, required)
- if v is None:
+ value = self.value_string(default, warn, required)
+ if value is None:
return None
- return expand(v, lambda x: self._getsubst(x))
+ return expand(value, lambda x: self._getsubst(x))
def location(self):
if self.filename is None or self.lineno is None:
@@ -202,7 +206,7 @@ class TalerConfig:
if xdg:
filename = os.path.join(xdg, "taler.conf")
else:
- filename = os.path.expanduser("~/.config/taler.conf") # <-
what if you aren't there!?
+ filename = os.path.expanduser("~/.config/taler.conf")
if load_defaults:
cfg.load_defaults()
cfg.load_file(filename)
@@ -229,10 +233,10 @@ class TalerConfig:
prefix = tmp[0]
self.load_dir(os.path.join(prefix, "share/taler/config.d"))
return
- if taler_datadir:
- self.load_dir(os.path.join(taler_datadir, "share/taler/config.d"))
+ if TALER_DATADIR:
+ self.load_dir(os.path.join(TALER_DATADIR, "share/taler/config.d"))
return
- logger.warn("no base directory found")
+ LOGGER.warn("no base directory found")
@staticmethod
def from_env(*args, **kwargs):
@@ -247,7 +251,7 @@ class TalerConfig:
try:
files = os.listdir(dirname)
except FileNotFoundError:
- logger.warn("can't read config directory '%s'", dirname)
+ LOGGER.warn("can't read config directory '%s'", dirname)
return
for file in files:
if not file.endswith(".conf"):
@@ -263,7 +267,7 @@ class TalerConfig:
for line in file:
lineno += 1
line = line.strip()
- if len(line) == 0:
+ if line == "":
# empty line
continue
if line.startswith("#"):
@@ -271,36 +275,37 @@ class TalerConfig:
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
- kv = line.split("=", 1)
- if len(kv) != 2:
- logger.error("invalid option in line %s: %s", lineno,
repr(line))
- key = kv[0].strip()
- value = kv[1].strip()
+ pair = line.split("=", 1)
+ if len(pair) != 2:
+ 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]
- e = Entry(self.sections, current_section, key, value,
filename, lineno)
- sections[current_section][key] = e
+ entry = Entry(self.sections, current_section, key, value,
filename, lineno)
+ sections[current_section][key] = entry
except FileNotFoundError:
- logger.error("Configuration file (%s) not found", filename)
+ LOGGER.error("Configuration file (%s) not found", filename)
sys.exit(3)
def dump(self):
for section_name, section in self.sections.items():
print("[%s]" % (section.section_name,))
- for option_name, e in section.items():
- print("%s = %s # %s" % (e.option, e.value, e.location()))
+ for option_name, entry in section.items():
+ print("%s = %s # %s" % (entry.option, entry.value,
entry.location()))
def __getitem__(self, slice):
if isinstance(slice, str):
@@ -309,24 +314,27 @@ class TalerConfig:
if __name__ == "__main__":
- import sys
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')
- args = parser.parse_args()
-
- tc = TalerConfig.from_file(args.config)
-
- if args.section is not None and args.option is not None:
- if args.expand_filename:
- x = tc.value_filename(args.section, args.option)
+ 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')
+ ARGS = PARSER.parse_args()
+
+ TC = TalerConfig.from_file(ARGS.config)
+
+ if ARGS.section is not None and ARGS.option is not None:
+ if ARGS.expand_filename:
+ X = TC.value_filename(ARGS.section, ARGS.option)
else:
- x = tc.value_string(args.section, args.option)
- if x is not None:
- print(x)
+ X = TC.value_string(ARGS.section, ARGS.option)
+ if X is not None:
+ print(X)
else:
- tc.dump()
+ TC.dump()
--
To stop receiving notification emails like this one, please contact
address@hidden