File size: 1,078 Bytes
d4c51f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Config loading and tiny on-disk JSON cache so re-runs don't re-hit the API."""
from __future__ import annotations

import json
import os
from pathlib import Path

import yaml


def load_config(path: str = "config.yaml") -> dict:
    p = Path(path)
    if not p.exists():
        raise SystemExit(
            f"{path} not found. Copy config.example.yaml -> config.yaml and edit it."
        )
    with p.open() as f:
        return yaml.safe_load(f)


def data_dir(cfg: dict) -> Path:
    d = Path(cfg.get("data_dir", "data"))
    d.mkdir(parents=True, exist_ok=True)
    return d


def cache_path(cfg: dict, *parts: str) -> Path:
    d = data_dir(cfg)
    for part in parts[:-1]:
        d = d / part
        d.mkdir(parents=True, exist_ok=True)
    return d / parts[-1]


def read_json(path: Path):
    if path.exists():
        with path.open() as f:
            return json.load(f)
    return None


def write_json(path: Path, obj) -> None:
    tmp = path.with_suffix(path.suffix + ".tmp")
    with tmp.open("w") as f:
        json.dump(obj, f)
    os.replace(tmp, path)