@@ -8,16 +8,15 @@ import pathlib
from . import cache, loaders
HOME_PATH = pathlib.Path(os.path.expanduser('~'))
CONFFILE_SEED = """
[Historical]
base=USD
"""
def currency_code(s):
if not ((len(s) == 3) and s.isalpha()):
raise ValueError("bad currency code: {!r}".format(s))
return s.upper()
def currency_list(s):
return [currency_code(code.strip()) for code in s.split(',')]
def date_from(fmt_s):
def date_from_fmt(s):
return datetime.datetime.strptime(s, fmt_s).date()
@@ -66,12 +65,29 @@ class Configuration:
command='historical',
amount=None,
from_currency=None,
ledger=None,
)
hist_parser.add_argument(
'--base',
type=currency_code,
help="Base currency (default USD)",
'--ledger', '-L',
action='store_true',
help="Output the rate or conversion in Ledger format",
'--no-ledger',
action='store_false', dest='ledger',
help="Turn off an earlier --ledger setting",
'--signed-currency', '--sign-currency',
type=currency_code, action='append', dest='signed_currencies',
help="In Ledger output, use a sign for this currency if known. "
"Can be specified multiple times.",
'date',
type=date_from('%Y-%m-%d'),
@@ -96,9 +112,19 @@ class Configuration:
return prog_parser
def _build_conffile(self):
conffile = configparser.ConfigParser()
conffile.read_string(CONFFILE_SEED)
return conffile
return configparser.ConfigParser()
def _read_from_conffile(self, argname, sectionname, fallback, convert_to=None,
confname=None, getter='get', unset=None):
if getattr(self.args, argname) is not unset:
return
elif confname is None:
confname = argname
get_method = getattr(self.conffile, getter)
value = get_method(sectionname, confname, fallback=fallback)
if convert_to is not None:
value = self._convert_or_error(convert_to, value, confname)
setattr(self.args, argname, value)
def _convert_or_error(self, argtype, s_value, argname=None, typename=None):
try:
@@ -114,8 +140,9 @@ class Configuration:
self.error(': '.join(errmsg))
def _post_hook_historical(self):
if self.args.base is None:
self.args.base = self.conffile.get('Historical', 'base')
self._read_from_conffile('base', 'Historical', 'USD', currency_code)
self._read_from_conffile('signed_currencies', 'Historical', self.args.base, currency_list)
self._read_from_conffile('ledger', 'Historical', False, getter='getboolean')
self.args.to_currency = self.args.base
if self.args.word4 and (self.args.word3.lower() in self.PREPOSITIONS):
self.args.word3 = self.args.word4