#!/usr/bin/env python3 """幂等地把品牌相关配置项写进生产 docker-compose.yml 的 environment 段。 为什么单独成文件而不是内联在 ssh 里:内联要穿过「本地 bash → ssh → 远端 sh → python」四层引号, 而 python 正则里的 `$'` 会被本地 bash 当 ANSI-C 引用吃掉 —— 这类静默改写在生产脚本里不可接受。 用法: patch-compose.py 在 compose 所在目录内运行(就地改 docker-compose.yml)。 输出:PATCHED / UNCHANGED / NO_ANCHOR(NO_ANCHOR 时不改文件,退出码 3) """ import re import sys WANT_KEYS = ["GITEA__ui.meta__DESCRIPTION", "GITEA__ui.meta__KEYWORDS"] # APP_NAME 不在这里:Gitea 读的是 app.ini 顶层 DEFAULT 段,env 这条路到不了(见 patch-app-ini.py 文件头) ANCHOR_RE = re.compile(r"^([ \t]*)- GITEA__security__INSTALL_LOCK=.*$") FILE = "docker-compose.yml" def main(): if len(sys.argv) != 3: print("用法: patch-compose.py ") return 2 want = dict(zip(WANT_KEYS, sys.argv[1:3])) try: src = open(FILE, encoding="utf-8").read() except OSError as e: print("READ_FAIL %s" % e) return 2 lines = src.split("\n") ind = None anchor_idx = None for i, line in enumerate(lines): m = ANCHOR_RE.match(line) if m: ind, anchor_idx = m.group(1), i break if anchor_idx is None: print("NO_ANCHOR") return 3 out = list(lines) # 从锚点往下逐个键:已存在则原地替换,不存在则紧跟锚点插入(保持同一缩进块内) pos = anchor_idx + 1 for key in WANT_KEYS: pat = re.compile(r"^[ \t]*- %s=.*$" % re.escape(key)) hit = next((i for i, l in enumerate(out) if pat.match(l)), None) line = "%s- %s=%s" % (ind, key, want[key]) if hit is not None: out[hit] = line else: out.insert(pos, line) pos += 1 new = "\n".join(out) if new == src: print("UNCHANGED") return 0 open(FILE, "w", encoding="utf-8").write(new) print("PATCHED") return 0 if __name__ == "__main__": sys.exit(main())