Changeset - c8000a8a747c
[Not reviewed]
0 1 0
Brett Smith - 7 years ago 2017-05-19 14:21:33
brettcsmith@brettcsmith.org
config: Print usage if no subcommand is given.
1 file changed with 3 insertions and 0 deletions:
0 comments (0 inline, 0 general)
oxrlib/config.py
Show inline comments
...
 
@@ -11,64 +11,67 @@ HOME_PATH = pathlib.Path(os.path.expanduser('~'))
 

	
 
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()
 
    return date_from_fmt
 

	
 
class Configuration:
 
    DEFAULT_CONFIG_PATH = pathlib.Path(HOME_PATH, '.config', 'oxrlib.ini')
 
    PREPOSITIONS = frozenset(['in', 'to', 'into'])
 

	
 
    def __init__(self, arglist):
 
        argparser = self._build_argparser()
 
        self.error = argparser.error
 
        self.args = argparser.parse_args(arglist)
 

	
 
        if self.args.config_file is None:
 
            self.args.config_file = [self.DEFAULT_CONFIG_PATH]
 
        self.conffile = self._build_conffile()
 
        conffile_paths = [path.as_posix() for path in self.args.config_file]
 
        read_files = self.conffile.read(conffile_paths)
 
        for expected_path, read_path in zip(conffile_paths, read_files):
 
            if read_path != expected_path:
 
                self.error("failed to read configuration file {!r}".format(expected_path))
 

	
 
        if not hasattr(self.args, 'command'):
 
            argparser.print_help()
 
            exit(2)
 
        try:
 
            post_hook = getattr(self, '_post_hook_' + self.args.command)
 
        except AttributeError:
 
            pass
 
        else:
 
            post_hook()
 

	
 
    def _build_argparser(self):
 
        prog_parser = argparse.ArgumentParser()
 
        prog_parser.add_argument(
 
            '--config-file', '-c',
 
            action='append', type=pathlib.Path,
 
            help="Path of a configuration file to read",
 
        )
 
        subparsers = prog_parser.add_subparsers()
 

	
 
        hist_parser = subparsers.add_parser(
 
            'historical', aliases=['hist'],
 
            usage='%(prog)s YYYY-MM-DD [[amount] code] [[in] code]',
 
            help="Show a currency conversion or rate from a past date",
 
        )
 
        hist_parser.set_defaults(
 
            command='historical',
 
            amount=None,
 
            from_currency=None,
 
            ledger=None,
 
        )
 
        hist_parser.add_argument(
 
            '--base',
 
            metavar='CODE', type=currency_code,
 
            help="Base currency (default USD)",
 
        )
0 comments (0 inline, 0 general)