env.py
1.9 kB · python · 75 lines
1import json2import os3import sys45# PATHS67SHOP_DIR = os.path.dirname(os.path.abspath(__file__))8REPO = os.path.dirname(SHOP_DIR)9DESK = os.path.dirname(REPO)10ENV_PATH = os.path.join(DESK, ".env")11DATA_DIR = os.path.join(SHOP_DIR, "data")1213# ENV1415def load_env():16 if not os.path.exists(ENV_PATH):17 raise SystemExit(f"refuse: {ENV_PATH} is missing")18 with open(ENV_PATH) as handle:19 for line in handle:20 line = line.strip()21 if not line or line.startswith("#"): continue22 key, _, value = line.partition("=")23 os.environ.setdefault(key.strip(), value.strip())2425def env(key, fallback=""):26 return os.environ.get(key) or fallback2728def need(key):29 value = env(key)30 if not value:31 raise SystemExit(f"refuse: {key} is not in .env")32 return value3334def save_env(key, value):35 if env(key):36 say(f"skip {key}, .env already holds a value")37 return38 with open(ENV_PATH) as handle:39 head = "" if handle.read().endswith("\n") else "\n"40 with open(ENV_PATH, "a") as handle:41 handle.write(f"{head}{key}={value}\n")42 os.environ[key] = value43 say(f"{key} written to .env")4445# JSON4647def load_json(path):48 with open(path) as handle:49 return json.load(handle)5051def save_json(path, data, indent=2):52 parent = os.path.dirname(path)53 if parent:54 os.makedirs(parent, exist_ok=True)55 with open(path, "w") as handle:56 json.dump(data, handle, indent=indent)5758# SAY5960def say(text=""):61 print(text)6263def gate(title, steps):64 say(f"PLAN {title}")65 for step in steps: say(f" {step}")66 if "--yes" in sys.argv: return True67 say("HOLD rerun with --yes to apply")68 return False6970def verb(names):71 word = sys.argv[1] if len(sys.argv) > 1 else ""72 if word not in names:73 say("verbs: " + " ".join(names))74 raise SystemExit(1)75 return word