SHA256
deploy / deploy (push) Skipped
按 deploy/ci-cd.md 方案把除推送触发之外的东西都准备好:
- customization/check.sh <base-url>: 把 preview.sh check 里的"定制生效"断言抽成
任意实例可跑的脚本(首页/页脚/meta/官网链接/登录页两张卡/无通行密钥方框/
无「工单」/无 example.com), 另加生产才有的 OIDC 入口 307 断言(404 = 认证源没注册上)。
实测对生产 17/17 通过。
- deploy/scripts/auto-deploy.sh: build.py -> compose up -d -> verify.sh + check.sh,
失败自动回滚到 deploy/.state/last-deployed; flock 串行; 结束时把 clone 所有权还给
ymy(job 容器里是 root); 内网验证强制不走代理。
- deploy/runner/{compose.yaml,config.yaml,.env.example}: act_runner v0.6.1 跑在容器里
(不需要 root), network: host + 同路径挂载部署克隆 + 宿主 docker CLI/compose 插件,
capacity 1 保证部署串行。
- .gitea/workflows/deploy.yml: push main + workflow_dispatch, [skip deploy] 跳过,
concurrency 串行, 只做"同步到 github.sha + 调 auto-deploy.sh"。
- .gitignore: deploy/.state/、deploy/runner/{.env,data/}。
依据见 deploy/ci-cd.md(含全部实测证据与待确认项)。
211 lines
8.5 KiB
Python
Executable File
211 lines
8.5 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)
|
|
try:
|
|
OUT_PATH.write_text(rendered, encoding="utf-8")
|
|
except PermissionError as exc:
|
|
raise SystemExit(
|
|
f"写入失败: {exc}\n"
|
|
f" 多半是 docker 以 root 创建过这个挂载源目录(bind mount 的源目录不存在时它会这么做),\n"
|
|
f" 普通用户就写不进去了。删掉再重试: sudo rm -rf {OUT_PATH.parent}\n"
|
|
f" (仓库里 customization/custom/options/.gitkeep 就是为防止这种情况而存在的)"
|
|
) from exc
|
|
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())
|