Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 63 additions & 14 deletions scripts/i18n_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@
import os
import pathlib
import re
import stat
import sys
import tempfile
import xml.etree.ElementTree as ET
Expand Down Expand Up @@ -456,16 +457,24 @@ def _no_duplicates(pairs: list) -> dict:
return out


def load_json(path: pathlib.Path) -> tuple[dict, dict]:
def _parse_json(path: pathlib.Path, raw: str | None = None) -> tuple[dict, dict, dict]:
"""Parse path, or raw text already read from it: (tree, flat texts, inline hashes)."""
try:
tree = json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=_no_duplicates)
if raw is None:
raw = path.read_text(encoding="utf-8")
tree = json.loads(raw, object_pairs_hook=_no_duplicates)
except (json.JSONDecodeError, ParseError) as e:
raise ParseError(f"{path}: {e}") from e
if not isinstance(tree, dict):
raise ParseError(f"{path}: the top level must be an object")
out: dict = {}
hashes: dict = {}
_flatten(_drop_locale_root(tree, locale_of(path, "json")), "", out, path, hashes)
return tree, out, hashes


def load_json(path: pathlib.Path) -> tuple[dict, dict]:
_, out, hashes = _parse_json(path)
return out, hashes


Expand Down Expand Up @@ -505,6 +514,15 @@ def _write_atomic(path: pathlib.Path, text: str) -> None:
fd, name = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.")
tmp = pathlib.Path(name)
try:
# mkstemp makes the file 0600; keep the mode the file had, or for a
# new file the mode open() would give it.
try:
mode = stat.S_IMODE(path.stat().st_mode)
except FileNotFoundError:
umask = os.umask(0)
os.umask(umask)
mode = 0o666 & ~umask
os.chmod(name, mode)
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(text)
os.replace(tmp, path)
Expand Down Expand Up @@ -726,7 +744,15 @@ def _icu_argument(s: str, i: int, out: set, depth: int) -> int:
if s[j : j + 1] != "{":
raise IcuError(f"{kind} option {o.group(1)!r} needs a {{message}}")
keys.append(o.group(1))
j = _icu_scan(s, j + 1, kind != "select", out, depth + 1) + 1
if kind == "select":
# Each select keyword must keep its own placeholders: {name}
# moved from one keyword to another is a different message.
inner: set = set()
j = _icu_scan(s, j + 1, False, inner, depth + 1) + 1
out.update(inner)
out.add(("select-branch", name, o.group(1), frozenset(inner)))
else:
j = _icu_scan(s, j + 1, True, out, depth + 1) + 1
if kind == "select":
out.add(("select", name, tuple(sorted(keys))))
else:
Expand All @@ -752,16 +778,17 @@ def placeholders(text: str) -> frozenset:
out: set = set()

links: dict = {}
# In an ICU plural or select each branch may repeat a link, and other
# languages have more branches, so a link inside braces is not counted.
# In an ICU plural or select each branch may repeat a link, other
# languages have more branches, and a translation may move a link out of
# the branches. So an ICU message checks links only by destination, which
# the "tag" entries already do, and counts none.
icu = bool(_ICU_COMPLEX.search(text))

def tag(m: re.Match) -> str:
href = _HREF.search(m.group(3))
dest = (href.group(1) or href.group(2)) if href else ""
out.add(("tag", m.group(1) + m.group(2).lower(), dest))
before = text[: m.start()]
if href and not (icu and before.count("{") > before.count("}")):
if href and not icu:
# links to A, A, B differ from links to A, B, B
links[dest] = links.get(dest, 0) + 1
out.add(("link", dest, links[dest]))
Expand Down Expand Up @@ -843,6 +870,12 @@ def one(t: tuple) -> str:
return f"<{t[1]}" + (f" href={t[2]}" if t[2] else "") + ">"
if kind == "broken-braces":
return "(unbalanced braces)"
if kind == "select-branch":
return f"({t[1]} = {t[2]}: " + (_describe(t[3]) if t[3] else "no placeholder") + ")"
if kind == "link":
return f"(link {t[1]} #{t[2]})"
if kind == "plural-number":
return "(# in a plural)"
return str(t)

return ", ".join(sorted(one(t) for t in sig)) or "none"
Expand Down Expand Up @@ -878,6 +911,10 @@ def check_target(source: dict, target: dict, hashes: dict | None) -> dict:
empty = sorted(q for q, v in tgt.items() if not (v or "").strip())
found["placeholder"].append((key, f"empty plural form {', '.join(empty)}"))
s_sig, t_sig = signature(src), signature(tgt)
if ("broken-braces",) in t_sig:
# Reported even when the English is broken the same way.
found["placeholder"].append((key, "unbalanced or malformed braces"))
continue
no_other = sorted(t[1] for t in t_sig if t[0] == "no-other")
if no_other:
# Reported even when the English lacks it too: ICU needs "other".
Expand Down Expand Up @@ -935,14 +972,19 @@ def _leading_comments(path: pathlib.Path) -> str:
return "\n".join(head) + "\n" if head else ""


