|
| 1 | +import logging |
| 2 | +import yaml |
| 3 | + |
| 4 | +from collections import UserDict |
| 5 | + |
| 6 | +from assigner.config.versions import upgrade, validate, ValidationError |
| 7 | + |
| 8 | +class DuplicateUserError(Exception): |
| 9 | + pass |
| 10 | + |
| 11 | +def config_context(func): |
| 12 | + def wrapper(cmdargs, *args): |
| 13 | + with Config(cmdargs.config) as conf: |
| 14 | + return func(conf, cmdargs, *args) |
| 15 | + return wrapper |
| 16 | + |
| 17 | + |
| 18 | +class Config(UserDict): |
| 19 | + """Context manager for config; automatically saves changes""" |
| 20 | + |
| 21 | + def __init__(self, filename): |
| 22 | + super().__init__() |
| 23 | + self._filename = filename |
| 24 | + |
| 25 | + try: |
| 26 | + with open(filename) as f: |
| 27 | + self.data = yaml.safe_load(f) |
| 28 | + except FileNotFoundError: |
| 29 | + pass # Just make an empty config; create on __exit__() |
| 30 | + |
| 31 | + try: |
| 32 | + self.data = upgrade(self.data) |
| 33 | + validate(self.data) |
| 34 | + except ValidationError as e: |
| 35 | + logging.warning("Your configuration is not valid: %s", e.message) |
| 36 | + |
| 37 | + def __enter__(self): |
| 38 | + return self |
| 39 | + |
| 40 | + def __exit__(self, *args): |
| 41 | + with open(self._filename, "w") as f: |
| 42 | + yaml.dump(self.data, f, indent=2, default_flow_style=False) |
| 43 | + |
| 44 | + return False # propagate exceptions from the calling context |
| 45 | + |
| 46 | + def __getattr__(self, key): |
| 47 | + attr = getattr(super(Config, self), key, None) |
| 48 | + if attr: |
| 49 | + return attr |
| 50 | + # Keys contained dashes can be called using an underscore |
| 51 | + key = key.replace("_", "-") |
| 52 | + |
| 53 | + # Fill in a blank roster if needed |
| 54 | + if key == "roster" and self.data.get(key, None) is None: |
| 55 | + self.data[key] = [] |
| 56 | + |
| 57 | + return self.data[key] |
0 commit comments