aboutsummaryrefslogtreecommitdiff
path: root/utils/config.py
blob: 05c1f9dde4ee72368253e1a07468c77967f63478 (plain) (blame)
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
# Chris Xiong 2024
# License: Expat (MIT)

import os
from os import path

def stripped_str(x): return str(x).strip()

def s2bool(x): return str(x).strip() in ["True", "true", "TRUE"]

# "CONFIG_ITEM_NAME": (default value, parse function)
CONFIG_ITEMS = {
    "LOCAL_DATA_ROOT": ("", stripped_str),
    # e.g. https://chrisoft.org/notekins/
    "SERVED_DATA_ROOT": ("", stripped_str),
    # e.g. chrisoft@10.24.1.1:/home/chrisoft/notedir/
    "SYNC_TARGET": ("", stripped_str),
    "POSTS_PER_PAGE": (20, int),
    "THUMBNAIL_DIM": (1280, int),
    "DISPLAY_TIMEZONE": ("UTC", stripped_str),   # only used by backend
    # atom generator stuff
    "ATOM_ENABLED": (False, s2bool),
    "VERSION_STRING": ("1.0", stripped_str),
    "ATOM_TITLE": ("", stripped_str),
    "ATOM_ROOT": ("", stripped_str),
    "ATOM_SUBTITLE": ("", stripped_str),
    "ATOM_ICON": ("", stripped_str),
    "ATOM_AUTHOR": ("", stripped_str),
    "ATOM_NPOSTS": (20, int)
}

class config:
    def __init__(self):
        self.d = dict([(name, prop[0]) for name, prop in CONFIG_ITEMS.items()])
        p = os.getcwd()
        self.f = None
        try:
            while not path.isfile(path.join(p, "notekins.conf")):
                if p == path.dirname(p):
                    raise FileNotFoundError("Cannot locate configuration file.")
                p = path.dirname(p)
            fn = path.join(p, "notekins.conf")
            self.f = fn
            print(f"Using configuration file {fn}")
            with open(fn, "r") as f:
                for l in f:
                    try:
                        n, v = l.split('=')
                        if n not in CONFIG_ITEMS:
                            continue
                        self.d[n] = CONFIG_ITEMS[n][1](v)
                    except ValueError:
                        pass
        except FileNotFoundError:
            pass
                
    def __getattr__(self, k):
        return self.d[k]
    def require(self):
        if self.f is None:
            print("This operation requires a configuration file, but none can be found.")
            exit(1)

conf = config()