summaryrefslogtreecommitdiff
path: root/src/xpit_/issue_tracker.py
blob: 20c1662432e3e5851567a462dcc00ba4d3041133 (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
import os
import sys
from . import issue
from . import error
Err = error.Err

class State:
    def __init__(self):
        self.dir: str | None = None
        self.config: dict[bytes, bytes] | None = None
        self.allowed_labels: list[bytes] | None = None
state = State()

def find_dir(start_dir: str, suppress_warning: bool = False) -> str | None:
    cur = os.path.abspath(start_dir)

    while True:
        candidate = os.path.join(cur, "issue-tracker")
        if os.path.isdir(candidate):
            return candidate

        parent = os.path.dirname(cur)
        if parent == cur:  # reached filesystem root
            if not suppress_warning:
                sys.stderr.write(
                    "xpit has not been initialized. `xpit init` to initialize.\n"
                )
            return None
        cur = parent

def load_config() -> Err | None:
    if state.dir is None:
        state.dir = find_dir(os.getcwd())
    if state.dir is None:
        return Err("ERR_COULD_NOT_FIND_ISSUE_TRACKER_DIR")
    with open(os.path.join(state.dir, "_config.ini"), "rb") as f:
        src = f.read()
    state.config = {}
    issue.parse_ini(src, 0, state.config)
    if b"allowed_labels" not in state.config:
        sys.stdout.write("Warning: _config.ini has no allowed_labels\n")
        state.config[b"allowed_labels"] = b""
    if b"id_format" not in state.config:
        sys.stdout.write("Warning: _config.ini has no id_format. Defaulting to '%Y%m%d_%H%M%S'\n")
        state.config[b"id_format"] = b"%Y%m%d_%H%M%S"
    state.allowed_labels = state.config[b"allowed_labels"].split(b',')

    return None

def __getattr__(name):
    return getattr(state, name)