diff --git a/oxrlib/config.py b/oxrlib/config.py index cdb757462aad75988b1925a20013c84d6a3631b6..4c4877d5aa411e8b271feb27a4d59454c81b14f8 100644 --- a/oxrlib/config.py +++ b/oxrlib/config.py @@ -5,6 +5,9 @@ import decimal import os.path import pathlib +import babel +import babel.numbers + from . import cache, loaders HOME_PATH = pathlib.Path(os.path.expanduser('~')) @@ -20,7 +23,8 @@ def currency_list(s): class Configuration: DATE_SEPS = frozenset('.-/ ') DEFAULT_CONFIG_PATH = pathlib.Path(HOME_PATH, '.config', 'oxrlib.ini') - NO_DENOMINATION = object() + LOCALE = babel.core.Locale.default() + SENTINEL = object() PREPOSITIONS = frozenset(['in', 'to', 'into']) TODAY = datetime.date.today() @@ -106,7 +110,7 @@ class Configuration: ) hist_parser.add_argument( '--no-denomination', - dest='denomination', action='store_const', const=self.NO_DENOMINATION, + dest='denomination', action='store_const', const=self.SENTINEL, help="Turn off an earlier --denomination setting", ) hist_parser.add_argument( @@ -134,7 +138,7 @@ class Configuration: hist_parser.add_argument( 'word3', nargs='?', metavar='second code', help="Convert or show rates to this currency, in three-letter code format. " - "If not specified, defaults to the base currency.", + "If not specified, defaults to the user's preferred currency.", ) hist_parser.add_argument('word4', nargs='?', help=argparse.SUPPRESS) @@ -170,20 +174,27 @@ class Configuration: errmsg.append(repr(s_value)) self.error(': '.join(errmsg)) + def _user_currency(self, default=SENTINEL): + try: + return babel.numbers.get_territory_currencies( + self.LOCALE.territory, start_date=self.TODAY)[0] + except IndexError: + return default + def _post_hook_historical(self): year = self.args.date.year if year < 100: # Don't let the user specify ambiguous dates. self.error("historical data not available from year {}".format(year)) self._read_from_conffile('base', 'Historical', 'USD', currency_code) - if self.args.denomination is self.NO_DENOMINATION: + if self.args.denomination is self.SENTINEL: self.args.denomination = None else: self._read_from_conffile('denomination', 'Historical', None, currency_code) - self._read_from_conffile('signed_currencies', 'Historical', self.args.base, + pref_currency = self.args.denomination or self._user_currency(self.args.base) + self._read_from_conffile('signed_currencies', 'Historical', pref_currency, currency_list, convert_fallback=True) self._read_from_conffile('ledger', 'Historical', False, getter='getboolean') - self.args.to_currency = self.args.base raw_words = iter(getattr(self.args, 'word' + c) for c in '1234') words = iter(word for word in raw_words if word is not None) try: @@ -202,7 +213,7 @@ class Configuration: next_word = next(words, next_word) self.args.to_currency = self._convert_or_error(currency_code, next_word) except StopIteration: - pass + self.args.to_currency = pref_currency def _build_cache_loader(self): kwargs = dict(self.conffile.items('Cache'))