GitBucket
4.21.2
Toggle navigation
Snippets
Sign in
Files
Branches
1
Releases
Issues
1
Pull requests
Labels
Priorities
Milestones
Wiki
Forks
nigel.stanger
/
Handbook
Browse code
Converted load_config() into Configuration class
master
1 parent
317f558
commit
e4092edb1d11235d844012227c4b0d633fe4882d
Nigel Stanger
authored
on 26 Nov 2019
Patch
Showing
3 changed files
calendar/teachingdates/app.py
calendar/teachingdates/config/__init__.py
calendar/teachingdates/config/config.py
Ignore Space
Show notes
View
calendar/teachingdates/app.py
import argparse import copy import pathlib import sys from teachingdates import PROG import teachingdates.calendars as calendars import teachingdates.config as configuration def run(): args = configuration.parse_command_line() if args.debug: print("{prog}: debug: args: {a}".format(prog=PROG, a=args)) try: config = configuration.Configuration(args) if args.debug: print("{prog}: debug: period config: {c}".format( prog=PROG, c=config.get_period_config())) print("{prog}: debug: paper config: {c}".format( prog=PROG, c=config.get_paper_config())) cal = calendars.TeachingCalendar( config.year, config.period, config.paper, config.get_period_config(), config.get_paper_config()) print("Period = {p}".format(p=args.period)) print(cal.calendar()) print(cal.lecture_dates()) except configuration.LectureStyleError as e: print("{prog}: error: 'lecture' style was requested but " "{c} contains no papers for {t}.".format( prog=PROG, c=args.config, t=args.period)) except configuration.PaperError as e: print("{prog}: error: no entry in {c} for paper {p} ({t}).".format( prog=PROG, c=args.config, p=args.paper, t=args.period)) except configuration.PeriodError as e: print("{prog}: error: no entry in {c} for teaching " "period {p}.".format( prog=PROG, c=args.config_file, p=args.period)) except KeyError as e: print("{prog}: error: teaching period {p} in {c} is missing " "required key {k}.".format( prog=PROG, p=args.period, c=args.config, k=e))
import argparse import copy import pathlib import sys from teachingdates import PROG import teachingdates.calendars as calendars import teachingdates.config as config def run(): args = config.parse_command_line() if args.debug: print("{prog}: debug: args: {a}".format(prog=PROG, a=args)) try: period_config, paper_config = config.parse_config(args.config, args) if args.debug: print("{prog}: debug: period config: {c}".format( prog=PROG, c=period_config)) print("{prog}: debug: paper config: {c}".format( prog=PROG, c=paper_config)) # priority: year on command line (defaults to current year), # year in config if period_config: args.year = ( args.config["year"] if "year" in args.config.keys() else args.year) cal = calendars.TeachingCalendar( args.year, args.period, args.paper, period_config, paper_config) print("Period = {p}".format(p=args.period)) print(cal.calendar()) print(cal.lecture_dates()) except config.LectureStyleError as e: print("{prog}: error: 'lecture' style was requested but " "{c} contains no papers for {t}.".format( prog=PROG, c=args.config, t=args.period)) except config.PaperError as e: print("{prog}: error: no entry in {c} for paper {p} ({t}).".format( prog=PROG, c=args.config, p=args.paper, t=args.period)) except config.PeriodError as e: print("{prog}: error: no entry in {c} for teaching " "period {p}.".format( prog=PROG, c=args.config_file, p=args.period)) except KeyError as e: print("{prog}: error: teaching period {p} in {c} is missing " "required key {k}.".format( prog=PROG, p=args.period, c=args.config, k=e))
Ignore Space
Show notes
View
calendar/teachingdates/config/__init__.py
from .cli import parse_command_line from .config import Configuration, load_config from .errors import LectureStyleError, PaperError, PeriodError
from .cli import parse_command_line from .config import load_config, parse_config from .errors import LectureStyleError, PaperError, PeriodError
Ignore Space
Show notes
View
calendar/teachingdates/config/config.py
import datetime import importlib.resources as pkg_resources from pathlib import Path from shutil import copyfile import yaml from teachingdates import PROG from .errors import LectureStyleError, PaperError, PeriodError CONFIG_FILENAME = "config.yml" CONFIG_DIR = Path.home().joinpath(".config", PROG) CONFIG_FILE = CONFIG_DIR.joinpath(CONFIG_FILENAME) class Configuration(object): """Validate and structure the configuration for easy access. Includes methods to return the period configuration and the paper configuration, as applicable. (Yes, the period configuration includes the paper configuration, but it may also include other papers, so it's more convenient to return these separately.) The configuration file will normally contain specifications for several teaching periods and papers. We don't need all of this: usually we're only interested in one teaching period and one paper (if relevant). """ style = None period = None paper = None year = None config = None def __init__(self, args): self.config = args.config self.style = args.style self.period = args.period self.paper = args.paper # priority: year on command line (defaults to current year), # year in config self.year = ( args.config["year"] if "year" in args.config.keys() else args.year) period_config = paper_config = None if self.style != "iso": if self.period not in self.config.keys(): raise PeriodError() period_config = self.config[self.period] # raises KeyError if source key is missing period_config["name"] and period_config["weeks"] # papers are irrelevant in "calendar" style if self.style == "lecture": if "papers" in period_config.keys(): if self.paper in period_config["papers"].keys(): paper_config = period_config["papers"][self.paper] # we expect at least a "lectures" entry paper_config["lectures"] else: raise PaperError() else: raise LectureStyleError() def get_period_config(self, period=None): period = self.period if period is None else period if period in self.config.keys(): return self.config[period] else: return None def get_paper_config(self, period=None, paper=None): paper = self.paper if paper is None else paper period_config = self.get_period_config(period=period) if (period_config and "papers" in period_config.keys() and paper in period_config["papers"].keys()): return period_config["papers"][paper] else: return None def load_config(file=None): """Load a 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
import importlib.resources as pkg_resources from pathlib import Path from shutil import copyfile import yaml from teachingdates import PROG from .errors import LectureStyleError, PaperError, PeriodError CONFIG_FILENAME = "config.yml" CONFIG_DIR = Path.home().joinpath(".config", PROG) CONFIG_FILE = CONFIG_DIR.joinpath(CONFIG_FILENAME) def load_config(file=None): """Load a 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_config(config, args): """Validate and filter the top-level configuration. Returns separate references to the period configuration and the paper configuration, as applicable. (Yes, the period configuration includes the paper configuration, but it may also include other papers, so it's more convenient to return a separate reference for the specified paper.) The configuration file will normally contain specifications for several teaching periods and papers. We don't need all of this: usually we're only interested in one teaching period and one paper (if relevant). """ period_config = paper_config = None # this is all irrelevant if we're going ISO style if args.style != "iso": if args.period not in config.keys(): raise PeriodError() period_config = config[args.period] # raises KeyError if source key is missing period_config["name"] and period_config["weeks"] # papers are irrelevant in "calendar" style if args.style == "lecture": if "papers" in period_config.keys(): if args.paper in period_config["papers"].keys(): paper_config = period_config["papers"][args.paper] # we expect at least a "lectures" entry paper_config["lectures"] else: raise PaperError() else: raise LectureStyleError() return period_config, paper_config
Show line notes below