def write_json_inline(path: pathlib.Path, hashes: dict, checked: dict) -> None:
def write_json_inline(path: pathlib.Path, hashes: dict, checked: tuple[dict, dict]) -> None:
"""Rewrite a JSON locale file with every hashed leaf as {"text", "source"}.

`checked` is what the check read; a file that changed since is refused.
`checked` is (texts, inline hashes) as the check read them; a file that
changed since, in either, is refused. The tree that passed this comparison
is the tree that gets stamped, and a file that changed after that read is
refused too, so another editor's change is never lost or stamped.
"""
if load_json(path)[0] != checked:
raise ParseError(f"{path}: the file changed while it was being checked; run again")
tree = json.loads(path.read_text(encoding="utf-8"))
changed = ParseError(f"{path}: the file changed while it was being checked; run again")
raw = path.read_text(encoding="utf-8")
tree, texts, inline = _parse_json(path, raw)
if (texts, inline) != checked:
raise changed
root = _drop_locale_root(tree, locale_of(path, "json"))

def walk(node: dict, prefix: str) -> None:
Expand All @@ -956,6 +998,8 @@ def walk(node: dict, prefix: str) -> None:
walk(v, key)

walk(root, "")
if path.read_text(encoding="utf-8") != raw:
raise changed
_write_atomic(path, json.dumps(tree, ensure_ascii=False, indent=2) + "\n")


