Vigiar
1
0
Derivar
Você já tinha feito uma derivação do repositório wordpress-plugin, anteriormente
0
wordpress-plugin/tools/i18n-check.py
2026-11-28 15:28:06 +02:00

243 linhas
10 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 languages/interweb-mz-connect.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 dash (—),
a forbidden word, Portuguese and English on the same line, or different placeholders."""
import importlib.util
import json
import os
import re
import sys
import time
AQUI = os.path.dirname(os.path.abspath(__file__))
RAIZ = os.path.join(AQUI, '..', 'interweb-mz-connect')
DOMINIO = 'interweb-mz-connect'
LANGS = os.path.join(RAIZ, 'languages')
POT = os.path.join(LANGS, DOMINIO + '.pot')
sys.dont_write_bytecode = True
_spec = importlib.util.spec_from_file_location('build_mo', os.path.join(AQUI, '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"""('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")"""
PADROES = [
re.compile(r"(?:\b__|\b_e|esc_html__|esc_html_e|esc_attr__|esc_attr_e)\(\s*" + LIT + r"\s*,\s*'" + DOMINIO + "'"),
re.compile(r"INTERWEB_MZ_CONNECT_I18n::in\(\s*\$\w+\s*,\s*" + LIT),
re.compile(r"INTERWEB_MZ_CONNECT_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*,\s*'" + DOMINIO + "'")
# Default templates of the order alerts (keys 'sms', 'subject', 'body').
TEMPLATE = re.compile(r"'(?:sms|subject|body)'\s*=>\s*" + LIT)
TRADUTORES = re.compile(r"/\*\s*translators:(.*?)\*/", re.S)
# «ligar» is forbidden (say «associar»); «ligação» (a link, the connection test) is allowed.
PROIBIDAS = [r'\bportal\b', r'\bloja\b', r'\bregistador', r'\bvigi', r'\bn[ií]vel\b', r'\bEmail Center', r'área de cliente', r'\bligar\b']
MARCADOR = 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 Textos:
def __init__(self):
self.ordem = []
self.info = {}
def add(self, ctxt, msgid, plural=None, ref=None, comment=None):
k = (ctxt, msgid)
if k not in self.info:
self.ordem.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 textos():
t = Textos()
# Plugin header (WordPress translates it in the plugins list).
main = open(os.path.join(RAIZ, DOMINIO + '.php'), encoding='utf-8').read()
for campo in ('Plugin Name', 'Description', 'Author'):
m = re.search(r'^\s*\*\s*' + campo + r':\s*(.+)$', main, re.M)
if m:
t.add(None, m.group(1).strip(), ref=DOMINIO + '.php', comment=campo + ' of the plugin')
for raiz, dirs, fs in os.walk(RAIZ):
dirs.sort()
for f in sorted(fs):
if not f.endswith('.php'):
continue
path = os.path.join(raiz, f)
rel = os.path.relpath(path, RAIZ)
src = open(path, encoding='utf-8').read()
achados = []
for p in PADROES + ([TEMPLATE] if f == 'class-woo.php' else []):
for m in p.finditer(src):
achados.append((m.start(), php_str(m.group(1)), None))
for m in PLURAL.finditer(src):
achados.append((m.start(), php_str(m.group(1)), php_str(m.group(2))))
notas = [(m.end(), ' '.join(m.group(1).split())) for m in TRADUTORES.finditer(src)]
for pos, msgid, plural in sorted(achados):
linha = src.count('\n', 0, pos) + 1
nota = None
for fim, texto in notas:
# A translators comment belongs to the first text after it (within a few lines).
if fim <= pos and src.count('\n', fim, pos) <= 3 and not any(fim < p2 < pos for p2, _, _ in achados):
nota = 'translators: ' + texto
t.add(None, msgid, plural, '%s:%d' % (rel, linha), nota)
# block.json: WordPress translates title, description and keywords with these contexts.
for nome in sorted(os.listdir(os.path.join(RAIZ, 'blocks'))):
rel = 'blocks/%s/block.json' % nome
bj = json.load(open(os.path.join(RAIZ, 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')
partes = s.split('\n')
if len(partes) == 1:
return '"%s"' % s
linhas = [p + '\\n' for p in partes[:-1]] + ([partes[-1]] if partes[-1] else [])
return '""\n' + '\n'.join('"%s"' % l for l in linhas)
def versao():
main = open(os.path.join(RAIZ, DOMINIO + '.php'), encoding='utf-8').read()
return re.search(r'^\s*\*\s*Version:\s*(\S+)', main, re.M).group(1)
def pot_text(t, data=None):
data = data 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 Interweb Mozambique Connect plugin.',
'msgid ""', 'msgstr ""',
'"Project-Id-Version: Interweb Mozambique Connect %s\\n"' % versao(),
'"POT-Creation-Date: %s\\n"' % data,
'"MIME-Version: 1.0\\n"',
'"Content-Type: text/plain; charset=UTF-8\\n"',
'"Content-Transfer-Encoding: 8bit\\n"',
'"X-Domain: %s\\n"' % DOMINIO, '']
for k in t.ordem:
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(MARCADOR, 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 sem_data(texto):
return re.sub(r'"POT-Creation-Date: [^"]*"', '', texto)
def erros_de_texto(msgid, msgstr, onde):
erros = []
for s in (msgid, msgstr):
if '\u2014' in s:
erros.append('%s: travessão em: %s' % (onde, s))
for p in PROIBIDAS:
for s in (msgid, msgstr):
if re.search(p, s, re.I):
erros.append('%s: palavra proibida (%s): %s' % (onde, p, s))
for s in (msgid, msgstr):
if re.search(r'\S \/ \S', s) and not re.search(r'prod_\.\.\. / sandbox_', s):
erros.append('%s: duas línguas ou opções com « / » na mesma linha: %s' % (onde, s))
if sorted(re.findall(MARCADOR, msgid)) != sorted(re.findall(MARCADOR, msgstr)):
erros.append('%s: marcadores diferentes: %s' % (onde, msgid))
for ph in re.findall(r'\{[a-z_]+\}', msgid):
if ph not in msgstr:
erros.append('%s: falta %s em: %s' % (onde, ph, msgstr))
return erros
def main():
t = textos()
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 textos' % (os.path.relpath(POT), len(t.ordem)))
return 0
problemas = 0
if not os.path.exists(POT) or sem_data(open(POT, encoding='utf-8').read()) != sem_data(pot_text(t)):
print('ERRO: o .pot não está em dia: corra python3 -I tools/i18n-check.py --pot')
problemas += 1
pos = sorted(f for f in os.listdir(LANGS) if f.endswith('.po'))
if not pos:
print('ERRO: não há ficheiros .po em', LANGS)
return 1
for nome in pos:
caminho = os.path.join(LANGS, nome)
entradas = build_mo.parse_po(caminho)
po = {(e['ctxt'], e['id']): e for e in entradas if e['id'] != ''}
falta = []
for k in t.ordem:
e = po.get(k)
if e is None or not e['strs'] or not all(e['strs']) or e['fuzzy']:
falta.append(k)
elif bool(e['plural']) != bool(t.info[k]['plural']):
falta.append(k)
sobra = [k for k in po if k not in t.info]
erros = []
cab = next((e for e in entradas if e['id'] == ''), None)
if not cab or 'Plural-Forms:' not in cab['strs'][0] or 'charset=UTF-8' not in cab['strs'][0]:
erros.append('%s: cabeçalho sem Plural-Forms ou sem charset=UTF-8' % nome)
for k, e in po.items():
for i, s in enumerate(e['strs']):
erros += erros_de_texto(e['plural'] if (e['plural'] and i > 0) else k[1], s, nome)
mo = caminho[:-3] + '.mo'
mo_ok = os.path.exists(mo) and open(mo, 'rb').read() == build_mo.compile_mo(entradas)
if not mo_ok:
erros.append('%s: o .mo não está em dia: corra python3 -I tools/build-mo.py' % nome)
if '--missing-json' in sys.argv:
if nome.endswith('pt_PT.po'):
print(json.dumps([k[1] for k in falta], ensure_ascii=False, indent=1))
continue
print('%s: textos %d, traduzidos %d, em falta %d, a mais %d, erros %d'
% (nome, len(t.ordem), len(t.ordem) - len(falta), len(falta), len(sobra), len(erros)))
for k in falta:
print(' FALTA:', ('[%s] ' % k[0] if k[0] else '') + k[1])
for k in sobra:
print(' A MAIS:', ('[%s] ' % k[0] if k[0] else '') + k[1])
for e in erros:
print(' ERRO:', e)
problemas += len(falta) + len(sobra) + len(erros)
if '--missing-json' in sys.argv:
return 0
return 1 if problemas else 0
if __name__ == '__main__':
sys.exit(main())