#!/usr/bin/env python3 """把 APP_NAME 直写进 app.ini 的顶层(DEFAULT 段),并清掉历史误写的 [server] APP_NAME。 为什么不走 compose 环境变量(实测 2026-10-22): Gitea 读的是 rootCfg.Section("").Key("APP_NAME")(modules/setting/server.go:149), 而 environment-to-ini 把 GITEA__DEFAULT__APP_NAME 写成了字面 `[default]` 段 —— go-ini 只把 文件里第一个 section 头之前的键当 DEFAULT,`[default]` 是普通段 ⇒ 环境变量这条路根本到不了。 用法: patch-app-ini.py (就地改 ./app.ini,先留 .bak) 输出: PATCHED / UNCHANGED / RED(异常,不改文件) """ import os import re import shutil import sys FILE = "app.ini" KEY = "APP_NAME" def main(): if len(sys.argv) != 2: print("用法: patch-app-ini.py ") return 2 want = sys.argv[1] if not os.path.exists(FILE): print("RED 找不到 %s" % FILE) return 2 src = open(FILE, encoding="utf-8").read() lines = src.split("\n") # 顶层 = 第一个 [section] 头之前的区段 first_hdr = next((i for i, l in enumerate(lines) if re.match(r"^\[", l)), len(lines)) top_key = next((i for i in range(first_hdr) if re.match(r"^%s\s*=" % KEY, lines[i])), None) out = list(lines) if top_key is None: out.insert(0, "%s = %s" % (KEY, want)) elif out[top_key] != "%s = %s" % (KEY, want): out[top_key] = "%s = %s" % (KEY, want) # 清掉 [server] 里那条被 Gitea 忽略的残留(上一版部署误写的) cur = "(top)" stale = [] for i, l in enumerate(out): m = re.match(r"^\[(.*)\]", l) if m: cur = m.group(1) continue if cur == "server" and re.match(r"^%s\s*=" % KEY, l): stale.append(i) for i in sorted(stale, reverse=True): del out[i] new = "\n".join(out) if new == src: print("UNCHANGED") return 0 shutil.copy2(FILE, FILE + ".bak-brand") open(FILE, "w", encoding="utf-8").write(new) os.chmod(FILE, os.stat(FILE + ".bak-brand").st_mode & 0o777) print("PATCHED top=%s stale_removed=%d" % ("inserted" if top_key is None else "replaced", len(stale))) return 0 if __name__ == "__main__": sys.exit(main())