Expand Down Expand Up @@ -995,6 +1039,7 @@ def main(argv: list[str] | None = None) -> int:
try:
fmt = fmt or detect_format(path)
whole, inline = load(path, fmt, args.i18next_plurals)
snapshot = (dict(whole), dict(inline or {}))
# Ignored keys leave the comparison, never the file a stamp rewrites.
target = _drop_ignored(whole, args.ignore)
# An explicit --hashes-dir wins over inline hashes; the catalog
Expand Down Expand Up @@ -1022,7 +1067,11 @@ def main(argv: list[str] | None = None) -> int:
if hashes is None or (sidecar is None and fmt not in ("catalog", "json")):
print(f"error: {path}: stamping the {fmt} format needs --hashes-dir", file=sys.stderr)
return 2
n = stamp(source, target, hashes, args.restamp, args.stamp)
# A key that fails the check keeps its old hash, so a stale
# translation that is still wrong stays marked stale.
failing = check_target(source, target, None)
bad = {k for kind in ("missing", "placeholder") for k, _ in failing[kind]}
n = stamp(source, {k: v for k, v in target.items() if k not in bad}, hashes, args.restamp, args.stamp)
if n:
try:
if fmt == "catalog":
Expand All @@ -1031,7 +1080,7 @@ def main(argv: list[str] | None = None) -> int:
sidecar.parent.mkdir(parents=True, exist_ok=True)
_write_atomic(sidecar, json.dumps(hashes, ensure_ascii=False, indent=2, sort_keys=True) + "\n")
else:
write_json_inline(path, hashes, whole)
write_json_inline(path, hashes, snapshot)
except (OSError, ParseError) as e:
print(
f"error: writing the hashes for {path} failed: {e}. Earlier targets stay stamped.",
Expand Down
96 changes: 92 additions & 4 deletions tests/test_i18n_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -606,7 +606,11 @@ def test_root_level_inline_entry_is_refused(tmp_path):

def test_a_file_changed_between_check_and_stamp_is_not_written(tmp_path):
es = write(tmp_path / "es.json", json.dumps({"a": "Hola"}))
checked = ic.load_json(es)[0]
checked = ic.load_json(es)
# The control: an unchanged file is stamped.
ic.write_json_inline(es, {"a": ic.source_hash("Hello")}, checked)
assert json.loads(es.read_text())["a"] == {"text": "Hola", "source": ic.source_hash("Hello")}
checked = ic.load_json(es)
write(es, json.dumps({"a": "Adiós"}))
with pytest.raises(ic.ParseError):
ic.write_json_inline(es, {"a": ic.source_hash("Hello")}, checked)
Expand Down Expand Up @@ -751,10 +755,17 @@ def test_the_temporary_file_never_overwrites_another_file(tmp_path):
assert sorted(p.name for p in tmp_path.iterdir()) == [".es.yml.tmp", "es.yml"]


def test_links_outside_a_plural_are_still_counted(tmp_path):
def test_an_icu_message_checks_links_by_destination(tmp_path):
link = "<a href='/help'>help</a>"
en = write(tmp_path / "en.json", json.dumps({"x": f"{link} {link} {{n, plural, other {{#}}}}"}))
es = write(tmp_path / "es.json", json.dumps({"x": f"{link} {{n, plural, other {{#}}}}"}))
en = write(
tmp_path / "en.json", json.dumps({"x": f"{{n, plural, one {{# box, {link}}} other {{# boxes, {link}}}}}"})
)
# The link moved out of the branches: the same message.
es = write(tmp_path / "es.json", json.dumps({"x": f"{link}: {{n, plural, one {{# caja}} other {{# cajas}}}}"}))
assert run(en, es)[0] == 0
write(es, json.dumps({"x": "<a href='/ayuda'>ayuda</a>: {n, plural, one {# caja} other {# cajas}}"}))
assert run(en, es)[0] == 1
write(es, json.dumps({"x": "{n, plural, one {# caja} other {# cajas}}"}))
assert run(en, es)[0] == 1


Expand All @@ -765,3 +776,80 @@ def test_an_empty_plural_form_fails(tmp_path):
assert code == 1 and "empty plural form one" in out
write(es, json.dumps({"f_other": "{{count}} archivos"}))
assert run(en, es, "--i18next-plurals")[0] == 0


# --- The Desktop copy's review -----------------------------------------------


def test_a_placeholder_moved_between_select_keywords_fails(tmp_path):
en = write(tmp_path / "en.json", json.dumps({"a": "{g, select, male {He, {name}} other {They}}"}))
es = write(tmp_path / "es.json", json.dumps({"a": "{g, select, male {Él} other {Ellos, {name}}}"}))
code, out = run(en, es)
assert code == 1 and "male" in out
write(es, json.dumps({"a": "{g, select, other {Ellos} male {Él, {name}}}"}))
assert run(en, es)[0] == 0


def test_broken_braces_fail_even_when_the_english_is_broken_too(tmp_path):
en = write(tmp_path / "en.json", json.dumps({"a": "Hello {name"}))
es = write(tmp_path / "es.json", json.dumps({"a": "Hola {name"}))
code, out = run(en, es)
assert code == 1 and "braces" in out


def _edit_after_read(monkeypatch, path, n, text):
"""Rewrite path right after its n-th read, as another editor would."""
real = pathlib.Path.read_text
reads = []

def read_text(self, *a, **k):
out = real(self, *a, **k)
if self == path:
reads.append(1)
if len(reads) == n:
path.write_text(text, encoding="utf-8")
return out

monkeypatch.setattr(pathlib.Path, "read_text", read_text)


def test_a_source_hash_changed_after_the_check_is_not_overwritten(tmp_path, monkeypatch):
en = write(tmp_path / "en.json", json.dumps({"a": "Hi", "b": "Bye"}))
es = write(tmp_path / "es.json", json.dumps({"a": {"text": "Hola", "source": "111111111111"}, "b": "Adiós"}))
edited = json.dumps({"a": {"text": "Hola", "source": "222222222222"}, "b": "Adiós"})
_edit_after_read(monkeypatch, es, 1, edited)
assert ic.main([str(en), str(es), "--stamp"]) != 0
assert json.loads(es.read_text(encoding="utf-8"))["a"]["source"] == "222222222222"


def test_text_edited_during_the_stamp_is_never_stamped_current(tmp_path, monkeypatch):
en = write(tmp_path / "en.json", json.dumps({"a": "Hi"}))
es = write(tmp_path / "es.json", json.dumps({"a": "Hola"}))
# The second read is the stamp's own check; the edit lands just after it.
_edit_after_read(monkeypatch, es, 2, json.dumps({"a": "Hola {name}"}))
assert ic.main([str(en), str(es), "--stamp"]) != 0
# The edit stays, unstamped.
assert json.loads(es.read_text(encoding="utf-8")) == {"a": "Hola {name}"}


def test_a_stamp_keeps_the_file_mode(tmp_path):
en = write(tmp_path / "en.json", json.dumps({"a": "Hi"}))
es = write(tmp_path / "es.json", json.dumps({"a": "Hola"}))
es.chmod(0o644)
assert run(en, es, "--stamp")[0] == 0
assert "source" in es.read_text(encoding="utf-8")
assert es.stat().st_mode & 0o777 == 0o644


def test_restamp_leaves_a_still_broken_translation_stale(tmp_path):
d, en = catalog(tmp_path)
es = write(
d / "es.yml",
'iproyal.description:\n text: "Comparte"\n source: "000000000000"\n'
'iproyal.notes:\n text: "Paga el día"\n source: "000000000000"\n',
)
code, out = run(en, es, "--restamp", "*")
assert code == 1 and "stamped 1" in out
data = yaml.safe_load(es.read_text(encoding="utf-8"))
assert data["iproyal.notes"]["source"] == "000000000000"
assert data["iproyal.description"]["source"] == ic.source_hash("Share bandwidth")
Loading