summaryrefslogtreecommitdiff
path: root/src/worklog.py
blob: 56ae46a883a8929c8472412f3c47831c225356a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
from pathlib import Path
from utils.log_util import logger, setup_logging

from args_worklogger import parser
from funcs_worklogger import configure, add_log, arg_convert
from utils import paths_util as pu
import logging

import os.path as osp
import os
import sys
import json
from datetime import timezone
import datetime


SAVEPATH: Path | str
BACKUPPATH: Path | str
CONFIGPATH: Path | str

formats: dict = {
    "TEXT": '.txt',
    "JSON": '.json',
    "CSV": '.csv'
}

# creates a NameSpace of arguments that were made
args = parser.parse_args()

if args.configure:
    configure(dir_list=None)
    logger.info("Configuration completed.")
    sys.exit()

numeric_loglevel = getattr(logging, str(args.log).upper())
if isinstance(numeric_loglevel, int):
    setup_logging(numeric_loglevel)
else:
    setup_logging()


dotfile: list | None = None
if osp.exists(osp.join(os.getcwd(), os.pardir)):
    dotfile = list(Path(osp.join(os.getcwd(), os.pardir)).glob(
        '**/*.workloggerconfig.json'))
    if len(dotfile) > 1:
        logger.error(
            f"You have {len(dotfile)} config files, using defaults...")
        dotfile = None
    else:
        logger.debug(f"Using user config file in {str(dotfile[0])}")

settings: dict | None = None
if dotfile is not None:
    with open(dotfile[0], 'r') as fd:
        try:
            settings = json.load(fd)
        except Exception as e:
            logger.exception(str(e))
            if args.verbose:
                print("There was an error loading your config.")
                print("Using defaults")

if settings is not None:
    SAVEPATH = Path(osp.join(osp.expanduser("~"), settings['savepath']))
    BACKUPPATH = Path(osp.join(osp.expanduser("~"), settings['backuppath']))
    CONFIGPATH = Path(osp.join(osp.expanduser("~"), settings['configpath']))
    numeric_loglevel_settings = getattr(
        logging, str(settings['loglvl']).upper())
    setup_logging(numeric_loglevel_settings)
    dir_list: list = [d for d in [
        SAVEPATH, BACKUPPATH, CONFIGPATH] if not osp.exists(d)]
    if len(dir_list) > 0:
        configure(dir_list=dir_list)


jname_proj: dict[str, dict] = {}
if settings is not None:
    for j in settings['jobs']:
        jname_proj[str(j['name']).upper()] = j['projects'][0]
    logger.debug(f"{jname_proj}")

    for name, projs in jname_proj.items():
        projs_new: dict[str, str] = {}
        for key, proj in projs.items():
            projs_new[str(key).upper()] = proj
        projs = projs_new

        jname_proj[name] = projs
    logger.debug(f"{jname_proj}")

try:
    for name in jname_proj.keys():
        filepath = osp.join(SAVEPATH, f"{name}.txt")
        filepath_backup = osp.join(BACKUPPATH, f"{name}.txt")
        if not osp.exists(filepath):
            with open(filepath, 'x'):
                pass
        if not osp.exists(filepath_backup):
            with open(filepath_backup, 'x'):
                pass
except Exception as e:
    logger.exception(str(e))

if settings is not None:
    add_log(file_format=formats[str(
        settings['fileformat']).upper()], proj_settings=jname_proj, savepath=SAVEPATH, backuppath=BACKUPPATH, job=args.job, proj=args.project,
        loc=args.location, time=args.time, start=args.start, end=args.end, message=args.message)
else:
    add_log(file_format=None, proj_settings=None,
            savepath=SAVEPATH, backuppath=BACKUPPATH, job=args.job, proj=args.project,
            loc=args.location, time=args.time, start=args.start, end=args.end, message=args.message)