taskwarrior-grocy/cli.py

90 lines
2.8 KiB
Python
Raw Normal View History

import click
from pkg_resources import iter_entry_points
import yaml
from sys import exit
from shutil import copy
from os import path, chmod, makedirs
from taskw import TaskWarriorShellout
import logging
log = logging.getLogger(__name__)
APP_NAME = 'twservices'
SAMPLE_CONFIG_FILE = 'sample.config.yml'
CONFIG_FILE = 'config.yml'
CONFIG_DIR = click.get_app_dir(APP_NAME)
PROJ_DIR = path.join(path.dirname(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_FILE)
if not 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.group()
def main():
pass
def get_config_file():
no_config_msg = 'A config file was not found'
no_config_msg+= ' and will be created under {}. Is that Ok?'
no_config_msg = no_config_msg.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(cfg_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 'level' not in log_cfg else log_cfg['level']
log_filename = 'log' if 'file'not in log_cfg else log_cfg['file']
logging.basicConfig(level=log_level, filename=log_filename)
for service in services:
try:
entry_service_point = iter_entry_points(group='twservices.apps', name=service['name'])
entry_service_point = next(entry_service_point)
except StopIteration as e:
log.error(e)
log.error('Could not import %s service', services['name'])
try:
ServiceClass = entry_service_point.load()
ServiceInstance = ServiceClass(**service)
udas = ServiceInstance.get_udas()
tw = TaskWarriorShellout(
config_filename=taskwarrior_cfg['rc'],
config_overrides=udas,
marshal=True,
)
ServiceInstance.set_taskwarrior(tw)
ServiceInstance.sync()
except BaseException as e:
# TODO: Need to handle base exceptions better
# See if you can print stacktrace
log.exception('Could not sync %s', e)
print(e.stderr)
exit(1)