summaryrefslogtreecommitdiff
path: root/src/worklog
blob: 39266801397fc58906e9f5058efda75ce1c3ba28 (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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#!/opt/homebrew/bin/python3
"""
MAIN FILE FOR WORKLOGGER
author: Wacky404 <wacky404@dev.com>
"""

import json
import sys
import os
import os.path as osp
import logging
import src.utils.paths_util_worklogger as pu
from src.funcs_worklogger import configure, add_log, combine_log
from src.args_worklogger import parser
from pathlib import Path
from src.util.log_util_worklogger import logger, setup_logging
from typing import Optional


SAVEPATH: Path | str
BACKUPPATH: Path | str

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

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

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


dotfile: list | None = None
# this will change once this moves to another directory; depends on install path
if osp.exists(osp.join(os.getcwd(), os.pardir)):
    dotfile = list(Path(osp.join(osp.expanduser('~'), ".config")).glob(
        '**/*.workloggerconfig.json'))
    logger.debug(f"Found dotfile(s): {dotfile}")
    if len(dotfile) > 1:
        logger.error(
            f"You have {len(dotfile)} config files, using defaults...")
        dotfile = None
    elif len(dotfile) == 1:
        logger.debug(f"Using user config file in {str(dotfile[0])}")
    elif len(dotfile) == 0:
        logger.debug(f"Could not find your config file, using defaults...")
        dotfile = None


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))
            logger.error(
                "There was an error loading your config. Using defaults.")

if settings is not None:
    SAVEPATH = Path(osp.join(osp.expanduser("~"), settings['savepath']))
    BACKUPPATH = Path(osp.join(osp.expanduser("~"), settings['backuppath']))
    try:
        numeric_loglevel_settings = getattr(
            logging, str(settings['loglvl']).upper())
        setup_logging(numeric_loglevel_settings)
    except Exception as e:
        logger.exception(str(e))

    dir_list: list = [d for d in [
        SAVEPATH, BACKUPPATH] if not osp.exists(d)]
    if len(dir_list) > 0:
        configure(dir_list=dir_list)
else:
    SAVEPATH = Path(osp.join(osp.expanduser("~"), "Documents"))
    BACKUPPATH = Path(osp.join(osp.expanduser("~"), "Documents", "worklogger"))


if 'extension' in vars(args).keys():
    combine_log(target_job=args.job, specified_ext=formats[str(args.extension).upper(
    )], delete=args.delete, savepath=SAVEPATH, backuppath=BACKUPPATH)
    sys.exit()


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:
        filepath = osp.join(SAVEPATH, f"{str(args.job).upper()}{formats[str(
            settings['fileformat']).upper()]}")
        filepath_backup = osp.join(BACKUPPATH, f"{str(args.job).upper()}{formats[str(
            settings['fileformat']).upper()]}")
        for _path in [filepath, filepath_backup]:
            if not osp.exists(_path):
                with open(_path, 'x'):
                    pass
    except Exception as e:
        logger.exception(str(e))

else:
    try:
        filepath = osp.join(SAVEPATH, f"{str(args.job).upper()}.txt")
        filepath_backup = osp.join(BACKUPPATH, f"{str(args.job).upper()}.txt")
        for _path in [filepath, filepath_backup]:
            if not osp.exists(_path):
                with open(_path, '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)