Skip to content

Commit 49869c9

Browse files
committed
Use polib in scripts
1 parent 716fc2e commit 49869c9

2 files changed

Lines changed: 19 additions & 134 deletions

File tree

scripts/check_markup.py

Lines changed: 14 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
common review slip: translating or mangling `:class:`int``-style markup,
88
``code`` spans, %s/{0} placeholders, or |substitution| refs.
99
10+
Requires: pip install polib
11+
1012
Usage:
1113
python3 scripts/check_markup.py library/functions.po
1214
python3 scripts/check_markup.py tutorial/*.po
@@ -16,6 +18,8 @@
1618
import sys
1719
from pathlib import Path
1820

21+
import polib
22+
1923
PATTERNS = [
2024
("sphinx role", re.compile(r":(?:\w+:)?[\w.-]+:`.*?`")),
2125
("literal/code span", re.compile(r"``.*?``")),
@@ -25,83 +29,24 @@
2529
]
2630

2731

28-
def unescape(raw: str) -> str:
29-
"""Undo PO string escaping (raw includes the surrounding quotes)."""
30-
inner = raw[1:-1]
31-
out = []
32-
i = 0
33-
while i < len(inner):
34-
c = inner[i]
35-
if c == "\\" and i + 1 < len(inner):
36-
nxt = inner[i + 1]
37-
out.append({"n": "\n", "t": "\t", '"': '"', "\\": "\\"}.get(nxt, nxt))
38-
i += 2
39-
else:
40-
out.append(c)
41-
i += 1
42-
return "".join(out)
43-
44-
45-
def parse_po(path: Path):
46-
"""Yield (location, flags, msgid, msgstr) for each entry in a .po file."""
47-
lines = path.read_text(encoding="utf-8").splitlines()
48-
i, n = 0, len(lines)
49-
50-
def read_block(keyword_line):
51-
nonlocal i
52-
parts = [unescape(keyword_line.split(" ", 1)[1].strip())]
53-
i += 1
54-
while i < n and lines[i].strip().startswith('"'):
55-
parts.append(unescape(lines[i].strip()))
56-
i += 1
57-
return "".join(parts)
58-
59-
while i < n:
60-
location, flags = "", []
61-
while i < n and lines[i].startswith("#"):
62-
if lines[i].startswith("#:"):
63-
location = lines[i][2:].strip()
64-
elif lines[i].startswith("#,"):
65-
flags = [f.strip() for f in lines[i][2:].split(",")]
66-
i += 1
67-
if i >= n or not lines[i].startswith("msgid"):
68-
i += 1
69-
continue
70-
71-
msgid = read_block(lines[i])
72-
msgid_plural = read_block(lines[i]) if i < n and lines[i].startswith("msgid_plural") else None
73-
74-
if i < n and lines[i].startswith("msgstr["):
75-
msgstrs = {}
76-
while i < n and lines[i].startswith("msgstr["):
77-
idx = int(lines[i][7:lines[i].index("]")])
78-
msgstrs[idx] = read_block(lines[i])
79-
yield location, flags, msgid, msgstrs.get(0, "")
80-
if msgid_plural is not None and 1 in msgstrs:
81-
yield location, flags, msgid_plural, msgstrs[1]
82-
continue
83-
84-
msgstr = read_block(lines[i]) if i < n and lines[i].startswith("msgstr") else ""
85-
yield location, flags, msgid, msgstr
86-
87-
8832
def check_file(path: Path) -> int:
8933
problems = 0
90-
for location, flags, msgid, msgstr in parse_po(path):
91-
if not msgid or not msgstr:
92-
continue # header entry or still untranslated
34+
po = polib.pofile(str(path))
35+
for entry in po:
36+
if entry.obsolete or not entry.msgid or not entry.msgstr:
37+
continue # obsolete entry, header, or still untranslated
9338
for label, pattern in PATTERNS:
94-
expected = pattern.findall(msgid)
39+
expected = pattern.findall(entry.msgid)
9540
if not expected:
9641
continue
97-
missing = [tok for tok in expected if tok not in msgstr]
42+
missing = [tok for tok in expected if tok not in entry.msgstr]
9843
if missing:
9944
problems += 1
100-
loc = f" ({location})" if location else ""
101-
tag = " [fuzzy]" if "fuzzy" in flags else ""
45+
loc = f" ({entry.occurrences[0][0]}:{entry.occurrences[0][1]})" if entry.occurrences else ""
46+
tag = " [fuzzy]" if entry.fuzzy else ""
10247
print(f"{path}{loc}{tag}: missing {label}: {missing}")
103-
print(f" msgid : {msgid[:100]}")
104-
print(f" msgstr: {msgstr[:100]}")
48+
print(f" msgid : {entry.msgid[:100]}")
49+
print(f" msgstr: {entry.msgstr[:100]}")
10550
return problems
10651

10752

scripts/translation_status.py

Lines changed: 5 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
translated, fuzzy, or untranslated per file, plus overall totals. Meant to
77
help a contributor quickly find files that need work.
88
9+
Requires: pip install polib
10+
911
Usage:
1012
python3 scripts/translation_status.py # whole repo, least-translated first
1113
python3 scripts/translation_status.py tutorial/ # just one directory
@@ -17,74 +19,12 @@
1719
import sys
1820
from pathlib import Path
1921

20-
21-
def unescape(raw: str) -> str:
22-
"""Undo PO string escaping (raw includes the surrounding quotes)."""
23-
inner = raw[1:-1]
24-
out = []
25-
i = 0
26-
while i < len(inner):
27-
c = inner[i]
28-
if c == "\\" and i + 1 < len(inner):
29-
nxt = inner[i + 1]
30-
out.append({"n": "\n", "t": "\t", '"': '"', "\\": "\\"}.get(nxt, nxt))
31-
i += 2
32-
else:
33-
out.append(c)
34-
i += 1
35-
return "".join(out)
36-
37-
38-
def parse_po_entries(path: Path):
39-
"""Yield (flags, msgid, msgstrs) for each entry in a .po file."""
40-
lines = path.read_text(encoding="utf-8").splitlines()
41-
i, n = 0, len(lines)
42-
43-
def read_block(keyword_line):
44-
nonlocal i
45-
parts = [unescape(keyword_line.split(" ", 1)[1].strip())]
46-
i += 1
47-
while i < n and lines[i].strip().startswith('"'):
48-
parts.append(unescape(lines[i].strip()))
49-
i += 1
50-
return "".join(parts)
51-
52-
while i < n:
53-
flags = []
54-
while i < n and lines[i].startswith("#"):
55-
if lines[i].startswith("#,"):
56-
flags = [f.strip() for f in lines[i][2:].split(",")]
57-
i += 1
58-
if i >= n or not lines[i].startswith("msgid"):
59-
i += 1
60-
continue
61-
62-
msgid = read_block(lines[i])
63-
if i < n and lines[i].startswith("msgid_plural"):
64-
read_block(lines[i]) # plural source not needed for counting
65-
66-
msgstrs = []
67-
if i < n and lines[i].startswith("msgstr["):
68-
while i < n and lines[i].startswith("msgstr["):
69-
msgstrs.append(read_block(lines[i]))
70-
elif i < n and lines[i].startswith("msgstr"):
71-
msgstrs.append(read_block(lines[i]))
72-
73-
yield flags, msgid, msgstrs
22+
import polib
7423

7524

7625
def file_stats(path: Path):
77-
translated = fuzzy = untranslated = 0
78-
for flags, msgid, msgstrs in parse_po_entries(path):
79-
if not msgid:
80-
continue # header entry
81-
if "fuzzy" in flags:
82-
fuzzy += 1
83-
elif any(m.strip() for m in msgstrs):
84-
translated += 1
85-
else:
86-
untranslated += 1
87-
return translated, fuzzy, untranslated
26+
po = polib.pofile(str(path))
27+
return len(po.translated_entries()), len(po.fuzzy_entries()), len(po.untranslated_entries())
8828

8929

9030
def collect_files(paths):

0 commit comments

Comments
 (0)