From 39923a0c5f4db627628cf51b630b3532960a95ae Mon Sep 17 00:00:00 2001 From: redxef Date: Thu, 13 Oct 2022 11:27:21 +0200 Subject: [PATCH] Change config loading method. --- main.py | 68 +++++++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 49 insertions(+), 19 deletions(-) diff --git a/main.py b/main.py index 488901b..9e803ff 100755 --- a/main.py +++ b/main.py @@ -19,10 +19,11 @@ logger = logging.getLogger(f'wp_cal') class BaseConfig(dict): - def __init__(self, file, defaults, *args, **kwargs): + def __init__(self, file, defaults, overrides, *args, **kwargs): self._ex = None self.file = file self.defaults = defaults + self.overrides = overrides super().__init__(*args, **kwargs) try: self._load() @@ -55,6 +56,12 @@ class BaseConfig(dict): repl = value if (i == len(keylist) - 1) else {} d[key] = d.get(key, repl) d = d[key] + for keylist, value in self.overrides: + d = self + for key in keylist[:-1]: + d[key] = d.get(key, {}) + d = d[key] + d[keylist[-1]] = value def _save(self): with open(self.file, 'w') as fp: @@ -88,7 +95,7 @@ class Config(BaseConfig): .range: the range in the format , where n are digits and u is the unit; valid units: 'smhdw' <-> seconds minutes hours days weeks """ - def __init__(self, file, defaults, *args, **kwargs): + def __init__(self, file, defaults, overrides, converters, *args, **kwargs): defaults += [ ('google.calendar_id', '#TODO insert google calendar id'), ('google.credentials', {}), @@ -99,9 +106,28 @@ class Config(BaseConfig): ('wordpress.calendar.translations', {'en': '#TODO insert english translation'}), ('wordpress.credentials.user', '#TODO insert wordpress username'), ('wordpress.credentials.password', '#TODO insert wordpress password'), + ('logging.level', ':WARNING,wp_cal:INFO'), + ('range', '365d'), ] defaults = [(x[0].split('.'), x[1]) for x in defaults] - super().__init__(file, defaults, *args, **kwargs) + overrides = [(x[0].split('.'), x[1]) for x in overrides] + self.converters = converters + super().__init__(file, defaults, overrides, *args, **kwargs) + + def value(self, k): + if isinstance(k, str): + sel = k.split('.') + elif isinstance(k, list): + sel = k + k = '.'.join(k) + else: + raise TypeError('invalid type for parameter k') + v = self + for s in sel: + v = v[s] + if k in self.converters: + return self.converters[k](v) + return v def range_str_to_timedelta(value): valid_units = 'smhdw' @@ -150,15 +176,20 @@ def set_logging_level(level: str): logging.getLogger(module).setLevel(level) @click.command() -@click.option('--level', '-l', envvar='WP_CAL_LEVEL', default=':WARNING,wp_cal:INFO', help='The log level for the application') @click.option('--config', '-c', envvar='WP_CAL_CONFIG', default='-', help='The configuration file') @click.option('--dryrun', '-d', envvar='WP_CAL_DRYRUN', is_flag=True, help="Don't actually post any data, just show it") -@click.option('--range', '-r', envvar='WP_CAL_RANGE', default='365d', help='The time range from start to start + range to synchronize events') -def main(level, config, dryrun, range): +@click.option('--level', '-l', envvar='WP_CAL_LEVEL', default=None, help='The log level for the application') +@click.option('--range', '-r', envvar='WP_CAL_RANGE', default=None, help='The time range from start to start + range to synchronize events') +def main(config, dryrun, level, range): init_logging() set_logging_level(level) - config = Config(config, [('logging.level', level), ('range', range)]) + config_overrides = [('logging.level', level), ('range', range)] + config_overrides = [x for x in config_overrides if x[1] is not None] + converters = { + 'range': range_str_to_timedelta, + } + config = Config(config, [], config_overrides, converters) if config.exception(): logger.info('config not found, trying to generate template') try: @@ -169,25 +200,24 @@ def main(level, config, dryrun, range): logger.info('generated config at "%s"', config.file) return - set_logging_level(config['logging']['level']) - config['range'] = range_str_to_timedelta(config['range']) + set_logging_level(str(config.value('logging.level'))) g = Google( - config['google']['calendar_id'], - credentials=config['google']['credentials'], - token_file=config['google']['token_file'], + config.value('google.calendar_id'), + credentials=config.value('google.credentials'), + token_file=config.value('google.token_file'), ) w = Wordpress( - config['wordpress']['url'], + config.value('wordpress.url'), calendar_metadata=CalendarMetadata( - id=config['wordpress']['calendar']['id'], - name=config['wordpress']['calendar']['name'], - translations=config['wordpress']['calendar']['translations'], + id=config.value('wordpress.calendar.id'), + name=config.value('wordpress.calendar.name'), + translations=config.value('wordpress.calendar.translations'), ), - credentials=config['wordpress']['credentials'], + credentials=config.value('wordpress.credentials'), ) g.login() - events = g.get_events(until=config['range']) + events = g.get_events(until=config.value('range')) logger.info("syncing %d events", len(events)) if not w.login(): logger.info('failed to login to wordpress') @@ -195,7 +225,7 @@ def main(level, config, dryrun, range): if dryrun: logger.info("dryrun; would post events: %s", events) else: - if not w.post_events(events, until=config['range']): + if not w.post_events(events, until=config.value('range')): logger.info('failed to post event data') return 1 logger.info("done")