Skip to content
Closed
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
37 changes: 9 additions & 28 deletions scripts/translations/babel_update.sh
Original file line number Diff line number Diff line change
Expand Up @@ -108,33 +108,14 @@ do
fi
done

# A few UI labels ("% calculation" etc.) parse as accidentally-valid
# %-format directives (a space flag plus a conversion character), so
# babel auto-flags them python-format on every write and msgfmt then
# fatals on their translations. The app never %-formats them; strip the
# flag AFTER the update pass (babel re-adds it during the update, so
# this must run last). Line-targeted so canonical wrapping is untouched.
python3 - <<'PYEOF'
import glob

TARGETS = {'msgid "% calculation"\n', 'msgid "% of parent"\n', 'msgid "% of total"\n'}
paths = ["superset/translations/messages.pot"] + sorted(
glob.glob("superset/translations/*/LC_MESSAGES/messages.po")
)
for path in paths:
lines = open(path, encoding="utf-8").readlines()
changed = False
for i, line in enumerate(lines):
if line in TARGETS and i > 0 and lines[i - 1].startswith("#,"):
tokens = [t.strip() for t in lines[i - 1][2:].split(",")]
if "python-format" in tokens:
tokens = [t for t in tokens if t != "python-format"]
if "no-python-format" not in tokens:
tokens.append("no-python-format")
lines[i - 1] = "#, " + ", ".join(tokens) + "\n"
changed = True
if changed:
open(path, "w", encoding="utf-8").writelines(lines)
PYEOF
# Some UI labels ("% of total", "% calculation" ...) parse as
# accidentally-valid %-format directives (a space flag plus a conversion
# character), so babel auto-flags them python-format on every write and
# msgfmt then fatals on their translations. The app never %-formats them;
# strip the flag AFTER the update pass (babel re-adds it during the update,
# so this must run last). The script detects these strings rather than
# listing them, and only rewrites "#," lines, so canonical wrapping is
# untouched. Fail fast, like the marker step above.
python scripts/translations/unflag_pseudo_format.py || exit 1

cd $CURRENT_DIR
26 changes: 22 additions & 4 deletions scripts/translations/backfill_po.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,14 @@
from __future__ import annotations

import argparse
import importlib.util
import json
import re
import shutil
import subprocess
import sys
import time
from collections.abc import Callable, Iterable
from pathlib import Path
from typing import Any

