264 linhas
11 KiB
Python
264 linhas
11 KiB
Python
#!/usr/bin/env python3
|
|
"""Lists the English texts of the plugin and checks the translations in languages/*.po.
|
|
Use:
|
|
python3 -I tools/i18n-check.py check the .pot, every .po and every .mo
|
|
python3 -I tools/i18n-check.py --pot write the .pot again from the code
|
|
python3 -I tools/i18n-check.py --missing-json texts missing in the pt_PT .po, as JSON
|
|
Exit code 1 when a text is missing, the .pot or a .mo is out of date, or a text has a long dash,
|
|
a forbidden word, two languages on the same line, or different placeholders."""
|
|
import importlib.util
|
|
import json
|
|
import os
|
|
import re
|
|
import sys
|
|
import time
|
|
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
BASE = os.path.normpath(os.path.join(HERE, '..'))
|
|
|
|
|
|
def find_plugin():
|
|
for name in sorted(os.listdir(BASE)):
|
|
if name == 'tools':
|
|
continue
|
|
main = os.path.join(BASE, name, name + '.php')
|
|
if os.path.isfile(main) and 'Plugin Name:' in open(main, encoding='utf-8').read():
|
|
return name
|
|
raise SystemExit('plugin folder not found next to tools/')
|
|
|
|
|
|
DOMAIN = find_plugin()
|
|
ROOT = os.path.join(BASE, DOMAIN)
|
|
LANGS = os.path.join(ROOT, 'languages')
|
|
POT = os.path.join(LANGS, DOMAIN + '.pot')
|
|
MAIN_SRC = open(os.path.join(ROOT, DOMAIN + '.php'), encoding='utf-8').read()
|
|
PREFIX = re.search(r"define\('([A-Z0-9_]+)_VERSION'", MAIN_SRC).group(1)
|
|
|
|
sys.dont_write_bytecode = True
|
|
_spec = importlib.util.spec_from_file_location('build_mo', os.path.join(HERE, 'build-mo.py'))
|
|
build_mo = importlib.util.module_from_spec(_spec)
|
|
_spec.loader.exec_module(build_mo)
|
|
|
|
# PHP string literal, single or double quoted.
|
|
LIT = r"""('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")"""
|
|
PATTERNS = [
|
|
re.compile(r"(?:\b__|\b_e|esc_html__|esc_html_e|esc_attr__|esc_attr_e)\(\s*" + LIT + r"\s*,\s*'" + DOMAIN + "'"),
|
|
re.compile(PREFIX + r"_I18n::in\(\s*\$\w+\s*,\s*" + LIT),
|
|
re.compile(PREFIX + r"_I18n::in\('pt',\s*" + LIT),
|
|
re.compile(r"\$t\(\s*" + LIT + r"\s*\)"),
|
|
]
|
|
PLURAL = re.compile(r"(?:_n_noop\(\s*" + LIT + r"\s*,\s*" + LIT + r"\s*,|\b_n\(\s*" + LIT + r"\s*,\s*" + LIT + r"\s*,\s*[^,()]+(?:\([^()]*\))?\s*,)\s*'" + DOMAIN + "'")
|
|
# Default templates of the order alerts (keys 'sms', 'subject', 'body').
|
|
TEMPLATE = re.compile(r"'(?:sms|subject|body)'\s*=>\s*" + LIT)
|
|
TRANSLATORS = re.compile(r"/\*\s*translators:(.*?)\*/", re.S)
|
|
# House words: «ligar» is not used (say «associar»); «ligação» (a link, the connection test) is fine.
|
|
FORBIDDEN = [r'\bportal\b', r'\bloja\b', r'\bstore\b', r'\bshop\b', r'\bregistador', r'\bvigi', r'\bn[ií]vel\b',
|
|
r'\bEmail Center', r'área de cliente', r'\bligar\b']
|
|
PLACEHOLDER = r'%(?:\d\$)?[sd]'
|
|
|
|
|
|
def php_str(lit):
|
|
q = lit[0]
|
|
s = lit[1:-1]
|
|
if q == "'":
|
|
return s.replace("\\'", "'").replace('\\\\', '\\')
|
|
return s.encode('utf-8').decode('unicode_escape').encode('latin-1').decode('utf-8')
|
|
|
|
|
|
class Texts:
|
|
def __init__(self):
|
|
self.order = []
|
|
self.info = {}
|
|
|
|
def add(self, ctxt, msgid, plural=None, ref=None, comment=None):
|
|
k = (ctxt, msgid)
|
|
if k not in self.info:
|
|
self.order.append(k)
|
|
self.info[k] = {'plural': plural, 'refs': [], 'comments': []}
|
|
i = self.info[k]
|
|
if plural and not i['plural']:
|
|
i['plural'] = plural
|
|
if ref and ref not in i['refs']:
|
|
i['refs'].append(ref)
|
|
if comment and comment not in i['comments']:
|
|
i['comments'].append(comment)
|
|
|
|
|
|
def texts():
|
|
t = Texts()
|
|
# Plugin header (WordPress translates it in the plugins list).
|
|
for field in ('Plugin Name', 'Description', 'Author'):
|
|
m = re.search(r'^\s*\*\s*' + field + r':\s*(.+)$', MAIN_SRC, re.M)
|
|
if m:
|
|
t.add(None, m.group(1).strip(), ref=DOMAIN + '.php', comment=field + ' of the plugin')
|
|
for root, dirs, fs in os.walk(ROOT):
|
|
dirs.sort()
|
|
for f in sorted(fs):
|
|
if not f.endswith('.php'):
|
|
continue
|
|
path = os.path.join(root, f)
|
|
rel = os.path.relpath(path, ROOT)
|
|
src = open(path, encoding='utf-8').read()
|
|
found = []
|
|
for p in PATTERNS + ([TEMPLATE] if f == 'class-woo.php' else []):
|
|
for m in p.finditer(src):
|
|
found.append((m.start(), php_str(m.group(1)), None))
|
|
for m in PLURAL.finditer(src):
|
|
one, many = (m.group(1), m.group(2)) if m.group(1) else (m.group(3), m.group(4))
|
|
found.append((m.start(), php_str(one), php_str(many)))
|
|
notes = [(m.end(), ' '.join(m.group(1).split())) for m in TRANSLATORS.finditer(src)]
|
|
for pos, msgid, plural in sorted(found):
|
|
line = src.count('\n', 0, pos) + 1
|
|
note = None
|
|
for end, text in notes:
|
|
# A translators comment belongs to the first text after it (within a few lines).
|
|
if end <= pos and src.count('\n', end, pos) <= 3 and not any(end < p2 < pos for p2, _, _ in found):
|
|
note = 'translators: ' + text
|
|
t.add(None, msgid, plural, '%s:%d' % (rel, line), note)
|
|
# block.json: WordPress translates title, description and keywords with these contexts.
|
|
blocks = os.path.join(ROOT, 'blocks')
|
|
if os.path.isdir(blocks):
|
|
for name in sorted(os.listdir(blocks)):
|
|
rel = 'blocks/%s/block.json' % name
|
|
bj = json.load(open(os.path.join(ROOT, rel), encoding='utf-8'))
|
|
t.add('block title', bj['title'], ref=rel)
|
|
t.add('block description', bj['description'], ref=rel)
|
|
for kw in bj.get('keywords', []):
|
|
t.add('block keyword', kw, ref=rel)
|
|
return t
|
|
|
|
|
|
def po_quote(s):
|
|
s = s.replace('\\', '\\\\').replace('"', '\\"').replace('\t', '\\t')
|
|
parts = s.split('\n')
|
|
if len(parts) == 1:
|
|
return '"%s"' % s
|
|
lines = [p + '\\n' for p in parts[:-1]] + ([parts[-1]] if parts[-1] else [])
|
|
return '""\n' + '\n'.join('"%s"' % l for l in lines)
|
|
|
|
|
|
def version():
|
|
return re.search(r'^\s*\*\s*Version:\s*(\S+)', MAIN_SRC, re.M).group(1)
|
|
|
|
|
|
def plugin_name():
|
|
return re.search(r'^\s*\*\s*Plugin Name:\s*(.+)$', MAIN_SRC, re.M).group(1).strip()
|
|
|
|
|
|
def pot_text(t, date=None):
|
|
date = date or time.strftime('%Y-%m-%d %H:%M+0000', time.gmtime())
|
|
out = ['# Copyright (C) 2026 RLX Holdings',
|
|
'# This file is distributed under the same license as the %s plugin.' % plugin_name(),
|
|
'msgid ""', 'msgstr ""',
|
|
'"Project-Id-Version: %s %s\\n"' % (plugin_name(), version()),
|
|
'"POT-Creation-Date: %s\\n"' % date,
|
|
'"MIME-Version: 1.0\\n"',
|
|
'"Content-Type: text/plain; charset=UTF-8\\n"',
|
|
'"Content-Transfer-Encoding: 8bit\\n"',
|
|
'"X-Domain: %s\\n"' % DOMAIN, '']
|
|
for k in t.order:
|
|
ctxt, msgid = k
|
|
i = t.info[k]
|
|
for c in i['comments']:
|
|
out.append('#. ' + c)
|
|
if i['refs']:
|
|
out.append('#: ' + ' '.join(i['refs']))
|
|
if re.search(PLACEHOLDER, msgid):
|
|
out.append('#, php-format')
|
|
if ctxt is not None:
|
|
out.append('msgctxt ' + po_quote(ctxt))
|
|
out.append('msgid ' + po_quote(msgid))
|
|
if i['plural']:
|
|
out.append('msgid_plural ' + po_quote(i['plural']))
|
|
out += ['msgstr[0] ""', 'msgstr[1] ""']
|
|
else:
|
|
out.append('msgstr ""')
|
|
out.append('')
|
|
return '\n'.join(out)
|
|
|
|
|
|
def no_date(text):
|
|
return re.sub(r'"POT-Creation-Date: [^"]*"', '', text)
|
|
|
|
|
|
def text_errors(msgid, msgstr, where):
|
|
errors = []
|
|
for s in (msgid, msgstr):
|
|
if '\u2014' in s:
|
|
errors.append('%s: long dash in: %s' % (where, s))
|
|
for p in FORBIDDEN:
|
|
for s in (msgid, msgstr):
|
|
if re.search(p, s, re.I):
|
|
errors.append('%s: forbidden word (%s): %s' % (where, p, s))
|
|
for s in (msgid, msgstr):
|
|
if re.search(r'\S \/ \S', s) and not re.search(r'prod_\.\.\. / sandbox_', s):
|
|
errors.append('%s: two languages or options with « / » on one line: %s' % (where, s))
|
|
if sorted(re.findall(PLACEHOLDER, msgid)) != sorted(re.findall(PLACEHOLDER, msgstr)):
|
|
errors.append('%s: different placeholders: %s' % (where, msgid))
|
|
for ph in re.findall(r'\{[a-z_]+\}', msgid):
|
|
if ph not in msgstr:
|
|
errors.append('%s: %s missing in: %s' % (where, ph, msgstr))
|
|
return errors
|
|
|
|
|
|
def main():
|
|
t = texts()
|
|
if '--pot' in sys.argv:
|
|
os.makedirs(LANGS, exist_ok=True)
|
|
with open(POT, 'w', encoding='utf-8') as fh:
|
|
fh.write(pot_text(t))
|
|
print('%s: %d texts' % (os.path.relpath(POT), len(t.order)))
|
|
return 0
|
|
|
|
problems = 0
|
|
if not os.path.exists(POT) or no_date(open(POT, encoding='utf-8').read()) != no_date(pot_text(t)):
|
|
print('ERROR: the .pot is out of date: run python3 -I tools/i18n-check.py --pot')
|
|
problems += 1
|
|
|
|
pos = sorted(f for f in os.listdir(LANGS) if f.endswith('.po'))
|
|
if not pos:
|
|
print('ERROR: no .po files in', LANGS)
|
|
return 1
|
|
for name in pos:
|
|
path = os.path.join(LANGS, name)
|
|
entries = build_mo.parse_po(path)
|
|
po = {(e['ctxt'], e['id']): e for e in entries if e['id'] != ''}
|
|
missing = []
|
|
for k in t.order:
|
|
e = po.get(k)
|
|
if e is None or not e['strs'] or not all(e['strs']) or e['fuzzy']:
|
|
missing.append(k)
|
|
elif bool(e['plural']) != bool(t.info[k]['plural']):
|
|
missing.append(k)
|
|
extra = [k for k in po if k not in t.info]
|
|
errors = []
|
|
head = next((e for e in entries if e['id'] == ''), None)
|
|
if not head or 'Plural-Forms:' not in head['strs'][0] or 'charset=UTF-8' not in head['strs'][0]:
|
|
errors.append('%s: header without Plural-Forms or charset=UTF-8' % name)
|
|
for k, e in po.items():
|
|
for i, s in enumerate(e['strs']):
|
|
errors += text_errors(e['plural'] if (e['plural'] and i > 0) else k[1], s, name)
|
|
mo = path[:-3] + '.mo'
|
|
mo_ok = os.path.exists(mo) and open(mo, 'rb').read() == build_mo.compile_mo(entries)
|
|
if not mo_ok:
|
|
errors.append('%s: the .mo is out of date: run python3 -I tools/build-mo.py' % name)
|
|
if '--missing-json' in sys.argv:
|
|
if name.endswith('pt_PT.po'):
|
|
print(json.dumps([k[1] for k in missing], ensure_ascii=False, indent=1))
|
|
continue
|
|
print('%s: texts %d, translated %d, missing %d, extra %d, errors %d'
|
|
% (name, len(t.order), len(t.order) - len(missing), len(missing), len(extra), len(errors)))
|
|
for k in missing:
|
|
print(' MISSING:', ('[%s] ' % k[0] if k[0] else '') + k[1])
|
|
for k in extra:
|
|
print(' EXTRA:', ('[%s] ' % k[0] if k[0] else '') + k[1])
|
|
for e in errors:
|
|
print(' ERROR:', e)
|
|
problems += len(missing) + len(extra) + len(errors)
|
|
if '--missing-json' in sys.argv:
|
|
return 0
|
|
return 1 if problems else 0
|
|
|
|
|
|
if __name__ == '__main__':
|
|
sys.exit(main())
|