Repository navigation
Conversation
87e1b13 to
3035fe1
Compare
|
Thanks for this — the sync is the right place for the check, and it catches all four cases from #14664. One gap I'd like to suggest closing while the check is being added: placeholders that a translation drops are explicitly allowed ( To be upfront: Sphinx has none of these today. I ran the check below against all 71 catalogues on this branch and it reports zero dropped placeholders — only the four known el/fa errors. So this is not a fix for existing data, it is about what the next Transifex sync can bring in. In the other projects I scanned for #14664 dropped placeholders were by far the most common kind (1352 of 1439 findings in Laravel-Lang), so I'd expect them to show up here sooner or later too, and with this PR as it stands nothing would point at them. The suggestion, as a patch on top of this branch (diff below):
Feel free to take it into this PR as is, adjust it, or tell me if you'd rather keep this PR minimal — then I can open it as a follow-up after this one lands. (The patch and tests were prepared with Claude Code and run locally on Python 3.13.) Patch on top of 3035fe1diff --git a/CHANGES.rst b/CHANGES.rst
index fbc9ae2..b1205c4 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -21,7 +21,8 @@ Testing
* #14664: Check that the format placeholders of every translation match
its msgid when pulling catalogues from Transifex, and exclude failing
- catalogues from the automated update pull request.
+ catalogues from the automated update pull request. Placeholders that a
+ translation drops are reported as warnings.
Patch by Shash Bhaskar
* #14690: Fix test isolation issues caused by shared test directories and
diff --git a/tests/test_babel_runner_check.py b/tests/test_babel_runner_check.py
index 09d248e..0a79d64 100644
--- a/tests/test_babel_runner_check.py
+++ b/tests/test_babel_runner_check.py
@@ -105,6 +105,48 @@ def test_each_plural_form_is_checked() -> None:
]
+def _missing(msgid: str | tuple[str, str], msgstr: str | tuple[str, ...]) -> list[str]:
+ return babel_runner._missing_placeholders(Message(msgid, msgstr))
+
+
+def test_missing_placeholder_is_a_warning() -> None:
+ assert _missing('bad value {name!r}', 'valeur incorrecte') == [
+ "placeholder 'name' from the msgid is missing in translation"
+ ]
+
+
+def test_missing_percent_placeholder_is_a_warning() -> None:
+ assert _missing('bad value %(name)r', 'valeur incorrecte') == [
+ "placeholder 'name' from the msgid is missing in translation"
+ ]
+
+
+def test_complete_translation_has_no_missing_placeholders() -> None:
+ assert _missing('bad value {name!r}', 'mauvaise valeur {name!r}') == []
+
+
+def test_reordered_placeholders_are_not_missing() -> None:
+ assert _missing('{name} in {path}', 'dans {path}: {name}') == []
+
+
+def test_plural_placeholder_needs_only_one_form() -> None:
+ # the singular form may legitimately omit the count
+ msgid = 'one file in {path}', '{n} files in {path}'
+ msgstr = 'un fichier dans {path}', '{n} fichiers dans {path}'
+ assert _missing(msgid, msgstr) == []
+ assert _missing(msgid, ('un fichier', '{n} fichiers')) == [
+ "placeholder 'path' from the msgid is missing in translation"
+ ]
+
+
+def test_positional_placeholders_are_not_compared() -> None:
+ assert _missing('bad value {}', 'valeur incorrecte') == []
+
+
+def test_damaged_syntax_is_not_also_reported_missing() -> None:
+ assert _missing('bad value {name}', 'valeur incorrecte {name]') == []
+
+
def test_run_check_reports_and_excludes(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
@@ -140,13 +182,49 @@ def fake_git(*args: Any, **kwargs: Any) -> int:
monkeypatch.setattr(babel_runner, '_write_pr_body_line', lambda m: None)
# plain mode: reports the damaged catalogue and exits non-zero
- with caplog.at_level('ERROR', logger='babel'), pytest.raises(SystemExit) as exc:
+ with caplog.at_level('WARNING', logger='babel'), pytest.raises(SystemExit) as exc:
babel_runner.run_check()
assert exc.value.code == 1
assert any('el' in record.getMessage() for record in caplog.records)
+ # the renamed placeholder is an error only, not also a missing one
+ assert not [r for r in caplog.records if r.levelname == 'WARNING']
# exclusion mode: reverts the damaged catalogue and exits cleanly
babel_runner.run_check(exclude_failing=True)
assert len(reverted) == 1
assert Path(reverted[0]).name == 'sphinx.po'
assert Path(reverted[0]).parent.parent.name == 'el'
+
+
+def test_run_check_warns_without_excluding(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
+) -> None:
+ d = tmp_path / 'sphinx' / 'locale' / 'el' / 'LC_MESSAGES'
+ d.mkdir(parents=True)
+ (d / 'sphinx.po').write_text(
+ dedent(
+ """\
+ msgid "value '{name}'"
+ msgstr "valeur"
+ """
+ ),
+ encoding='utf-8',
+ )
+
+ def fake_git(*_args: Any, **_kwargs: Any) -> int:
+ pytest.fail('a catalogue with only missing placeholders was reverted')
+
+ body: list[str] = []
+ monkeypatch.setattr(babel_runner, 'ROOT', tmp_path)
+ monkeypatch.setattr(babel_runner.subprocess, 'run', fake_git)
+ monkeypatch.setattr(babel_runner, '_write_pr_body_line', body.append)
+
+ # neither mode fails or excludes the catalogue
+ with caplog.at_level('WARNING', logger='babel'):
+ babel_runner.run_check()
+ babel_runner.run_check(exclude_failing=True)
+ warnings = [r for r in caplog.records if r.levelname == 'WARNING']
+ assert len(warnings) == 2
+ assert "'name'" in warnings[0].getMessage()
+ assert '* el: 1 placeholder' in body
+ assert '## Catalogues excluded from this update' not in body
diff --git a/utils/babel_runner.py b/utils/babel_runner.py
index 25d0c82..ac4885f 100644
--- a/utils/babel_runner.py
+++ b/utils/babel_runner.py
@@ -19,7 +19,8 @@
Transifex largely do not, so damaged placeholders slip through it
(#14664). With "--exclude-failing" (used by the Transifex sync),
failing catalogues are reverted so that the automated pull request
- excludes them, and they are listed in its body.
+ excludes them, and they are listed in its body. Placeholders that a
+ translation drops are reported as warnings and do not fail the check.
"""
from __future__ import annotations
@@ -353,17 +354,72 @@ def _placeholder_errors(message: Message) -> list[str]:
return errors
+def _missing_placeholders(message: Message) -> list[str]:
+ """Return placeholders of the msgid that the translation drops.
+
+ A dropped placeholder does not break formatting, so it is reported
+ as a warning rather than an error: the message still renders, but
+ loses the information the placeholder carried (a name, a path, ...).
+
+ For plural messages a placeholder only has to appear in one of the
+ translated forms, since a singular form may legitimately omit the
+ count. Positional ``{}`` fields are not compared.
+ """
+ msgid = message.id
+ if isinstance(msgid, (list, tuple)):
+ msgid_forms = [msgid[0], msgid[1]]
+ else:
+ msgid_forms = [msgid]
+
+ required: set[str] = set()
+ for form in msgid_forms:
+ try:
+ required |= _brace_format_fields(form)
+ except ValueError:
+ return []
+ required |= _percent_format_fields(''.join(msgid_forms))
+ required.discard('')
+
+ msgstr = message.string
+ if msgstr is None:
+ return []
+ if isinstance(msgstr, (list, tuple)):
+ msgstr_forms = [form for form in msgstr if form]
+ else:
+ msgstr_forms = [msgstr]
+ if not msgstr_forms:
+ return []
+
+ used: set[str] = set()
+ for form in msgstr_forms:
+ try:
+ used |= _brace_format_fields(form)
+ except ValueError:
+ # invalid syntax is already reported by _placeholder_errors()
+ return []
+ used |= _percent_format_fields(form)
+
+ return [
+ f'placeholder {name!r} from the msgid is missing in translation'
+ for name in sorted(required - used)
+ ]
+
+
def run_check(exclude_failing: bool = False) -> None:
"""Check catalogue placeholder consistency.
With *exclude_failing*, revert catalogues that fail the check so the
Transifex sync excludes them from the automated pull request, and
record them in its body.
+
+ Placeholders that a translation drops are reported as warnings: they
+ neither fail the check nor exclude the catalogue.
"""
log = _get_logger()
directory = ROOT / 'sphinx' / 'locale'
excluded: list[str] = []
+ missing: dict[str, int] = {}
failures = 0
for locale in sorted(directory.iterdir()):
@@ -378,7 +434,8 @@ def run_check(exclude_failing: bool = False) -> None:
for message in catalogue:
if not message.id or not message.string or message.fuzzy:
continue
- for error in _placeholder_errors(message):
+ errors = _placeholder_errors(message)
+ for error in errors:
locale_errors += 1
log.error(
'error: %s:%d: %s\nerror: in message string: %r',
@@ -387,6 +444,19 @@ def run_check(exclude_failing: bool = False) -> None:
error,
message.string,
)
+ if errors:
+ # a renamed placeholder is already an error; do not also
+ # report the original name as missing
+ continue
+ for warning in _missing_placeholders(message):
+ missing[locale.name] = missing.get(locale.name, 0) + 1
+ log.warning(
+ 'warning: %s:%d: %s\nwarning: in message string: %r',
+ po_file.relative_to(ROOT),
+ message.lineno,
+ warning,
+ message.string,
+ )
if not locale_errors:
continue
@@ -409,6 +479,13 @@ def run_check(exclude_failing: bool = False) -> None:
for locale_name in excluded:
_write_pr_body_line(f'* {locale_name}')
+ if missing:
+ _write_pr_body_line('## Translations missing placeholders')
+ _write_pr_body_line('')
+ for locale_name, count in missing.items():
+ s = 's' if count != 1 else ''
+ _write_pr_body_line(f'* {locale_name}: {count} placeholder{s}')
+
if failures and not exclude_failing:
raise SystemExit(1)
|
Extension contributed by katerynaKhar in the PR discussion: report msgid placeholders that a translation drops as warnings, without failing or excluding the catalogue, so the sync PR body surfaces them for a Transifex-side fix. Co-authored-by: katerynaKhar <[email protected]>
|
Taking this into the PR - thanks for writing it out. The error path is untouched, so the existing tests carry over as they are, and I re-ran the full battery on the patch: 22 tests pass, the type checkers and ruff are clean, and the check over all 71 catalogues reports exactly the four known errors and zero dropped placeholders, matching your numbers. The plural one-form rule and not double-reporting renamed placeholders were exactly the details I would have got wrong. Commit pushed with you as co-author. |
m-aciek
left a comment
There was a problem hiding this comment.
One correction to the PR description: msgfmt --check-format does not require gettext ≥ 0.23 to validate python-brace-format messages. Gettext 0.21 already includes that validator; 0.23 added f-string recognition to xgettext, which is separate from PO validation.
I also pulled the source POT and all 68 translation catalogues from Transifex and found no missing format flags relative to the POT. Could you update the description to reflect this?
Keeping validation in Python is still reasonable, but we could reuse Catalog.check() for percent formatting and limit the custom checker to brace formatting. Once Babel #333 is addressed, we could remove that custom checker too.
| for message in catalogue: | ||
| if not message.id or not message.string or message.fuzzy: | ||
| continue | ||
| errors = _placeholder_errors(message) |
There was a problem hiding this comment.
Could we limit the brace-format check to messages flagged python-brace-format and leave percent-format validation to the existing Catalog.check() call? I pulled the source POT and all 68 translation catalogues from Transifex: none were missing the format flags present in the POT. The claim that downloaded catalogues largely lack these flags therefore seems inaccurate.
This would also keep our custom check limited to the functionality Babel currently lacks. Once Babel supports brace-format validation (python-babel/babel#333), we could rely on Catalog.check() for both formats and remove it.
| Raises ``ValueError`` for invalid brace-format syntax. | ||
| """ | ||
| fields: set[str] = set() | ||
| for _literal, field_name, _spec, _conversion in string.Formatter().parse(text): |
There was a problem hiding this comment.
Formatter.parse() alone does not validate conversions or collect nested fields. For example, translating {name} as either {name!x} or {name:{unknown}} passes this check but fails at runtime. Could we validate conversion characters and recursively check fields inside format specifications?
| locale_errors, | ||
| ) | ||
| subprocess.run( | ||
| ('git', 'checkout', '--', str(po_file)), # ruff: ignore[start-process-with-partial-path] |
There was a problem hiding this comment.
If an invalid catalogue belongs to a newly downloaded language, its PO file is untracked. git checkout -- <path> then fails and aborts synchronization, including valid updates to other languages. Could we remove invalid new catalogues and restore existing ones?
…drop invalid new catalogues
|
Thanks for the really thorough review, and especially for pulling the source POT and all 68 catalogues - that settled the design question. You were right about the flags: every brace-format message carries |
There was a problem hiding this comment.
run_check() locates catalogues through ROOT, but _is_tracked() and the git checkout call run Git from the caller's current directory. If someone runs python /path/to/sphinx/utils/babel_runner.py check --exclude-failing from outside the checkout, git ls-files exits 128; _is_tracked() treats its empty stdout as “untracked”, and this branch unlinks a tracked .po file. Please run both Git commands with cwd=ROOT and check the ls-files exit status before deciding to delete a catalogue. An outside-cwd test would cover this case.
There was a problem hiding this comment.
Thanks for the update. I rechecked the current patch: both Git calls now run with cwd=ROOT, ls-files failures stop the check, and the outside-checkout regression test covers the tracked-catalogue case. This addresses my concern.
|
Confirmed — I reproduced exactly this: run from outside the checkout, git ls-files exits 128 and the empty output was read as untracked, so --exclude-failing unlinked a tracked catalogue instead of reverting it. Both git commands now run with cwd=ROOT, and _is_tracked() raises on a non-zero ls-files exit rather than treating empty output as untracked, so nothing is deleted when git can't answer. I've added a test that drives the check from outside the checkout root and one for the failing ls-files case. |
m-aciek
left a comment
There was a problem hiding this comment.
Thanks for working on this and addressing the earlier feedback. I found two more cases worth covering, particularly positional argument reordering, which translators may need.
| fields: set[str] = set() | ||
| for _literal, field_name, spec, conversion in string.Formatter().parse(text): | ||
| if field_name is not None: | ||
| fields.add(field_name) |
There was a problem hiding this comment.
Could we support explicit positional indices for automatically numbered fields? Translators may need them to reorder arguments. For example, "File {} was created by user {}." can naturally become "Użytkownik {1} utworzył plik {0}.". Both work with the same arguments, but the checker currently rejects the translation. With --exclude-failing, this would discard an otherwise valid catalogue update.
| if spec: | ||
| fields |= _brace_format_fields(spec) |
There was a problem hiding this comment.
The recursive parsing accepts {name:{name:{name}}}, so run_check() succeeds without warnings, but str.format() raises ValueError: Max string recursion exceeded. Could we enforce the runtime nesting limit here?
…t in the catalogue check
|
Thanks for catching both of these. The checker now works out the argument list the msgid implies and accepts anything |
…limit
str.format() expands a format specification only when it holds a
replacement field - CPython's formatter decrements its recursion depth
(from an initial 2) only for a specification marked as needing
expansion. A literal specification inside a specification therefore
still formats ("{a:{b:>5}}"), and only a second field-bearing level,
as in "{a:{b:{c}}}", raises "ValueError: Max string recursion
exceeded" at runtime; the check now rejects exactly that. Also drop
the _brace_format_fields helper, which _brace_format_info replaced.
|
Small correction to my earlier reply: re-testing the recursion boundary against CPython I found the nesting check was still one case too strict. |
|
Preferable solution would be to bring the check for |
|
Fair — and for what it's worth there's been movement on the Babel side already: |
Following the discussion on #14664 and #14666 (closed): this adds a placeholder check to the Transifex sync so damaged catalogues can no longer land in the automated update PR.
This is the placement the earlier attempt converged on: #12394 was closed because a CI check on ordinary pull requests mostly guards against direct .po edits, which is not how translations are submitted, while the same check at the Transifex sync catches every catalogue it pulls in (see also sphinx-doc/sphinx-doc-translations#36, which proposed a
babel_runner.py checkcommand with no gettext dependency).I've corrected two claims in this description. The catalogues do carry format flags - the POT and every catalogue mark all 11 brace-format messages
python-brace-formatand all 423 printf-style messagespython-format, so m-aciek's Transifex pull finding no missing flags matches what's checked in; my "11 of ~870 entries carry almost no flags" line was me misreading my own measurement, since those 11 flagged entries are all the brace-format messages there are. The actual reason the #14664 damage slipped through is that babel'sCatalog.check()has no checker forpython-brace-formatmessages at all (python-babel/babel#333) - it reports zero errors on the damaged el and fa catalogues even though those entries carry the flag. And on msgfmt,--check-formathas validated python-brace-format since gettext 0.21, not 0.23; 0.23 added f-string recognition to xgettext. The check is still needed in the sync, since msgfmt isn't part of it and babel won't catch this until #333 lands, but it's now scoped like babel itself: brace validation for flagged messages only, percent validation delegated to babel's ownMessage.check().In the sync workflow the check runs between the pull and the compile with
--exclude-failing: a failing catalogue is reverted so the automated PR excludes it, and the locale is listed in the PR body alongside the existing "Babel catalogue errors" section. Without the flag the check exits non-zero, so it can gate other CI paths later.Measured against all 71 catalogues on current master, the check reports exactly the four damaged messages from #14664 (three in el, one in fa) and nothing else.
AI Disclosure
Per the PR template: the opencode coding agent (GLM) was used in preparing this pull request ΓÇö to survey the catalogue damage from #14664, implement the placeholder check, and write the tests. I reviewed the change and validated it locally (the new tests and
tests/test_intl/test_locale.pygreen;ruff checkandruff format --checkclean; the check flags exactly the four damaged messages across all 71 catalogues and nothing else).The dropped-placeholder warning extension was contributed by katerynaKhar in the PR discussion; per her note there, her patch and tests were prepared with Claude Code. I reviewed the extension and re-verified it locally (same battery as above).