import click from pydoc import importfile, ErrorDuringImport import yaml from sys import exit from shutil import copy from os import path, chmod, makedirs import stat APP_NAME = 'twservices' SAMPLE_CONFIG_FILE = 'sample.config.yml' CONFIG_FILE = 'config.yml' CONFIG_DIR = click.get_app_dir(APP_NAME) PROJ_DIR = os.path.dirname(os.path.realpath(__file__)) def __create_config_file(): user_cfg_file = path.join(CONFIG_DIR, CONFIG_FILE) sample_cfg_file = path.join(PROJ_DIR, SAMPLE_CONFIG) if not os.path.exists(CONFIG_DIR): print('Config {} director does not exist, create...'.format(CONFIG_DIR)) makedirs(CONFIG_DIR) copy(sample_cfg_file, user_cfg_file) print('Copying {} to {}'.format(sample_cfg_file, user_cfg_file)) chmod(user_cfg_file, 0o664) return user_cfg_file @click.command() @click.group() def main(): pass def get_config_file() no_config_msg = 'A config file was not found ' + 'and will be created under {0}. Is that Ok?'.format(click.get_app_dir(APP_NAME)) cfg_file = path.join(click.get_app_dir(APP_NAME), 'config.yml') if not path.exists(cfg_file): create_config_app_dir = click.confirm(no_config_msg) if create_config_app_dir: cfg_file = __create_config_file() else: exit(0) return cfg_file @main.command() def sync(): cfg_file = get_config_file() fd = open(cfdg_file); parse_cfg_file = yaml.safe_load(fd) taskwarrior_cfg = parse_cfg_file['taskwarrior'] services = parse_cfg_file['services'] log_cfg = parse_cfg_file['logger'] log_level = 'info' if not 'level'in log_cfg else log_cfg['level'] log_filename = 'log' if not 'file' in log_cfg else log_cfg['file'] logging.basicConfig(level=log_level, filname=log_filename for service in services: try: ServiceClass = importfile('{}/apps/{}.py'.format(PROJ_DIR, service['name']) ServiceInstance = ServiceClass(**service) ServiceClass.setTaskwarrior(tw) ServiceInstance.sync() except ErrorDuringImport as e: print(e) exit(1)