aboutsummaryrefslogblamecommitdiff
path: root/utils/config.py
blob: 43d3683aace590c2c07e18e8466c2b999c5937c9 (plain) (tree)



























































                                                                                
                                                                                      


                   
# 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 was found.")
            exit(1)

conf = config()