diff --git a/calendar/teachingdates/config/cli.py b/calendar/teachingdates/config/cli.py index d31072f..86d1fa8 100644 --- a/calendar/teachingdates/config/cli.py +++ b/calendar/teachingdates/config/cli.py @@ -1,10 +1,45 @@ import argparse import datetime import importlib.resources as pkg_resources +from os import mkdir +from pathlib import Path +from shutil import copyfile + import yaml from teachingdates import PROG +CONFIG_FILENAME = "config.yml" +CONFIG_DIR = Path.home().joinpath(".config", PROG) +CONFIG_FILE = CONFIG_DIR.joinpath(CONFIG_FILENAME) + + +def load_config(file=None): + """Load the configuration file. + + If no file is specified, try the default configuration in + ~/.config. If that doesn't exist, copy the default configuration + from teachingdates.config. + """ + cfg = None + if not file: + file = CONFIG_FILE + if not CONFIG_FILE.exists(): + CONFIG_DIR.mkdir(exist_ok=True) + configmgr = pkg_resources.path( + "teachingdates.config", CONFIG_FILENAME) + with configmgr as f: + copyfile(f, CONFIG_FILE) + print("{prog}: created new configuration file at " + "'{f}'".format(prog=PROG, f=str(CONFIG_FILE))) + try: + with open(file) as f: + cfg = yaml.safe_load(f.read()) + except FileNotFoundError as e: + print("{prog}: error: no such file '{f}'".format(prog=PROG, f=file)) + return file, cfg + + def parse_command_line(): """Parse command-line arguments. @@ -79,19 +114,16 @@ args.style = style_map[args.style] # Load the default config if none is explicitly specified. - if not args.config_file: - args.config_file = "default.yml" - args.config = yaml.safe_load( - pkg_resources.read_text("teachingdates.config", args.config_file)) - else: - with open(args.config_file) as cfg: - args.config = yaml.safe_load(cfg.read()) + args.config_file, args.config = load_config(file=args.config_file) + if not args.config: + parser.exit(2, "{prog}: error: failed to load configuration " + "from '{f}'\n".format(prog=PROG, f=args.config_file)) if args.style == "calendar": # --paper is irrelevant if args.paper: print("{prog}: warning: --paper/-p is ignored for " - "'calendar' style\n".format(prog=PROG)) + "'calendar' style".format(prog=PROG)) # --teaching-period is required if not args.period: parser.exit(2, "{prog}: error: --teaching-period/-t " @@ -102,7 +134,7 @@ if args.paper or args.period: print("{prog}: warning: --paper/-p and " "--teaching-period/-t are ignored for 'iso' " - "style\n".format(prog=PROG)) + "style".format(prog=PROG)) elif args.style == "lecture": # both --paper and --teaching-period are required