Expand Down Expand Up @@ -810,9 +812,21 @@ def _process_batches(
return translated_count, failed_count


# Mirrors the post-processing at the end of babel_update.sh: Babel tags these
# msgids python-format because of the bare ``%``, but they are literal labels.
_PERCENT_LABEL_MSGIDS = {"% calculation", "% of parent", "% of total"}
def _load_is_pseudo_format() -> Callable[[Iterable[str]], bool]:
"""Return ``is_pseudo_format`` from the sibling ``unflag_pseudo_format.py``.

babel_update.sh runs that script after its update pass, and a backfill must
apply the same check or it re-flags what the script unflagged. The scripts
here are run by path rather than installed as a package, so the sibling is
loaded by file path, which works however this module itself was loaded.
"""
path = Path(__file__).resolve().with_name("unflag_pseudo_format.py")
spec = importlib.util.spec_from_file_location("unflag_pseudo_format", path)
if spec is None or spec.loader is None:
raise ImportError(f"Cannot load {path}")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module.is_pseudo_format


def normalize_catalog(po_path: Path) -> None:
Expand All @@ -827,11 +841,15 @@ def normalize_catalog(po_path: Path) -> None:
"""
from babel.messages.pofile import read_po, write_po

is_pseudo_format = _load_is_pseudo_format()
lang = po_path.parent.parent.name
with open(po_path, "rb") as f:
catalog = read_po(f, locale=lang)
# read_po re-adds python-format to labels that only look like format
# strings ("% of" reads as "% o"); drop it as babel_update.sh does.
for message in catalog:
if message.id in _PERCENT_LABEL_MSGIDS and "python-format" in message.flags:
ids = message.id if isinstance(message.id, (list, tuple)) else [message.id]
if "python-format" in message.flags and is_pseudo_format(ids):
message.flags.discard("python-format")
message.flags.add("no-python-format")
with open(po_path, "wb") as f:
Expand Down
130 changes: 130 additions & 0 deletions scripts/translations/unflag_pseudo_format.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
#!/usr/bin/env python3
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Drop the python-format flag from strings that only look like format strings.

Some UI labels ("% of total", "% calculation", help text mentioning
"% of column" ...) parse as accidentally valid %-format directives: a space
flag plus a conversion character, so "% of" reads as "% o". Babel flags them
python-format whenever it writes a catalog, and ``msgfmt --check`` then fatals
on any translation whose word after "%" is not a conversion character
("% von" reads as "% v"). The app never %-formats these strings.

An entry is unflagged when every directive Babel finds in its msgid (and
msgid_plural) carries the space flag. Real placeholders never do (``%s``,
``%d``, ``%(name)s``), and requiring *all* directives to qualify leaves a
string that mixes both kinds flagged. The flag becomes ``no-python-format``.

Two writers need this, so both share :func:`is_pseudo_format`:

* ``babel_update.sh`` runs this script after ``pybabel update``, which re-adds
the flag. Only ``#,`` lines are rewritten, so the canonical wrapping of the
template and catalogs is untouched.
* ``backfill_po.py`` applies the same check when it re-serializes a catalog.

Idempotent: re-running makes no further changes.

Usage:
python scripts/translations/unflag_pseudo_format.py [PATH ...]
# PATHs default to messages.pot and every catalog under superset/translations
"""

from __future__ import annotations

import sys
from collections.abc import Iterable
from pathlib import Path

from babel.messages.catalog import PYTHON_FORMAT

TRANSLATIONS_DIR: Path = (
Path(__file__).resolve().parent.parent.parent / "superset" / "translations"
)


def is_pseudo_format(ids: Iterable[str]) -> bool:
"""Whether every %-directive Babel finds in ``ids`` carries the space flag.

``ids`` holds the msgid and, for a plural entry, the msgid_plural. A
``%%`` counts as a directive without the space flag: a percent sign is
only escaped in a string that is %-formatted, so it keeps the flag.
"""
directives = [match for text in ids for match in PYTHON_FORMAT.finditer(text)]
return bool(directives) and all(m.group(2).startswith(" ") for m in directives)


def _entry_ids(block: list[str]) -> list[str]:
"""Return the msgid and msgid_plural texts of one entry's lines."""
ids: list[list[str]] = []
current: list[str] | None = None
for line in block:
if line.startswith(("msgid ", "msgid_plural ")):
current = [line.split(" ", 1)[1].strip()[1:-1]]
ids.append(current)
elif line.startswith('"') and current is not None:
current.append(line.strip()[1:-1])
else:
current = None
return ["".join(parts) for parts in ids]


def unflag_file(path: Path) -> int:
"""Rewrite the ``#,`` line of each pseudo-format entry in ``path``.

Entries are the blank-line separated blocks gettext and Babel write.
Returns the number of entries changed.
"""
lines = path.read_text(encoding="utf-8").splitlines(keepends=True)
changed = 0
start = 0
for end in range(len(lines) + 1):
if end < len(lines) and lines[end].strip():
continue
block = lines[start:end]
flag_index = next(
(start + i for i, line in enumerate(block) if line.startswith("#,")),
None,
)
if flag_index is not None and is_pseudo_format(_entry_ids(block)):
tokens = [t.strip() for t in lines[flag_index][2:].split(",")]
if "python-format" in tokens:
tokens = [t for t in tokens if t != "python-format"]
if "no-python-format" not in tokens:
tokens.append("no-python-format")
lines[flag_index] = "#, " + ", ".join(tokens) + "\n"
changed += 1
start = end + 1
if changed:
path.write_text("".join(lines), encoding="utf-8")
return changed


def default_paths() -> list[Path]:
"""The template followed by every language catalog, in a stable order."""
return [TRANSLATIONS_DIR / "messages.pot"] + sorted(
TRANSLATIONS_DIR.glob("*/LC_MESSAGES/messages.po")
)


def main(argv: list[str]) -> None:
paths = [Path(arg) for arg in argv] or default_paths()
total = sum(unflag_file(path) for path in paths)
print(f"Unflagged {total} pseudo-format entries across {len(paths)} files.")


if __name__ == "__main__":
main(sys.argv[1:])
16 changes: 8 additions & 8 deletions superset/translations/ar/LC_MESSAGES/messages.po
Original file line number Diff line number Diff line change
Expand Up @@ -203,22 +203,22 @@ msgid "% calculation"
msgstr "حساب ٪"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid "% of"
msgstr "% من"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid "% of column"
msgstr "% من العمود"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid "% of column total"
msgstr "% من إجمالي العمود"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid "% of grand total"
msgstr "% من الإجمالي الكلي"

Expand All @@ -229,7 +229,7 @@ msgid "% of parent"
msgstr "% من الأصل"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid "% of row total"
msgstr "% من إجمالي الصف"

Expand Down Expand Up @@ -14426,7 +14426,7 @@ msgid "Optional warning about use of this metric"
msgstr "تحذير اختياري حول استخدام هذا المقياس"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid ""
"Optional. When set together with Low color, Mid color, and High color "
"below, colors diverge from Mid color at this value toward Low color below"
Expand Down Expand Up @@ -24282,7 +24282,7 @@ msgid "Value transform"
msgstr "تحويل القيمة"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid ""
"Value: type the exact numbers used for coloring below. % of column is "
"unavailable with Server pagination enabled, since each page would compute"
Expand All @@ -24295,7 +24295,7 @@ msgstr ""
"التلقائي أثناء تفعيل ترقيم الصفحات من الخادم."

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid ""
"Value: type the exact numbers used for coloring below. % of column: type "
"a percentage of the column maximum or sum selected below, so the rule "
Expand Down
16 changes: 8 additions & 8 deletions superset/translations/ca/LC_MESSAGES/messages.po
Original file line number Diff line number Diff line change
Expand Up @@ -198,22 +198,22 @@ msgid "% calculation"
msgstr "% càlcul"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid "% of"
msgstr "% de"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid "% of column"
msgstr "% de la columna"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid "% of column total"
msgstr "% del total de la columna"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid "% of grand total"
msgstr "% del total general"

Expand All @@ -222,7 +222,7 @@ msgid "% of parent"
msgstr "%% del pare"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid "% of row total"
msgstr "% del total de la fila"

Expand Down Expand Up @@ -14094,7 +14094,7 @@ msgid "Optional warning about use of this metric"
msgstr "Advertència opcional sobre l'ús d'aquesta mètrica"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid ""
"Optional. When set together with Low color, Mid color, and High color "
"below, colors diverge from Mid color at this value toward Low color below"
Expand Down Expand Up @@ -23899,7 +23899,7 @@ msgid "Value transform"
msgstr "Transformació del valor"

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid ""
"Value: type the exact numbers used for coloring below. % of column is "
"unavailable with Server pagination enabled, since each page would compute"
Expand All @@ -23913,7 +23913,7 @@ msgstr ""
"dades mentre la paginació del servidor està activada."

# Machine-translated via backfill_po.py (claude-sonnet-5-5) [refs: de]
#, fuzzy, python-format
#, fuzzy, no-python-format
msgid ""
"Value: type the exact numbers used for coloring below. % of column: type "
"a percentage of the column maximum or sum selected below, so the rule "
Expand Down
Loading
Loading