返回 CodeWhale
check-readme-translations.py
根目录 / scripts / check-readme-translations.py
1 #!/usr/bin/env python3
2 """Keep the localized READMEs in lockstep with README.md.
3
4 Every translated README must:
5 1. carry a source stamp `<!-- source: README.md sha256:<12-hex> -->`
6 matching the current hash of README.md — so any English edit fails CI
7 until the translations are refreshed;
8 2. contain exactly the same fenced code blocks, in the same order
9 (commands are never translated);
10 3. contain every non-language-switcher URL the English README contains;
11 4. have the same number of `##` sections.
12
13 Run: python3 scripts/check-readme-translations.py
14 """
15
16 from __future__ import annotations
17
18 import hashlib
19 import posixpath
20 import re
21 import sys
22 from pathlib import Path
23
24 ROOT = Path(__file__).resolve().parent.parent
25 SOURCE = ROOT / "README.md"
26 TRANSLATIONS = [
27 "docs/i18n/README.zh-CN.md",
28 "docs/i18n/README.ja-JP.md",
29 "docs/i18n/README.vi.md",
30 "docs/i18n/README.id.md",
31 "docs/i18n/README.ko-KR.md",
32 "docs/i18n/README.es-419.md",
33 "docs/i18n/README.pt-BR.md",
34 "docs/i18n/README.ru.md",
35 "docs/i18n/README.uk.md",
36 "docs/i18n/README.fr.md",
37 "docs/i18n/README.de.md",
38 "docs/i18n/README.zh-TW.md",
39 "docs/i18n/README.hi.md",
40 "docs/i18n/README.tr.md",
41 "docs/i18n/README.it.md",
42 "docs/i18n/README.pl.md",
43 "docs/i18n/README.ar.md",
44 "docs/i18n/README.ca.md",
45 ]
46 STAMP_RE = re.compile(r"<!--\s*source:\s*README\.md\s+sha256:([0-9a-f]{12})\s*-->")
47 FENCE_RE = re.compile(r"```[a-z]*\n(.*?)```", re.DOTALL)
48 URL_RE = re.compile(r"\((https?://[^)\s]+|(?:docs/|\.\./)[^)\s]+|[A-Za-z0-9_./-]+\.md[^)\s]*)\)")
49 # The language-switcher line legitimately differs per translation (each file
50 # links the *other* languages), so its links are exempt from the URL check.
51 LANGUAGE_LINKS = {
52 "README.md",
53 "README.zh-CN.md",
54 "README.ja-JP.md",
55 "README.vi.md",
56 "README.id.md",
57 "README.ko-KR.md",
58 "README.es-419.md",
59 "README.pt-BR.md",
60 "README.ru.md",
61 "README.uk.md",
62 "README.fr.md",
63 "README.de.md",
64 "README.zh-TW.md",
65 "README.hi.md",
66 "README.tr.md",
67 "README.it.md",
68 "README.pl.md",
69 "README.ar.md",
70 "README.ca.md",
71 }
72
73
74 def source_stamp() -> str:
75 return hashlib.sha256(SOURCE.read_bytes()).hexdigest()[:12]
76
77
78 def fences(text: str) -> list[str]:
79 return [m.strip() for m in FENCE_RE.findall(text)]
80
81
82 def urls(text: str, document: str = "README.md") -> set[str]:
83 """Links that must agree with README.md, independent of where a translation sits.
84
85 Relative links resolve from the document's repository directory. The
86 language switcher legitimately differs per file; external URLs are compared
87 verbatim.
88 """
89 out = set()
90 for url in URL_RE.findall(text):
91 if url in LANGUAGE_LINKS or url.rsplit("/", 1)[-1] in LANGUAGE_LINKS:
92 continue
93 out.add(
94 url if url.startswith(("https://", "http://"))
95 else posixpath.normpath(posixpath.join(posixpath.dirname(document), url))
96 )
97 return out
98
99
100 def sections(text: str) -> int:
101 return len(re.findall(r"^## ", text, re.MULTILINE))
102
103
104 def main() -> int:
105 expected = source_stamp()
106 en = SOURCE.read_text()
107 en_fences = fences(en)
108 en_urls = urls(en)
109 en_sections = sections(en)
110 failures: list[str] = []
111
112 for name in TRANSLATIONS:
113 path = ROOT / name
114 if not path.exists():
115 failures.append(f"{name}: missing")
116 continue
117 text = path.read_text()
118
119 stamp = STAMP_RE.search(text)
120 if not stamp:
121 failures.append(
122 f"{name}: no source stamp — add "
123 f"'<!-- source: README.md sha256:{expected} -->'"
124 )
125 elif stamp.group(1) != expected:
126 failures.append(
127 f"{name}: stale (stamped {stamp.group(1)}, README.md is now "
128 f"{expected}) — retranslate, then update the stamp"
129 )
130
131 tr_fences = fences(text)
132 if tr_fences != en_fences:
133 failures.append(
134 f"{name}: code blocks differ from README.md "
135 f"({len(tr_fences)} vs {len(en_fences)}; commands must never "
136 f"be translated or reordered)"
137 )
138
139 missing = en_urls - urls(text, name)
140 if missing:
141 failures.append(f"{name}: missing links: {sorted(missing)[:5]}")
142
143 if sections(text) != en_sections:
144 failures.append(
145 f"{name}: {sections(text)} '##' sections vs README.md's "
146 f"{en_sections}"
147 )
148
149 if failures:
150 print("README translation check FAILED:")
151 for f in failures:
152 print(f" - {f}")
153 print(f"\nCurrent README.md stamp: sha256:{expected}")
154 return 1
155
156 print(
157 f"README translation check OK — {len(TRANSLATIONS)} translations in "
158 f"sync with README.md (sha256:{expected})"
159 )
160 return 0
161
162
163 if __name__ == "__main__":
164 sys.exit(main())
165
165 lines PYTHON