SHA256
forked from course-team/tjhlp-gitea
不改 Go 代码、不 fork, 只用官方 CustomPath 覆盖层 + app.ini/env 配置: - custom/templates: 整文件覆盖 home.tmpl(落地页换成答疑平台介绍)与 base/head_navbar.tmpl(docs.gitea.com -> 站内提问指南、新增课程官网入口) - custom/public/assets/tjhlp/ask-guide.html: 站内提问指南静态页 - overrides/ + build.py: 由上游快照确定性生成整份 locale_zh-CN.json (工单 -> Issue 等 133 处), 带占位符校验; 缺失键会退回英文, 必须整份覆盖 - build.py 同时负责规范 custom/ 权限: 容器内 Gitea 以 git(982) 运行, 文件若为 600 只读挂载也会 permission denied 并拒绝启动(生产踩过) - upstream/<版本>/ + fetch-upstream.sh: 上游基线, 供升级时 diff 与重生成 - preview/: 独立 compose + preview.sh(up/check/reload/admin/reset), 与生产隔离(独立端口 2081/数据目录/sqlite), 用同一镜像版本验证效果 - website-linkage.md: 官网(VitePress)侧的联动改动提案
203 lines
8.0 KiB
Python
Executable File
203 lines
8.0 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""生成 TJHLP 定制用的 Gitea 简体中文语言文件。
|
|
|
|
Gitea 只支持「整个文件覆盖」locale: 放在 custom/options/locale/locale_zh-CN.json 的
|
|
文件会完全替换内置的 zh-CN。缺失的键不会退回中文, 而是退回默认语言(en-US),
|
|
所以覆盖文件必须是完整的一份, 不能只写改动项。本脚本用来从上游快照
|
|
(upstream/<版本>/locale_zh-CN.json) + 我们的覆盖(rules / overrides)确定性地产出
|
|
这份完整文件, 避免手工维护 3900 个键。
|
|
|
|
用法:
|
|
python3 customization/build.py # 生成 custom/options/locale/locale_zh-CN.json
|
|
python3 customization/build.py --check # 只校验磁盘上的生成物是否最新(CI / 部署前)
|
|
python3 customization/build.py --quiet # 不打印改动清单
|
|
|
|
除了生成语言文件, 本脚本还负责把 custom/ 的权限规范成「容器用户可读」——
|
|
Gitea 容器以镜像内的 git 用户运行, 而编辑器写出来的文件可能是 600, 只读挂载进容器后
|
|
会 permission denied 并让 Gitea 拒绝启动(见 deploy/README.md 已知陷阱 3)。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import re
|
|
import stat
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
HERE = Path(__file__).resolve().parent
|
|
CUSTOM_DIR = HERE / "custom"
|
|
OUT_PATH = CUSTOM_DIR / "options" / "locale" / "locale_zh-CN.json"
|
|
|
|
# Go 模板/printf 里的格式化占位符, 例如 %s %d %v %[1]s %[2]d %%
|
|
FORMAT_RE = re.compile(r"%(?:\[(\d+)\])?[-+# 0-9.]*[a-zA-Z%]")
|
|
|
|
|
|
def load_json(path: Path):
|
|
with path.open(encoding="utf-8") as f:
|
|
return json.load(f)
|
|
|
|
|
|
def strip_comments(obj: dict) -> dict:
|
|
"""去掉以 _ 开头的说明键, 它们只是给人看的元数据。"""
|
|
return {k: v for k, v in obj.items() if not k.startswith("_")}
|
|
|
|
|
|
def format_verbs(text: str) -> list[str]:
|
|
return FORMAT_RE.findall(text)
|
|
|
|
|
|
def _is_cjk_ideograph(ch: str) -> bool:
|
|
# 只在汉字旁边补空格; 中文标点(。,、「」…)本身不需要与英文分隔
|
|
return "\u4e00" <= ch <= "\u9fff"
|
|
|
|
|
|
def _pad_for(edge: str, neighbour: str) -> str:
|
|
"""中英混排时给替换结果补一个空格: 汉字紧邻英文/数字才需要。"""
|
|
if edge and edge[0].isascii() and edge[0].isalnum() and neighbour and _is_cjk_ideograph(neighbour):
|
|
return " "
|
|
return ""
|
|
|
|
|
|
def apply_rule(text: str, src: str, dst: str) -> str:
|
|
"""字面替换 src -> dst, 并在中英交界处补空格(工单 -> " Issue ")。"""
|
|
out: list[str] = []
|
|
pos = 0
|
|
while True:
|
|
found = text.find(src, pos)
|
|
if found < 0:
|
|
out.append(text[pos:])
|
|
return "".join(out)
|
|
out.append(text[pos:found])
|
|
left = text[found - 1] if found > 0 else ""
|
|
right = text[found + len(src)] if found + len(src) < len(text) else ""
|
|
out.append(_pad_for(dst, left) + dst + _pad_for(dst[::-1], right))
|
|
pos = found + len(src)
|
|
|
|
|
|
def build() -> tuple[dict, dict, list[tuple[str, str, str]]]:
|
|
version = (HERE / "gitea-version.txt").read_text(encoding="utf-8").strip()
|
|
upstream_path = HERE / "upstream" / version / "options" / "locale" / "locale_zh-CN.json"
|
|
if not upstream_path.exists():
|
|
sys.exit(f"缺少上游快照: {upstream_path} (先执行 customization/fetch-upstream.sh {version})")
|
|
|
|
upstream: dict[str, object] = load_json(upstream_path)
|
|
locale: dict[str, object] = dict(upstream)
|
|
rules = strip_comments(load_json(HERE / "overrides" / "locale_zh-CN.rules.json"))["rules"]
|
|
overrides = strip_comments(load_json(HERE / "overrides" / "locale_zh-CN.json"))["overrides"]
|
|
|
|
errors: list[str] = []
|
|
|
|
for rule in rules:
|
|
src, dst = rule["from"], rule["to"]
|
|
for key, value in locale.items():
|
|
if isinstance(value, str) and src in value:
|
|
locale[key] = apply_rule(value, src, dst)
|
|
|
|
for key, new_value in overrides.items():
|
|
if key not in upstream:
|
|
errors.append(f"覆盖键不存在于上游: {key}")
|
|
continue
|
|
old_value = upstream[key]
|
|
if not isinstance(old_value, str):
|
|
errors.append(f"覆盖键在上游不是字符串: {key}")
|
|
continue
|
|
if format_verbs(old_value) != format_verbs(new_value):
|
|
errors.append(f"占位符不一致: {key}\n 上游: {old_value}\n 覆盖: {new_value}")
|
|
locale[key] = new_value
|
|
|
|
if errors:
|
|
sys.exit("构建失败:\n - " + "\n - ".join(errors))
|
|
|
|
changes = [(k, str(upstream[k]), str(v)) for k, v in locale.items() if upstream.get(k) != v]
|
|
return locale, upstream, changes
|
|
|
|
|
|
def render(locale: dict) -> str:
|
|
# 保持上游的键顺序, 让 git diff 只显示真正改动的行
|
|
return json.dumps(locale, ensure_ascii=False, indent=2) + "\n"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# custom/ 的权限
|
|
# ---------------------------------------------------------------------------
|
|
# Gitea 容器以镜像内的 git 用户运行(部署里 USER_UID=982), 而编辑器/工具写出来的文件
|
|
# 可能是 600(仅属主可读)。custom/ 是只读挂载进容器的, 一旦容器用户读不到,
|
|
# prod 模式会直接拒绝启动: "Gitea can't run with template errors: open home.tmpl:
|
|
# permission denied"(2026-09 生产真的这样挂过一次)。预览之所以没暴露, 是因为
|
|
# 预览容器的 uid 就是宿主用户。
|
|
# 所以每次生成都顺手把 custom/ 规范成「组 + 其他人可读, 目录可进入」。
|
|
def unreadable_paths(root: Path) -> list[Path]:
|
|
"""列出容器用户(非属主)读不到的文件/进不去的目录。"""
|
|
bad: list[Path] = []
|
|
for path in sorted(root.rglob("*")):
|
|
mode = path.stat().st_mode
|
|
need = stat.S_IROTH | (stat.S_IXOTH if path.is_dir() else 0)
|
|
if mode & need != need:
|
|
bad.append(path)
|
|
return bad
|
|
|
|
|
|
def ensure_readable(root: Path) -> list[Path]:
|
|
"""补齐 g+r / o+r(目录再补 o+x), 返回被修正的路径。"""
|
|
fixed: list[Path] = []
|
|
for path in sorted(root.rglob("*")):
|
|
mode = path.stat().st_mode
|
|
want = mode | stat.S_IRGRP | stat.S_IROTH
|
|
if path.is_dir():
|
|
want |= stat.S_IXGRP | stat.S_IXOTH
|
|
if want != mode:
|
|
path.chmod(want)
|
|
fixed.append(path)
|
|
return fixed
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--check", action="store_true", help="只校验, 不写入")
|
|
parser.add_argument("--quiet", action="store_true", help="不打印改动清单")
|
|
args = parser.parse_args()
|
|
|
|
locale, upstream, changes = build()
|
|
rendered = render(locale)
|
|
|
|
if not args.quiet:
|
|
print(f"上游键数: {len(upstream)} 覆盖后键数: {len(locale)} 改动: {len(changes)} 处")
|
|
for key, old, new in changes:
|
|
print(f" {key}\n - {old}\n + {new}")
|
|
|
|
if args.check:
|
|
current = OUT_PATH.read_text(encoding="utf-8") if OUT_PATH.exists() else ""
|
|
if current != rendered:
|
|
print(f"✗ {OUT_PATH} 与覆盖配置不一致, 请运行 python3 customization/build.py", file=sys.stderr)
|
|
return 1
|
|
print(f"✓ {OUT_PATH} 是最新的")
|
|
|
|
bad = unreadable_paths(CUSTOM_DIR)
|
|
if bad:
|
|
print(
|
|
"✗ 下列文件/目录对容器用户不可读(挂载进容器会 permission denied), "
|
|
"请运行 python3 customization/build.py 修正:",
|
|
file=sys.stderr,
|
|
)
|
|
for path in bad:
|
|
print(f" {path.relative_to(HERE)} {oct(path.stat().st_mode & 0o777)}", file=sys.stderr)
|
|
return 1
|
|
print("✓ custom/ 权限正常(容器用户可读)")
|
|
return 0
|
|
|
|
OUT_PATH.parent.mkdir(parents=True, exist_ok=True)
|
|
OUT_PATH.write_text(rendered, encoding="utf-8")
|
|
print(f"✓ 已生成 {OUT_PATH}")
|
|
fixed = ensure_readable(CUSTOM_DIR)
|
|
if fixed:
|
|
print(f"✓ 修正了 {len(fixed)} 个权限过紧的路径(容器用户需要可读):")
|
|
for path in fixed:
|
|
print(f" {path.relative_to(HERE)}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|