fix(ios): stabilize manual localization catalog

This commit is contained in:
weishu
2026-09-11 14:29:23 +08:00
parent 68422ed6d3
commit 765aa42653
5 changed files with 3591 additions and 2887 deletions
+8
View File
@@ -36,7 +36,15 @@ jobs:
- uses: actions/checkout@v4
- name: Show toolchain versions
run: xcodebuild -version
- name: Check manual localization catalog
env:
PYTHONDONTWRITEBYTECODE: '1'
run: |
python3 ios/scripts/localizations.py --check
python3 -m unittest discover -s ios/scripts/tests -p 'test_localizations.py'
- name: Build Hapi app for iOS Simulator
run: xcodebuild build -project ios/Hapi.xcodeproj -scheme Hapi -destination 'generic/platform=iOS Simulator' CODE_SIGNING_ALLOWED=NO
- name: Transcript layout regression tests
run: ios/scripts/test-transcript.sh
- name: Verify localization catalog was not rewritten
run: git diff --exit-code -- ios/Hapi/Resources/Localizable.xcstrings
File diff suppressed because it is too large Load Diff
+29 -3
View File
@@ -36,9 +36,35 @@ changes under `ios/**` and `shared/fixtures/**`).
### Localization catalog
`Hapi/Resources/Localizable.xcstrings` is hand-maintained. Compiler string
extraction stays disabled so opening or building the project does not rewrite
the catalog with decorative or intentionally verbatim strings.
`Hapi/Resources/Localizable.xcstrings` is **manually managed**, including every
entry's `"extractionState" : "manual"`. Keep `SWIFT_EMIT_LOC_STRINGS = NO` for the
app/extension in Debug and Release. That setting disables compiler extraction;
it does **not** prevent the Xcode editor from synchronizing or saving a catalog.
Unspecified ownership can still turn entries into `stale` during synchronization.
Use Xcode's native catalog formatting (key order, spacing, escaping), not a
generic JSON formatter. After adding or editing translations, run from repo root:
```sh
python3 ios/scripts/localizations.py --check # read-only ownership check; no Xcode needed
python3 ios/scripts/localizations.py --fix # macOS/Xcode: mark manual, normalize native format
```
The normalizer uses `xcstringstool` on a temporary copy, verifies that all keys,
translations, plural variations and comments survive, and writes only if needed.
It never deletes real entries: review/remove unwanted auto-extracted additions
before `--fix`, rather than silently making them permanent. Keep dynamic values
and decorative text verbatim in SwiftUI where they are not localization keys.
CI checks manual ownership, tests normalization idempotence, and verifies that
building/testing does not rewrite the catalog. Formatting is delegated to the
installed Xcode rather than reimplementing its ordering in Python; `--check`
does not enforce one Xcode version's byte-level formatting on another version.
After migrating an existing checkout, use **Product → Clean Build Folder** if
Xcode still synchronizes old extraction results, then rebuild/reopen and inspect
the diff. Do not hide the file with `.gitignore`, `skip-worktree`, or restore it
unconditionally: real translation edits must remain visible and committed.
### Reading typography
+105
View File
@@ -0,0 +1,105 @@
#!/usr/bin/env python3
"""Check the manual catalog, or normalize it with Xcode's own serializer.
--fix changes extraction ownership and formatting only. It never deletes real
keys or edits translations; review automatically extracted additions first.
"""
import argparse
import copy
import json
import subprocess
import sys
import tempfile
import uuid
from pathlib import Path
CATALOG = Path(__file__).resolve().parents[1] / "Hapi/Resources/Localizable.xcstrings"
def parse_catalog(content):
def unique_keys(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ValueError(f"Duplicate JSON key: {key!r}")
result[key] = value
return result
data = json.loads(content, object_pairs_hook=unique_keys)
if not isinstance(data.get("strings"), dict):
raise ValueError("Expected a string catalog with a 'strings' object")
if any(not isinstance(entry, dict) for entry in data["strings"].values()):
raise ValueError("Every string entry must be an object")
return data
def load_catalog(path):
return parse_catalog(path.read_bytes())
def manual_keys_missing(data):
return [key for key, entry in data["strings"].items() if entry.get("extractionState") != "manual"]
def normalize(data):
expected = copy.deepcopy(data)
for entry in expected["strings"].values():
entry["extractionState"] = "manual"
with tempfile.TemporaryDirectory(prefix="hapi-localizations-") as directory:
directory = Path(directory)
catalog = directory / "Localizable.xcstrings"
empty_extraction = directory / "Empty.stringsdata"
empty_extraction.write_text(json.dumps({"source": "ManualCatalog", "tables": {}, "version": 1}), encoding="utf-8")
temporary = copy.deepcopy(expected)
# sync does not serialize an unchanged catalog. An untranslated automatic
# placeholder is removed by the empty extraction, forcing a native save.
# This only exists in the temporary copy, never in the source catalog.
placeholder = f"__hapi_format_{uuid.uuid4()}__"
temporary["strings"][placeholder] = {}
catalog.write_text(json.dumps(temporary, ensure_ascii=False), encoding="utf-8")
subprocess.run([
"xcrun", "xcstringstool", "sync", str(catalog), "--stringsdata", str(empty_extraction),
], check=True)
if load_catalog(catalog) != expected:
raise ValueError("Xcode changed catalog content unexpectedly; source file was not modified")
return catalog.read_bytes()
def main():
parser = argparse.ArgumentParser(description=__doc__)
mode = parser.add_mutually_exclusive_group()
mode.add_argument("--check", action="store_true", help="Check manual ownership without rewriting (default; no Xcode needed)")
mode.add_argument("--fix", action="store_true", help="Mark all entries manual and save in native Xcode format (macOS/Xcode)")
parser.add_argument("catalog", nargs="?", type=Path, default=CATALOG)
args = parser.parse_args()
try:
before = args.catalog.read_bytes()
data = parse_catalog(before)
if args.fix:
normalized = normalize(data)
if args.catalog.read_bytes() != before:
raise ValueError("Catalog changed while normalizing; retry after Xcode finishes saving")
if normalized != before:
args.catalog.write_bytes(normalized)
print(f"Normalized {len(data['strings'])} manual entries: {args.catalog}")
else:
print("Catalog already normalized; no write needed")
else:
missing = manual_keys_missing(data)
if missing:
print("Entries without extractionState=manual:", file=sys.stderr)
for key in missing:
print(f" {key!r}", file=sys.stderr)
print("Review these keys, then run python3 ios/scripts/localizations.py --fix", file=sys.stderr)
return 1
print(f"Catalog OK: {len(data['strings'])} manually managed entries")
except (OSError, ValueError, subprocess.CalledProcessError) as error:
print(f"Localization check failed: {error}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
+85
View File
@@ -0,0 +1,85 @@
import copy
import io
import json
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import localizations
class LocalizationTests(unittest.TestCase):
def test_check_detects_automatic_entries_without_writing(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "Localizable.xcstrings"
data = {"sourceLanguage": "en", "strings": {"Test": {}}, "version": "1.0"}
path.write_text(json.dumps(data), encoding="utf-8")
before = path.read_bytes()
result = subprocess.run([sys.executable, localizations.__file__, "--check", str(path)], capture_output=True)
self.assertEqual(result.returncode, 1)
self.assertEqual(path.read_bytes(), before)
data["strings"]["Test"]["extractionState"] = "manual"
path.write_text(json.dumps(data), encoding="utf-8")
result = subprocess.run([sys.executable, localizations.__file__, "--check", str(path)], capture_output=True)
self.assertEqual(result.returncode, 0, result.stderr)
def test_duplicate_keys_are_rejected(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "Localizable.xcstrings"
path.write_text('{"strings":{"Test":{},"Test":{}}}', encoding="utf-8")
with self.assertRaisesRegex(ValueError, "Duplicate JSON key"):
localizations.load_catalog(path)
def test_fix_preserves_concurrent_edits(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "Localizable.xcstrings"
original = {"sourceLanguage": "en", "strings": {"Test": {}}, "version": "1.0"}
path.write_text(json.dumps(original), encoding="utf-8")
edited = json.dumps({**original, "strings": {"New edit": {}}}).encode("utf-8")
def normalize_while_editing(data):
self.assertEqual(data, original)
path.write_bytes(edited)
return b"must not overwrite the edit"
with patch.object(sys, "argv", [localizations.__file__, "--fix", str(path)]), \
patch.object(localizations, "normalize", side_effect=normalize_while_editing), \
patch.object(sys, "stderr", new_callable=io.StringIO) as stderr:
self.assertEqual(localizations.main(), 1)
self.assertIn("Catalog changed while normalizing", stderr.getvalue())
self.assertEqual(path.read_bytes(), edited)
@unittest.skipUnless(sys.platform == "darwin", "Native formatting requires Xcode")
def test_xcode_normalization_preserves_content_and_is_idempotent(self):
data = {
"sourceLanguage": "en",
"strings": {
"zebra": {"extractionState": "stale", "comment": "Keep this comment", "localizations": {
"zh-Hans": {"stringUnit": {"state": "translated", "value": "斑马 🦓\n"}},
}},
"%lld items": {"localizations": {"en": {"variations": {"plural": {
"one": {"stringUnit": {"state": "translated", "value": "%lld item"}},
"other": {"stringUnit": {"state": "translated", "value": "%lld items"}},
}}}}},
"https://example.com/a": {"shouldTranslate": False},
"Untranslated": {},
},
"version": "1.0",
}
original = copy.deepcopy(data)
first = localizations.normalize(data)
self.assertEqual(data, original)
parsed = json.loads(first)
for key, entry in original["strings"].items():
self.assertEqual(parsed["strings"][key], {**entry, "extractionState": "manual"})
self.assertEqual(set(parsed["strings"]), set(original["strings"]))
self.assertIn(b'"sourceLanguage" : "en"', first)
self.assertEqual(first, localizations.normalize(parsed))
if __name__ == "__main__":
unittest.main()