diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index fd9d3db..0667264 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -29,6 +29,8 @@ jobs: run: npm run build - name: Check that Chinese and English pages match run: python3 scripts/i18n.py + - name: Unit tests for the i18n check + run: python3 -B -I -X utf8 scripts/test_i18n.py -v - name: Warn when a page changed in one language only if: github.event_name == 'pull_request' env: diff --git a/AGENTS.en.md b/AGENTS.en.md new file mode 100644 index 0000000..4d64e80 --- /dev/null +++ b/AGENTS.en.md @@ -0,0 +1,30 @@ +# Maintenance rules for modavd.github.io + +[简体中文](AGENTS.md) | **English** + + + +For general contribution, branch, commit, privacy and release rules, see [AGENTS.en.md](https://github.com/ModAVD/ModAVD/blob/main/AGENTS.en.md) of the main ModAVD repository. This file only adds what is specific to the docs site. The guide for people is on the site under "Contributing → Documentation and this site" (`docs/en/develop/docs.md`). + +## Layout + +- `docs/` is the VitePress documentation (VitePress 1.6.4, Node.js 24). Chinese pages are in `docs/`, English pages in `docs/en/`, at the same paths. +- `docs/.vitepress/config.mts` is the site configuration. Page titles for the navigation and sidebar are in one table for both languages (`[link, Chinese title, English title]`); add a row for a new page. +- `docs/public/` holds images and other static files, shared by both languages. +- `scripts/` holds the check scripts: `i18n.py` (Chinese/English comparison), `privacy.py` (privacy scan) and their tests. `privacy.py`, `repo_checks.py` and `test_repo_checks.py` are byte for byte the same as in the main ModAVD repository: change them there first and copy them here, CI compares them. Only `privacy-allowlist.json` belongs to this repository. + +## Testing + +- Locally: `npm ci --ignore-scripts`, then `npm run build` (fails on dead links), `python scripts/i18n.py` and `python scripts/privacy.py .`. After changing `scripts/i18n.py`, also run `python -I -X utf8 scripts/test_i18n.py`. +- CI (`.github/workflows/check.yml`) does the same on a PR and also checks commit authors and workflow security; `deploy.yml` publishes to GitHub Pages after a merge into `main`. + +## Chinese and English + +Chinese is the main language and the English pages match page by page; if you change a page in one language, change the other in the same PR. `README.md`, `AGENTS.md` and their `.en.md` files follow the same rule. `python scripts/i18n.py` checks: + +- Errors (CI fails): a page is missing in one language; headings differ in level, order or `{#id}`; a link inside the site leads to the other language; a `#anchor` cannot be found. +- Warnings (shown, CI does not fail): the two versions have a different number of code blocks; they link to different URLs, pages or images (URLs are compared without the `#anchor`, and a README's Chinese and English file names count as the same); one side was last changed in a later commit than the other ("English page older than Chinese since " or the reverse, by commit time in `git log`); a PR changes only one language (`--base`). A warning does not have to be fixed at once, but either update the other side or say in the PR why not. + +## Working rules + +Documentation holds public information only. Do not commit accounts, keys, user paths or test data. Ordinary documentation changes do not add a release-notes entry (`changelog.d`). diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..4464c25 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,30 @@ +# modavd.github.io 维护规矩 + +**简体中文** | [English](AGENTS.en.md) + + + +通用参与、分支、提交、隐私和发版规矩见 ModAVD 主仓库的 [AGENTS.md](https://github.com/ModAVD/ModAVD/blob/main/AGENTS.md)。本文件只补充文档站自己的约定。给人看的写法说明在站内「参与开发 → 文档和本站」(`docs/develop/docs.md`)。 + +## 目录 + +- `docs/` 是 VitePress 文档(VitePress 1.6.4,Node.js 24),中文页在 `docs/`,英文页在 `docs/en/`,路径一一对应。 +- `docs/.vitepress/config.mts` 是站点配置;导航和侧边栏的页面标题两种语言写在同一张表里(`[链接, 中文标题, 英文标题]`),新加页面加一行。 +- `docs/public/` 放图片等静态文件,两种语言共用。 +- `scripts/` 保存检查脚本:`i18n.py`(中英对照)、`privacy.py`(隐私扫描),以及它们的测试。`privacy.py`、`repo_checks.py`、`test_repo_checks.py` 和 ModAVD 主仓库的逐字节相同,先在主仓库改再抄过来,CI 会比对;只有 `privacy-allowlist.json` 是本仓库自己的。 + +## 测试 + +- 本地:`npm ci --ignore-scripts`,然后 `npm run build`(有死链会失败)、`python scripts/i18n.py`、`python scripts/privacy.py .`。改了 `scripts/i18n.py` 再跑 `python -I -X utf8 scripts/test_i18n.py`。 +- CI(`.github/workflows/check.yml`)在 PR 上做同样的事,并检查提交作者和 workflow 安全;`deploy.yml` 在合进 `main` 后发布到 GitHub Pages。 + +## 中英两种语言 + +中文是主语言,英文页逐页对应;改了一种语言的页面,同一个 PR 里把另一种也改了。`README.md`、`AGENTS.md` 和各自的 `.en.md` 也是这样。`python scripts/i18n.py` 核对: + +- 出错(会让 CI 失败):缺了某一种语言的页面;标题的层级、顺序、`{#id}` 不同;站内链接串到另一种语言;`#锚点` 找不到。 +- 提醒(只标出来,不失败):两边代码块数量不同;两边链到的网址、页面或图片不同(网址去掉 `#锚点`,README 的中英文件名视为同一个);一边最近一次改动晚于另一边(「English page older than Chinese since <提交>」或反过来,按 `git log` 的提交时间);PR 里只改了一种语言(`--base`)。提醒不要求马上改,但要么补上另一边,要么在 PR 里说明为什么不用。 + +## 做事 + +文档只放公开信息。不要提交账号、密钥、用户路径或测试数据。普通文档改动不添加发版公告条目(`changelog.d`)。 diff --git a/README.en.md b/README.en.md index 7f6cfa4..d4cde36 100644 --- a/README.en.md +++ b/README.en.md @@ -25,7 +25,7 @@ python scripts/privacy.py . # privacy scan, same as CI ## CI -- `check.yml`: on a PR it builds the whole site (dead-link check), checks that the Chinese and English pages match (`scripts/i18n.py`: every page exists in both languages, headings have the same levels and order, site links do not cross languages, and every anchor resolves; a page changed in one language only gets a warning), and runs the privacy scan. +- `check.yml`: on a PR it builds the whole site (dead-link check), checks that the Chinese and English pages match (`scripts/i18n.py`: every page exists in both languages, headings have the same levels and order, site links do not cross languages, and every anchor resolves; a page changed in one language only, different code blocks or links, or one side lagging behind the other only get a warning), and runs the privacy scan. - `deploy.yml`: after a merge into `main` it builds the site and publishes it to GitHub Pages. - Third-party actions are always pinned to a full 40-character commit SHA; no `pull_request_target`, no self-hosted runners. diff --git a/README.md b/README.md index 8a470d1..4f97e6e 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ python scripts/privacy.py . # 隐私扫描,和 CI 一样 ## CI -- `check.yml`:PR 上编译整站(查死链)、核对中英页面(`scripts/i18n.py`:每页都有两种语言,标题的层级和顺序相同,站内链接不串语言,锚点都找得到;只改了一种语言的页面会标出提醒)、跑隐私扫描。 +- `check.yml`:PR 上编译整站(查死链)、核对中英页面(`scripts/i18n.py`:每页都有两种语言,标题的层级和顺序相同,站内链接不串语言,锚点都找得到;只改了一种语言的页面、两边代码块或链接不同、一边落后于另一边,都只标出提醒)、跑隐私扫描。 - `deploy.yml`:合进 `main` 后编译并发布到 GitHub Pages。 - 第三方 action 一律钉到 40 位提交 SHA;不用 `pull_request_target`,不用自托管 runner。 diff --git a/docs/develop/docs.md b/docs/develop/docs.md index 78193db..9a8d023 100644 --- a/docs/develop/docs.md +++ b/docs/develop/docs.md @@ -32,7 +32,7 @@ python scripts/i18n.py # 核对中英两边的页面和标题 PR 上的 CI 会: - 编译整站,有死链就失败; -- 核对中英两边(`python scripts/i18n.py`):每页都有两种语言,标题的层级和顺序相同,站内链接不串到另一种语言,`#锚点` 都找得到;只改了一种语言的页面会标出提醒; +- 核对中英两边(`python scripts/i18n.py`):每页都有两种语言,标题的层级和顺序相同,站内链接不串到另一种语言,`#锚点` 都找得到;只改了一种语言的页面会标出提醒;另外两边代码块数量、链到的网址不同,或一边的最近改动晚于另一边,也会标出提醒(只提醒,不让 CI 失败); - 跑隐私扫描(`python scripts/privacy.py .`),文档里出现本机用户目录这类路径就失败。 合进 `main` 以后自动发布到 GitHub Pages。 diff --git a/docs/en/develop/docs.md b/docs/en/develop/docs.md index 6e2d46b..cee7762 100644 --- a/docs/en/develop/docs.md +++ b/docs/en/develop/docs.md @@ -32,7 +32,7 @@ python scripts/i18n.py # checks the pages and headings of the Chinese and Engl CI on a PR will: - build the whole site, and fail on dead links; -- check the Chinese and English sides against each other (`python scripts/i18n.py`): every page exists in both languages, headings have the same levels and order, links inside the site do not lead to the other language, and every `#anchor` can be found. A page changed in only one language is flagged as a reminder; +- check the Chinese and English sides against each other (`python scripts/i18n.py`): every page exists in both languages, headings have the same levels and order, links inside the site do not lead to the other language, and every `#anchor` can be found. A page changed in only one language is flagged as a reminder, and so are pages whose two versions have a different number of code blocks or link to different URLs, or where one side was last changed later than the other (reminders only; CI does not fail); - run the privacy scan (`python scripts/privacy.py .`), which fails if the docs contain paths such as a local user directory. After a merge into `main`, the site is published to GitHub Pages automatically. diff --git a/scripts/i18n.py b/scripts/i18n.py index b43adfa..9a4e0e3 100644 --- a/scripts/i18n.py +++ b/scripts/i18n.py @@ -5,10 +5,15 @@ - links into the site stay in their own language (English pages link to /en/..., Chinese pages do not); - every #anchor in a link to a page of this site exists in that page. -With --base it also warns about pages changed since in one language only. +Warnings (they never fail the check; they are printed as GitHub annotations in CI): +- the two versions of a page have a different number of code blocks, or link to different URLs, pages or images + (a cheap check that needs no translation); +- one language was last changed in a later commit than the other ("English page older than Chinese since "); +- with --base : pages changed since in one language only. Run from anywhere: python scripts/i18n.py [--base origin/main] """ +import os import re import subprocess import sys @@ -35,7 +40,7 @@ def slugify(text): def parse(path): """Headings as (level, explicit id, anchor) and links as (line, target), skipping code blocks.""" - headings, links, seen, fence = [], [], {}, None + headings, links, seen, fence, blocks = [], [], {}, None, 0 lines = path.read_text(encoding="utf-8").splitlines() front = lines.index("---", 1) if lines and lines[0] == "---" else 0 for number, line in enumerate(lines, 1): @@ -45,6 +50,8 @@ def parse(path): continue match = FENCE.match(line) if match: + if fence is None: + blocks += 1 fence = None if fence == match.group(1) else (fence or match.group(1)) continue if fence: @@ -56,7 +63,7 @@ def parse(path): seen[anchor] = count + 1 headings.append((len(match.group(1)), match.group(3), anchor if count == 0 else f"{anchor}-{count}")) links += [(number, target) for target in LINK.findall(line)] - return headings, links + return headings, links, blocks def resolve(page, target): @@ -81,6 +88,64 @@ def resolve(page, target): return rel if rel.endswith(".md") else re.sub(r"\.html$", "", rel) + ".md" +def warn(message, file=None): + """A warning that never fails the check: a GitHub annotation in CI, plain text elsewhere.""" + if os.environ.get("GITHUB_ACTIONS"): + print(f"::warning file={file}::{message}" if file else f"::warning::{message}") + else: + print(f"warning: {message}") + + +def external(url): + """Another site's URL without what is language specific: the #anchor (headings are translated) and the English + file name of a README (README.en.md is the same document as README.md; the repository root shows README.md).""" + url = url.split("#")[0].replace(".en.md", ".md") + url = re.sub(r"/blob/[^/]+/README\.md$", "", url) + return url.replace("modavd.github.io/en/", "modavd.github.io/").rstrip("/") + + +def link_set(page, links): + """The links of a page, in a form that is the same in both languages: other sites as they are, pages without the + en/ prefix, other files (images) as written.""" + result = set() + for _, target in links: + dest = resolve(page, target) + if dest is None: + result.add(external(target) if re.match(r"^[a-z]+:", target) else target.split("#")[0]) + else: + result.add("page:" + (dest[3:] if dest.startswith("en/") else dest)) + return result + + +def content_differences(zh_page, en_page): + """What differs between the two versions in ways that do not need a translation to see.""" + found = [] + if zh_page[2] != en_page[2]: + found.append(f"{zh_page[2]} code blocks in Chinese, {en_page[2]} in English") + only_zh = sorted(zh_page[3] - en_page[3]) + only_en = sorted(en_page[3] - zh_page[3]) + if only_zh: + found.append("links only in Chinese: " + ", ".join(only_zh)) + if only_en: + found.append("links only in English: " + ", ".join(only_en)) + return found + + +def last_change(path, cwd): + """(unix time, short commit) of the last commit that changed path, or None if git does not know the file.""" + out = subprocess.run(["git", "log", "-1", "--format=%ct %h", "--", str(path)], cwd=cwd, capture_output=True, + text=True, encoding="utf-8").stdout.split() + return (int(out[0]), out[1]) if len(out) == 2 else None + + +def stale_side(zh_change, en_change): + """Which side fell behind: 'English' or 'Chinese' with the commit that moved the other side, or None.""" + if not zh_change or not en_change or zh_change[1] == en_change[1] or zh_change[0] == en_change[0]: + return None + if zh_change[0] > en_change[0]: + return f"English page older than Chinese since {zh_change[1]}" + return f"Chinese page older than English since {en_change[1]}" + def main(): pages = {p.relative_to(DOCS).as_posix() for p in DOCS.rglob("*.md") if ".vitepress" not in p.parts} zh = {p for p in pages if not p.startswith("en/")} @@ -88,6 +153,7 @@ def main(): errors = [f"docs/{p}: no English page docs/en/{p}" for p in sorted(zh - en)] errors += [f"docs/en/{p}: no Chinese page docs/{p}" for p in sorted(en - zh)] parsed = {p: parse(DOCS / p) for p in pages} + parsed = {p: (*v, link_set(p, v[1])) for p, v in parsed.items()} for p in sorted(zh & en): a = [(level, hid) for level, hid, _ in parsed[p][0]] @@ -109,6 +175,13 @@ def main(): elif target.split("#", 1)[1] not in {anchor for _, _, anchor in parsed[dest][0]}: errors.append(f"docs/{p}:{number}: {target}: no such heading in docs/{dest}") + for p in sorted(zh & en): + for text in content_differences(parsed[p], parsed["en/" + p]): + warn(f"docs/{p} and docs/en/{p} differ: {text}", f"docs/en/{p}") + stale = stale_side(last_change(DOCS / p, DOCS.parent), last_change(DOCS / "en" / p, DOCS.parent)) + if stale: + warn(f"docs/en/{p}: {stale}", f"docs/en/{p}") + if "--base" in sys.argv: base = sys.argv[sys.argv.index("--base") + 1] diff = subprocess.run(["git", "diff", "--name-only", f"{base}...HEAD", "--", "docs"], cwd=DOCS.parent, diff --git a/scripts/test_i18n.py b/scripts/test_i18n.py new file mode 100644 index 0000000..d5c40b7 --- /dev/null +++ b/scripts/test_i18n.py @@ -0,0 +1,82 @@ +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +# CI runs this with python -I, which leaves the script's own directory off sys.path. +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import i18n # noqa: E402 + + +def page(tmp, name, text): + path = Path(tmp) / name + path.write_text(text, encoding="utf-8") + return i18n.parse(path) + + +class ContentCheckTest(unittest.TestCase): + def signature(self, tmp, name, page_name, text): + headings, links, blocks = page(tmp, name, text) + return headings, links, blocks, i18n.link_set(page_name, links) + + def test_code_blocks_are_counted_and_fenced_text_is_ignored(self): + with tempfile.TemporaryDirectory() as tmp: + _, links, blocks = page(tmp, "a.md", "# T\n\n```sh\n[x](http://skipped)\n```\n\n~~~\nb\n~~~\n[y](http://kept)\n") + self.assertEqual(blocks, 2) + self.assertEqual([t for _, t in links], ["http://kept"]) + + def test_same_content_in_both_languages_has_no_differences(self): + with tempfile.TemporaryDirectory() as tmp: + zh = self.signature(tmp, "zh.md", "guide/a.md", + "# 标题\n```sh\nx\n```\n[B](./b) ![i](/shot.png) [g](https://example.org/x/#中文)\n") + en = self.signature(tmp, "en.md", "en/guide/a.md", + "# Title\n```sh\nx\n```\n[B](./b) ![i](/shot.png) [g](https://example.org/x/#english)\n") + self.assertEqual(i18n.content_differences(zh, en), []) + + def test_different_blocks_and_links_are_reported(self): + with tempfile.TemporaryDirectory() as tmp: + zh = self.signature(tmp, "zh.md", "guide/a.md", "# T\n```\nx\n```\n[a](https://example.org/a)\n") + en = self.signature(tmp, "en.md", "en/guide/a.md", "# T\n[b](https://example.org/b)\n") + found = i18n.content_differences(zh, en) + self.assertEqual(len(found), 3) + self.assertIn("1 code blocks in Chinese, 0 in English", found) + self.assertIn("links only in Chinese: https://example.org/a", found) + self.assertIn("links only in English: https://example.org/b", found) + + def test_external_urls_ignore_anchor_and_readme_language(self): + self.assertEqual(i18n.external("https://github.com/ModAVD/ModAVD#已实测的游戏"), "https://github.com/ModAVD/ModAVD") + self.assertEqual(i18n.external("https://github.com/ModAVD/ModAVD/blob/main/README.en.md#tested-games"), + "https://github.com/ModAVD/ModAVD") + self.assertEqual(i18n.external("https://github.com/ModAVD/ModAVD/blob/main/AGENTS.en.md"), + "https://github.com/ModAVD/ModAVD/blob/main/AGENTS.md") + self.assertEqual(i18n.external("https://modavd.github.io/en/develop/"), "https://modavd.github.io/develop") + + def test_internal_links_compare_without_the_language_prefix(self): + self.assertEqual(i18n.link_set("en/guide/a.md", [(1, "/en/guide/install")]), + i18n.link_set("guide/a.md", [(1, "/guide/install")])) + + +class StaleTest(unittest.TestCase): + def test_which_side_fell_behind(self): + self.assertIsNone(i18n.stale_side(None, (1, "a"))) + self.assertIsNone(i18n.stale_side((5, "same"), (5, "same"))) + self.assertIsNone(i18n.stale_side((5, "c1"), (5, "c2"))) + self.assertEqual(i18n.stale_side((9, "zh9"), (5, "en5")), "English page older than Chinese since zh9") + self.assertEqual(i18n.stale_side((5, "zh5"), (9, "en9")), "Chinese page older than English since en9") + + def test_last_change_reads_git(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + git = ["git", "-c", "user.name=t", "-c", "user.email=t@users.noreply.github.com"] + subprocess.run(["git", "init", "-q"], cwd=root, check=True) + (root / "a.md").write_text("a", encoding="utf-8") + subprocess.run(["git", "add", "."], cwd=root, check=True) + subprocess.run([*git, "commit", "-qm", "x"], cwd=root, check=True) + change = i18n.last_change(root / "a.md", root) + self.assertEqual(len(change), 2) + self.assertIsNone(i18n.last_change(root / "missing.md", root)) + + +if __name__ == "__main__": + unittest.main()