~nhanb/mcross

ref: bd7d6dec5c9bd8c9f1f08ac64f33c0eff34f8163 mcross/src/mcross/conf.py -rw-r--r-- 1.9 KiB
bd7d6decBùi Thành Nhân satisfy black + isort 1 year, 1 month ago
                                                                                
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
import argparse
import os
from collections import namedtuple
from pathlib import Path

import toml
from appdirs import user_config_dir

CONFIG_DIR = Path(user_config_dir("mcross", False))
CONFIG_FILE = CONFIG_DIR / "mcross.toml"

_conf = None

ConfDef = namedtuple("ConfDef", ["name", "short_name", "type", "default"])
# argparse's add_argument() will ensure name/short_name uniqueness for free
conf_definitions = [
    ConfDef("text-font", "f", str, "Source Serif Pro"),
    ConfDef("mono-font", "m", str, "Ubuntu Mono"),
    ConfDef("background-color", "b", str, "#fff8dc"),
    ConfDef("text-color", "t", str, "black"),
    ConfDef("link-color", "l", str, "brown"),
    ConfDef("list-item-color", "i", str, "#044604"),
]


def init():
    default_conf = load_default_conf()
    file_conf = load_conf_file()
    cli_conf = parse_conf_args()

    global _conf
    _conf = {**default_conf, **file_conf, **cli_conf}
    return _conf


def load_default_conf():
    return {confdef.name: confdef.default for confdef in conf_definitions}


def load_conf_file():
    if not CONFIG_DIR.is_dir():
        os.mkdir(CONFIG_DIR)

    if not CONFIG_FILE.is_file():
        return {}

    try:
        data = toml.load(CONFIG_FILE)
        return {
            confdef.name: data[confdef.name]
            for confdef in conf_definitions
            if confdef.name in data
        }
    except Exception as e:
        print("Unexpected error reading config file:", str(e))
        return {}


def parse_conf_args():
    argparser = argparse.ArgumentParser()
    for confdef in conf_definitions:
        argparser.add_argument(
            f"-{confdef.short_name}",
            f"--{confdef.name}",
            type=confdef.type,
        )
    args = argparser.parse_args()
    return {key.replace("_", "-"): val for key, val in vars(args).items() if val}


def get(key):
    return _conf[key]


if __name__ == "__main__":
    init()
    import pprint

    print("Final conf:")
    pprint.pprint(_conf)