Vigiar
1
0
Derivar
Você já tinha feito uma derivação do repositório wordpress-sms-center-plugin, anteriormente
0
wordpress-sms-center-plugin/tools/build-mo.py
2026-12-01 13:25:59 +02:00

152 linhas
5 KiB
Python

#!/usr/bin/env python3
"""Compiles every languages/*.po of the plugin into the .mo file next to it (standard library only).
Use: python3 -I tools/build-mo.py
Fuzzy and untranslated entries are left out, as msgfmt does. Run it again after any change to a .po."""
import ast
import glob
import os
import struct
import sys
LANGS = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'mozout-sms-center', 'languages')
def _unquote(line):
return ast.literal_eval(line) if line.startswith('"') else ''
def parse_po(path):
"""Returns a list of entries: dict with ctxt, id, plural, strs (list), fuzzy, comments, refs, extracted."""
entries = []
cur = None
field = None
def new():
return {'ctxt': None, 'id': None, 'plural': None, 'strs': {}, 'fuzzy': False,
'comments': [], 'refs': [], 'extracted': [], 'flags': []}
def flush():
if cur is not None and cur['id'] is not None:
n = max(cur['strs']) + 1 if cur['strs'] else 0
cur['strs'] = [cur['strs'].get(i, '') for i in range(n)]
entries.append(cur)
with open(path, encoding='utf-8') as fh:
lines = fh.read().split('\n')
for raw in lines:
line = raw.strip()
if not line:
if cur is not None and cur['id'] is not None:
flush()
cur = None
field = None
continue
if line.startswith('#'):
if cur is None or cur['id'] is not None:
if cur is not None:
flush()
cur = new()
if line.startswith('#,'):
flags = [f.strip() for f in line[2:].split(',')]
cur['flags'] += flags
cur['fuzzy'] = cur['fuzzy'] or 'fuzzy' in flags
elif line.startswith('#:'):
cur['refs'] += line[2:].split()
elif line.startswith('#.'):
cur['extracted'].append(line[2:].strip())
elif line.startswith('#~'):
pass
else:
cur['comments'].append(line[1:].strip())
continue
if cur is None:
cur = new()
if line.startswith('msgctxt '):
if cur['id'] is not None:
flush()
cur = new()
field = ('ctxt', None)
cur['ctxt'] = _unquote(line[8:].strip())
elif line.startswith('msgid_plural '):
field = ('plural', None)
cur['plural'] = _unquote(line[13:].strip())
elif line.startswith('msgid '):
if cur['id'] is not None:
flush()
cur = new()
field = ('id', None)
cur['id'] = _unquote(line[6:].strip())
elif line.startswith('msgstr['):
i = int(line[7:line.index(']')])
field = ('strs', i)
cur['strs'][i] = _unquote(line[line.index(']') + 1:].strip())
elif line.startswith('msgstr '):
field = ('strs', 0)
cur['strs'][0] = _unquote(line[7:].strip())
elif line.startswith('"') and field:
name, i = field
if name == 'strs':
cur['strs'][i] += _unquote(line)
else:
cur[name] = (cur[name] or '') + _unquote(line)
else:
raise ValueError('%s: line not understood: %s' % (path, raw))
flush()
return entries
def compile_mo(entries):
"""Bytes of a .mo file (little endian, no hash table: WordPress does not need it)."""
pairs = {}
for e in entries:
if e['fuzzy'] and e['id'] != '':
continue
if not e['strs'] or not all(e['strs']) and e['id'] != '':
continue
key = e['id']
if e['plural'] is not None:
key += '\x00' + e['plural']
if e['ctxt'] is not None:
key = e['ctxt'] + '\x04' + key
pairs[key.encode('utf-8')] = '\x00'.join(e['strs']).encode('utf-8')
keys = sorted(pairs)
n = len(keys)
ids = b''
strs = b''
id_tab = []
str_tab = []
for k in keys:
id_tab.append((len(k), len(ids)))
ids += k + b'\x00'
v = pairs[k]
str_tab.append((len(v), len(strs)))
strs += v + b'\x00'
header = 7 * 4
o_ids = header
o_strs = o_ids + n * 8
o_data = o_strs + n * 8
out = struct.pack('<7I', 0x950412de, 0, n, o_ids, o_strs, 0, o_data)
for length, off in id_tab:
out += struct.pack('<2I', length, o_data + off)
for length, off in str_tab:
out += struct.pack('<2I', length, o_data + len(ids) + off)
return out + ids + strs
def main():
files = sorted(glob.glob(os.path.join(LANGS, '*.po')))
if not files:
print('no .po files in', LANGS)
return 1
for po in files:
entries = parse_po(po)
data = compile_mo(entries)
mo = po[:-3] + '.mo'
with open(mo, 'wb') as fh:
fh.write(data)
print('%s: %d entries' % (os.path.basename(mo), struct.unpack('<I', data[8:12])[0]))
return 0
if __name__ == '__main__':
sys.exit(main())