sisyo 1.6.8 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +5 -1
  2. package/bin/known-hashes.json +95 -7
  3. package/bin/sisyo.js +285 -285
  4. package/package.json +30 -30
  5. package/templates/.claude/rules/agents-and-tests.md +24 -0
  6. package/templates/.claude/skills/g6-style/SKILL.md +125 -0
  7. package/templates/.claude/skills/g6-style/references/checks.md +58 -0
  8. package/templates/.claude/skills/g6-style/references/imagery.md +103 -0
  9. package/templates/.claude/skills/g6-style/references/motion.md +121 -0
  10. package/templates/.claude/skills/g6-style/references/sections.md +263 -0
  11. package/templates/.claude/skills/g6-style/references/tokens.md +197 -0
  12. package/templates/.claude/skills/hindsight/SKILL.md +13 -10
  13. package/templates/.claude/skills/i18n-multilang/SKILL.md +153 -0
  14. package/templates/.claude/skills/i18n-multilang/assets/languages.json +47 -0
  15. package/templates/.claude/skills/i18n-multilang/assets/plural-vectors.json +46 -0
  16. package/templates/.claude/skills/i18n-multilang/assets/project/README.md +17 -0
  17. package/templates/.claude/skills/i18n-multilang/assets/project/gitattributes.txt +6 -0
  18. package/templates/.claude/skills/i18n-multilang/assets/project/gitignore.txt +4 -0
  19. package/templates/.claude/skills/i18n-multilang/assets/project/glossary.json +6 -0
  20. package/templates/.claude/skills/i18n-multilang/assets/project/i18n.config.json +22 -0
  21. package/templates/.claude/skills/i18n-multilang/assets/project/locales/__source__/common.json +10 -0
  22. package/templates/.claude/skills/i18n-multilang/assets/project/notes/common.json +5 -0
  23. package/templates/.claude/skills/i18n-multilang/assets/project/style.md +20 -0
  24. package/templates/.claude/skills/i18n-multilang/references/format.md +100 -0
  25. package/templates/.claude/skills/i18n-multilang/references/languages.md +97 -0
  26. package/templates/.claude/skills/i18n-multilang/references/layout-and-versioning.md +256 -0
  27. package/templates/.claude/skills/i18n-multilang/references/numbers.md +161 -0
  28. package/templates/.claude/skills/i18n-multilang/references/platform-unity.md +142 -0
  29. package/templates/.claude/skills/i18n-multilang/references/platform-web.md +107 -0
  30. package/templates/.claude/skills/i18n-multilang/references/translation.md +143 -0
  31. package/templates/.claude/skills/i18n-multilang/references/voice.md +271 -0
  32. package/templates/.claude/skills/i18n-multilang/scripts/i18n.py +1041 -0
  33. package/templates/.claude/skills/i18n-multilang/scripts/numwords.py +1013 -0
  34. package/templates/.claude/skills/i18n-multilang/scripts/voice.py +478 -0
  35. package/templates/.claude/skills/neon-game-ui-ux-skill/COMPONENTS.md +490 -490
  36. package/templates/.claude/skills/neon-game-ui-ux-skill/GAMIFICATION.md +246 -246
  37. package/templates/.claude/skills/neon-game-ui-ux-skill/ICONS.md +249 -249
  38. package/templates/.claude/skills/neon-game-ui-ux-skill/LAYOUT-NAV.md +362 -362
  39. package/templates/.claude/skills/neon-game-ui-ux-skill/MOTION-A11Y.md +168 -168
  40. package/templates/.claude/skills/neon-game-ui-ux-skill/SKILL.md +137 -137
  41. package/templates/.claude/skills/neon-game-ui-ux-skill/TOKENS.md +323 -323
  42. package/templates/SISYO.md +1 -1
@@ -0,0 +1,1041 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """i18n.py - the text side of the i18n-multilang skill (stdlib only, Python 3.8+).
4
+
5
+ python i18n.py init --product myapp --source vi scaffold ./i18n
6
+ python i18n.py status what every language is missing
7
+ python i18n.py todo --lang ja --out todo.ja.json the texts to translate (new or changed), with context
8
+ python i18n.py apply done.ja.json merge translations back, stamp them, validate
9
+ python i18n.py check validate every file (exit 1 on an error)
10
+ python i18n.py pack build the language packs + manifest, bump versions, copy the bundle
11
+ python i18n.py sync --write drop keys the source no longer has
12
+ python i18n.py stamp --lang en adopt translations that already exist as up to date
13
+ python i18n.py versions text version and voice version per language, and what lags
14
+ python i18n.py languages the registry, and what this project offers
15
+
16
+ It finds i18n.config.json in the current folder, in ./i18n, or in a parent folder (or pass --config).
17
+ Formats and rules: the skill's references/format.md and references/layout-and-versioning.md.
18
+ """
19
+ import argparse
20
+ import copy
21
+ import datetime
22
+ import fnmatch
23
+ import hashlib
24
+ import json
25
+ import re
26
+ import shutil
27
+ import sys
28
+ import unicodedata
29
+ from pathlib import Path
30
+
31
+ SKILL = Path(__file__).resolve().parent.parent
32
+ SCHEMA = 1
33
+ PLURAL_FORMS = ('zero', 'one', 'two', 'few', 'many', 'other')
34
+ _PLURAL_KEY = re.compile(r'^(.+)_(zero|one|two|few|many|other)$')
35
+ _PLACEHOLDER = re.compile(r'\{\{\s*([A-Za-z0-9_]+)\s*(,[^{}]*)?\}\}')
36
+ _LEGACY_PLACEHOLDER = re.compile(r'(?<!\{)\{([A-Za-z0-9_]+)\}(?!\})')
37
+ _PRINTF = re.compile(r'%(\d+\$)?[sdif@]')
38
+ _TAG = re.compile(r'</?[A-Za-z0-9]+[^<>]*>')
39
+ _SEGMENT = re.compile(r'^[A-Za-z0-9_-]+$')
40
+ _LANG = r'[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*'
41
+ _VI_ONLY = re.compile('[ạảấầẩẫậắằẳẵặẹẻẽếềểễệỉịọỏốồổỗộớờởỡợụủứừửữựỳỵỷỹơư]', re.I)
42
+ _SCRIPT = {
43
+ 'Jpan': r'[぀-ヿ㐀-鿿]', 'Hans': r'[㐀-鿿]', 'Hant': r'[㐀-鿿]',
44
+ 'Kore': r'[가-힯ᄀ-ᇿ]', 'Cyrl': r'[Ѐ-ӿ]', 'Grek': r'[Ͱ-Ͽ]',
45
+ 'Thai': r'[฀-๿]', 'Deva': r'[ऀ-ॿ]', 'Beng': r'[ঀ-৿]', 'Taml': r'[஀-௿]',
46
+ 'Arab': r'[؀-ۿݐ-ݿ]', 'Hebr': r'[֐-׿]',
47
+ }
48
+ DEFAULTS = {
49
+ 'schema': SCHEMA,
50
+ 'product': '',
51
+ 'sourceLanguage': 'en',
52
+ 'referenceLanguage': 'en',
53
+ 'compat': 1,
54
+ 'localesDir': 'locales',
55
+ 'layout': '{lang}/{ns}.json',
56
+ 'languages': 'default',
57
+ 'exclude': [],
58
+ 'capabilities': [],
59
+ 'extraLanguages': [],
60
+ 'bundle': {'languages': 'all', 'copyTo': []},
61
+ 'dist': 'dist',
62
+ 'cdn': {'baseUrl': '', 'textPrefix': 'i18n', 'voicePrefix': 'voice'},
63
+ 'voice': {'languages': [], 'fallback': 'en', 'sets': {}, 'voicePattern': '{lang}', 'voices': {}, 'numberStyle': {},
64
+ 'format': 'mp3'},
65
+ }
66
+
67
+
68
+ # ---------------------------------------------------------------- small helpers
69
+ def die(message):
70
+ print('error: ' + message, file=sys.stderr)
71
+ sys.exit(2)
72
+
73
+
74
+ def read_json(path):
75
+ with open(path, encoding='utf-8-sig') as f:
76
+ return json.load(f)
77
+
78
+
79
+ def write_json(path, data, compact=False):
80
+ """UTF-8, LF line ends on every OS (a file written on Windows is read on the Mac and by the CDN)."""
81
+ path = Path(path)
82
+ path.parent.mkdir(parents=True, exist_ok=True)
83
+ if compact:
84
+ text = json.dumps(data, ensure_ascii=False, separators=(',', ':'), sort_keys=True)
85
+ else:
86
+ text = json.dumps(data, ensure_ascii=False, indent=2) + '\n'
87
+ path.write_bytes(text.encode('utf-8'))
88
+ return len(text.encode('utf-8'))
89
+
90
+
91
+ def short_hash(text, n=12):
92
+ return hashlib.sha256(unicodedata.normalize('NFC', text).encode('utf-8')).hexdigest()[:n]
93
+
94
+
95
+ def merge(base, over):
96
+ out = copy.deepcopy(base)
97
+ for k, v in over.items():
98
+ out[k] = merge(out[k], v) if isinstance(v, dict) and isinstance(out.get(k), dict) else v
99
+ return out
100
+
101
+
102
+ def flatten(obj, problems, where, prefix='', out=None):
103
+ """Nested JSON -> {dotted.key: text}. Top-level keys that start with "_" are comments and are skipped."""
104
+ out = {} if out is None else out
105
+ for k, v in obj.items():
106
+ if not prefix and k.startswith('_'):
107
+ continue
108
+ key = prefix + k
109
+ if isinstance(v, dict):
110
+ flatten(v, problems, where, key + '.', out)
111
+ elif isinstance(v, str):
112
+ if key in out:
113
+ problems.append(('error', where, key, 'the key is written twice (nested and dotted)'))
114
+ out[key] = v
115
+ else:
116
+ problems.append(('error', where, key, 'the value is %s, not a text (arrays, numbers and null are not portable)' % type(v).__name__))
117
+ return out
118
+
119
+
120
+ def unflatten(flat):
121
+ """{dotted.key: text} -> nested dicts, or None when a key is both a text and a parent."""
122
+ root = {}
123
+ for key, value in flat.items():
124
+ parts = key.split('.')
125
+ d = root
126
+ for part in parts[:-1]:
127
+ nxt = d.get(part)
128
+ if nxt is None:
129
+ nxt = d[part] = {}
130
+ elif not isinstance(nxt, dict):
131
+ return None
132
+ d = nxt
133
+ if isinstance(d.get(parts[-1]), dict):
134
+ return None
135
+ d[parts[-1]] = value
136
+ return root
137
+
138
+
139
+ def units_of(flat, problems=None, where=''):
140
+ """Translation units in file order: {key: {'plural': bool, 'forms': {form: text}}}.
141
+ A plain key has the single form ''. Keys that end in _one, _other... form one plural unit named by their base."""
142
+ units = {}
143
+ for key, text in flat.items():
144
+ m = _PLURAL_KEY.match(key)
145
+ base, form = (m.group(1), m.group(2)) if m else (key, '')
146
+ unit = units.get(base)
147
+ if unit is None:
148
+ unit = units[base] = {'plural': bool(m), 'forms': {}}
149
+ elif unit['plural'] != bool(m):
150
+ if problems is not None:
151
+ problems.append(('error', where, base, 'is both a plain key and a plural key (%s_other)' % base))
152
+ continue
153
+ unit['forms'][form] = text
154
+ return units
155
+
156
+
157
+ def unit_hash(unit):
158
+ return short_hash(json.dumps(unit['forms'], ensure_ascii=False, sort_keys=True))
159
+
160
+
161
+ def placeholders(text):
162
+ return set(m.group(1) for m in _PLACEHOLDER.finditer(text)) | set('{%s}' % m.group(1) for m in _LEGACY_PLACEHOLDER.finditer(text))
163
+
164
+
165
+ def plural_category(lang, n):
166
+ """The CLDR cardinal category of the whole number n (the rules a non-web runtime must port; web uses Intl.PluralRules)."""
167
+ base = lang.split('-')[0]
168
+ n = abs(int(n))
169
+ n10, n100 = n % 10, n % 100
170
+ million = n != 0 and n % 1000000 == 0
171
+ if base in ('ja', 'ko', 'zh', 'vi', 'id', 'th', 'ms'):
172
+ return 'other'
173
+ if lang == 'pt-PT' or base in ('es', 'it', 'ca'):
174
+ return 'one' if n == 1 else 'many' if million else 'other'
175
+ if base in ('fr', 'pt'):
176
+ return 'one' if n in (0, 1) else 'many' if million else 'other'
177
+ if base in ('hi', 'bn', 'fa'):
178
+ return 'one' if n in (0, 1) else 'other'
179
+ if base == 'fil':
180
+ return 'one' if n in (1, 2, 3) or n10 not in (4, 6, 9) else 'other'
181
+ if base in ('ru', 'uk'):
182
+ return 'one' if n10 == 1 and n100 != 11 else 'few' if 2 <= n10 <= 4 and not 12 <= n100 <= 14 else 'many'
183
+ if base == 'pl':
184
+ return 'one' if n == 1 else 'few' if 2 <= n10 <= 4 and not 12 <= n100 <= 14 else 'many'
185
+ if base in ('cs', 'sk'):
186
+ return 'one' if n == 1 else 'few' if 2 <= n <= 4 else 'other'
187
+ if base == 'ro':
188
+ return 'one' if n == 1 else 'few' if n == 0 or 1 <= n100 <= 19 else 'other'
189
+ if base == 'hr':
190
+ return 'one' if n10 == 1 and n100 != 11 else 'few' if 2 <= n10 <= 4 and not 12 <= n100 <= 14 else 'other'
191
+ if base == 'ar':
192
+ return ('zero', 'one', 'two')[n] if n <= 2 else 'few' if 3 <= n100 <= 10 else 'many' if 11 <= n100 else 'other'
193
+ if base == 'he':
194
+ return 'one' if n == 1 else 'two' if n == 2 else 'other'
195
+ return 'one' if n == 1 else 'other'
196
+
197
+
198
+ # ---------------------------------------------------------------- the project
199
+ class Project:
200
+ def __init__(self, config_path):
201
+ self.config_path = Path(config_path).resolve()
202
+ self.root = self.config_path.parent
203
+ self.cfg = merge(DEFAULTS, read_json(self.config_path))
204
+ self.registry = {}
205
+ for entry in read_json(SKILL / 'assets' / 'languages.json')['languages'] + self.cfg['extraLanguages']:
206
+ self.registry[entry['code']] = entry
207
+ self.source = self.cfg['sourceLanguage']
208
+ if self.source not in self.registry:
209
+ die('sourceLanguage %r is not in the language registry (add it under extraLanguages)' % self.source)
210
+ self.locales = self.root / self.cfg['localesDir']
211
+ layout = self.cfg['layout']
212
+ if '{lang}' not in layout:
213
+ die('layout must contain {lang}: %r' % layout)
214
+ self._layout_re = re.compile('^' + re.escape(layout).replace(r'\{lang\}', '(?P<lang>%s)' % _LANG)
215
+ .replace(r'\{ns\}', r'(?P<ns>[A-Za-z0-9_-]+)') + '$')
216
+ self._cache = {}
217
+ self.load_problems = []
218
+
219
+ # --- languages
220
+ def enabled(self):
221
+ """Codes this project wants, the source first, then registry order."""
222
+ want = self.cfg['languages']
223
+ if want == 'default':
224
+ codes = [c for c, e in self.registry.items() if e.get('default')]
225
+ else:
226
+ for c in want:
227
+ if c not in self.registry:
228
+ die('language %r is not in the registry (add it under extraLanguages)' % c)
229
+ codes = [c for c in self.registry if c in want]
230
+ codes = [c for c in codes if c not in self.cfg['exclude'] and c != self.source]
231
+ return [self.source] + codes
232
+
233
+ def blocked(self, lang):
234
+ """The rendering capabilities the platform has not declared for this language ([] = fine)."""
235
+ return [r for r in self.registry[lang].get('requires', []) if r not in self.cfg['capabilities']]
236
+
237
+ def plural_forms(self, lang):
238
+ return self.registry[lang]['plurals']
239
+
240
+ # --- files
241
+ def path_for(self, lang, ns):
242
+ return self.locales / self.cfg['layout'].replace('{lang}', lang).replace('{ns}', ns)
243
+
244
+ def files(self, lang=None):
245
+ """[(lang, ns, path)] of the locale files on disk."""
246
+ found = []
247
+ if not self.locales.is_dir():
248
+ return found
249
+ for path in sorted(self.locales.rglob('*.json')):
250
+ m = self._layout_re.match(path.relative_to(self.locales).as_posix())
251
+ if m and (lang is None or m.group('lang') == lang):
252
+ found.append((m.group('lang'), m.groupdict().get('ns') or 'translation', path))
253
+ return found
254
+
255
+ def load(self, lang):
256
+ """{ns: {dotted.key: text}} of a language (cached)."""
257
+ if lang not in self._cache:
258
+ data = {}
259
+ for _, ns, path in self.files(lang):
260
+ try:
261
+ raw = read_json(path)
262
+ except (ValueError, OSError) as e:
263
+ self.load_problems.append(('error', lang, ns, 'cannot read %s: %s' % (path.name, e)))
264
+ continue
265
+ if not isinstance(raw, dict):
266
+ self.load_problems.append(('error', lang, ns, '%s must hold a JSON object' % path.name))
267
+ continue
268
+ data[ns] = flatten(raw, self.load_problems, lang + ':' + ns)
269
+ self._cache[lang] = data
270
+ return self._cache[lang]
271
+
272
+ def nested(self, ns):
273
+ """Does the source file of this namespace use nested objects? Targets are written the same way."""
274
+ path = self.path_for(self.source, ns)
275
+ try:
276
+ raw = read_json(path)
277
+ except (ValueError, OSError):
278
+ return True
279
+ return any(isinstance(v, dict) for k, v in raw.items() if not k.startswith('_'))
280
+
281
+ def source_units(self):
282
+ """{ns: {key: unit}} in source order."""
283
+ return {ns: units_of(flat) for ns, flat in self.load(self.source).items()}
284
+
285
+ # --- translation state
286
+ def meta_path(self, lang):
287
+ return self.root / 'meta' / (lang + '.json')
288
+
289
+ def meta(self, lang):
290
+ path = self.meta_path(lang)
291
+ data = read_json(path) if path.is_file() else {}
292
+ data.setdefault('schema', SCHEMA)
293
+ data.setdefault('lang', lang)
294
+ data.setdefault('keys', {})
295
+ data.setdefault('locked', [])
296
+ return data
297
+
298
+ def save_meta(self, lang, meta):
299
+ meta['keys'] = dict(sorted(meta['keys'].items()))
300
+ meta['locked'] = sorted(set(meta['locked']))
301
+ write_json(self.meta_path(lang), meta)
302
+
303
+ def target_keys(self, lang, key, unit):
304
+ return [key + '_' + f for f in self.plural_forms(lang)] if unit['plural'] else [key]
305
+
306
+ def state(self, lang, ns, key, unit, target_flat, meta):
307
+ """ok | untracked (translated, never stamped) | stale (the source changed) | incomplete (plural forms) | missing"""
308
+ if lang == self.source:
309
+ return 'ok'
310
+ keys = self.target_keys(lang, key, unit)
311
+ present = [k for k in keys if target_flat.get(k, '').strip()]
312
+ if not present:
313
+ return 'missing'
314
+ if len(present) < len(keys):
315
+ return 'incomplete'
316
+ stamp = meta['keys'].get(ns + ':' + key)
317
+ if stamp is None:
318
+ return 'untracked'
319
+ return 'ok' if stamp == unit_hash(unit) else 'stale'
320
+
321
+ def report(self, lang):
322
+ """{'states': {uid: state}, 'counts': {...}, 'total': n, 'usable': n, 'coverage': 0..1}"""
323
+ meta = self.meta(lang)
324
+ target = self.load(lang)
325
+ states = {}
326
+ for ns, units in self.source_units().items():
327
+ flat = target.get(ns, {})
328
+ for key, unit in units.items():
329
+ states[ns + ':' + key] = self.state(lang, ns, key, unit, flat, meta)
330
+ counts = {s: 0 for s in ('ok', 'untracked', 'stale', 'incomplete', 'missing')}
331
+ for s in states.values():
332
+ counts[s] += 1
333
+ total = len(states)
334
+ usable = counts['ok'] + counts['untracked']
335
+ return {'states': states, 'counts': counts, 'total': total, 'usable': usable,
336
+ 'coverage': 1.0 if not total else usable / total}
337
+
338
+ def notes(self, ns):
339
+ path = self.root / 'notes' / (ns + '.json')
340
+ return read_json(path) if path.is_file() else {}
341
+
342
+ def glossary(self):
343
+ path = self.root / 'glossary.json'
344
+ g = read_json(path) if path.is_file() else {}
345
+ return {'keep': g.get('keep', []), 'terms': g.get('terms', {}), 'forbidden': g.get('forbidden', {})}
346
+
347
+
348
+ def find_config(explicit=None, required=True):
349
+ if explicit:
350
+ p = Path(explicit)
351
+ p = p / 'i18n.config.json' if p.is_dir() else p
352
+ if not p.is_file():
353
+ die('no config at %s' % p)
354
+ return p
355
+ here = Path.cwd()
356
+ for folder in [here] + list(here.parents):
357
+ for cand in (folder / 'i18n.config.json', folder / 'i18n' / 'i18n.config.json'):
358
+ if cand.is_file():
359
+ return cand
360
+ if required:
361
+ die('no i18n.config.json here, in ./i18n or in a parent folder (run "init", or pass --config)')
362
+ return None
363
+
364
+
365
+ def voice_lines(p):
366
+ """([(set, 'ns:key', unit)], [skipped plural ids]): the lines the project's voice sets select, in set order then
367
+ source order. A line belongs to the first set that names it. A plural text cannot be one clip and is skipped."""
368
+ taken, out, skipped = set(), [], []
369
+ for name, rule in p.cfg['voice']['sets'].items():
370
+ for ns, units in p.source_units().items():
371
+ for key, unit in units.items():
372
+ uid = ns + ':' + key
373
+ if uid in taken or not any(fnmatch.fnmatchcase(uid, pat) for pat in rule.get('include', [])):
374
+ continue
375
+ if any(fnmatch.fnmatchcase(uid, pat) for pat in rule.get('exclude', [])):
376
+ continue
377
+ if unit['plural']:
378
+ skipped.append(uid)
379
+ continue
380
+ taken.add(uid)
381
+ out.append((name, uid, unit))
382
+ return out, skipped
383
+
384
+
385
+ # ---------------------------------------------------------------- check
386
+ def check_text(p, lang, ns, key, unit, target_flat, note, glossary, out):
387
+ """Problems of one translated unit, appended to out as (level, lang, 'ns:key', message)."""
388
+ uid = ns + ':' + key
389
+ entry = p.registry[lang]
390
+ source_all = set()
391
+ for text in unit['forms'].values():
392
+ source_all |= placeholders(text)
393
+ source_text = unit['forms'].get('') or unit['forms'].get('other') or next(iter(unit['forms'].values()))
394
+ forms = {}
395
+ if unit['plural']:
396
+ for f in PLURAL_FORMS:
397
+ if key + '_' + f in target_flat:
398
+ forms[f] = target_flat[key + '_' + f]
399
+ if f not in entry['plurals']:
400
+ out.append(('warning', lang, uid, 'the form _%s is never used in %s (its forms: %s)' % (f, lang, ' '.join(entry['plurals']))))
401
+ elif key in target_flat:
402
+ forms[''] = target_flat[key]
403
+ limit = note.get('max') if isinstance(note, dict) else None
404
+ for form, text in forms.items():
405
+ label = uid + ('_' + form if form else '')
406
+ if not text.strip():
407
+ out.append(('error', lang, label, 'empty translation'))
408
+ continue
409
+ got = placeholders(text)
410
+ for name in sorted(got - source_all):
411
+ out.append(('error', lang, label, 'placeholder %s is not in the source' % (name if name.startswith('{') else '{{%s}}' % name)))
412
+ missing = source_all - got
413
+ if unit['plural']:
414
+ missing -= {'count', '{count}'}
415
+ for name in sorted(missing):
416
+ out.append(('error', lang, label, 'placeholder %s of the source is missing' % (name if name.startswith('{') else '{{%s}}' % name)))
417
+ if sorted(_TAG.findall(text)) != sorted(_TAG.findall(source_text)):
418
+ out.append(('warning', lang, label, 'the markup tags differ from the source'))
419
+ if text.count('\n') != source_text.count('\n'):
420
+ out.append(('warning', lang, label, 'line breaks differ from the source (%d, source %d)' % (text.count('\n'), source_text.count('\n'))))
421
+ if (text[:1].isspace(), text[-1:].isspace()) != (source_text[:1].isspace(), source_text[-1:].isspace()):
422
+ out.append(('warning', lang, label, 'leading / trailing space differs from the source'))
423
+ if limit and len(text) > limit:
424
+ out.append(('error', lang, label, '%d characters, the note allows %d' % (len(text), limit)))
425
+ letters = sum(1 for ch in text if ch.isalpha())
426
+ script = _SCRIPT.get(entry.get('script'))
427
+ plain = _PLACEHOLDER.sub('', text)
428
+ if script and letters >= 4 and not re.search(script, plain) and not any(k in text for k in glossary['keep']):
429
+ out.append(('warning', lang, label, 'no %s characters: is it translated?' % entry['script']))
430
+ if p.source == 'vi' and lang != 'vi' and _VI_ONLY.search(plain) and not any(k in text for k in glossary['keep']):
431
+ out.append(('warning', lang, label, 'Vietnamese letters are left in the text'))
432
+ if lang != p.source and text == source_text and letters >= 12:
433
+ out.append(('warning', lang, label, 'identical to the source text'))
434
+ if lang == 'fr' and re.search(r' [!?;:]', text):
435
+ out.append(('warning', lang, label, 'French: a plain space before ! ? ; : lets the mark wrap alone to the next line: use a no-break space (U+00A0)'))
436
+ low = text.lower()
437
+ for word in glossary['forbidden'].get('*', []) + glossary['forbidden'].get(lang, []):
438
+ w = word.lower()
439
+ hit = re.search(r'(?<![A-Za-z])' + re.escape(w) + r'(?![A-Za-z])', low) if re.fullmatch(r'[\x00-\x7f]+', w) else w in low
440
+ if hit:
441
+ out.append(('error', lang, label, 'holds the forbidden word %r (glossary.json)' % word))
442
+ for word in glossary['keep']:
443
+ if word in source_text and word not in text:
444
+ out.append(('warning', lang, label, 'the name %r of the source is not kept as written' % word))
445
+ for term, by_lang in glossary['terms'].items():
446
+ fixed = by_lang.get(lang)
447
+ if fixed and term.lower() in source_text.lower() and fixed.lower() not in low:
448
+ out.append(('warning', lang, label, 'glossary: %r should be %r' % (term, fixed)))
449
+
450
+
451
+ def check(p, only_lang=None):
452
+ """Every problem of the project as (level, lang, where, message). level: error | warning."""
453
+ out = []
454
+ glossary = p.glossary()
455
+ source = p.load(p.source)
456
+ if not source:
457
+ out.append(('error', p.source, '-', 'no source texts under %s (layout %s)' % (p.locales, p.cfg['layout'])))
458
+ source_units = {}
459
+ for ns, flat in source.items():
460
+ where = p.source
461
+ for key in flat:
462
+ for seg in key.split('.'):
463
+ if not _SEGMENT.match(seg):
464
+ out.append(('error', where, ns + ':' + key, 'key part %r: use letters, digits, _ and - only' % seg))
465
+ if unflatten(flat) is None:
466
+ out.append(('error', where, ns, 'a key is both a text and the parent of other keys'))
467
+ units = source_units[ns] = units_of(flat, out, where)
468
+ for note_key in p.notes(ns):
469
+ if not note_key.startswith('_') and note_key not in units:
470
+ out.append(('warning', where, ns + ':' + note_key, 'a note for a key that does not exist (a note is keyed by the '
471
+ 'dotted key, flat; a plural key by its base name without _other)'))
472
+ for key, unit in units.items():
473
+ uid = ns + ':' + key
474
+ if unit['plural']:
475
+ if 'other' not in unit['forms']:
476
+ out.append(('error', where, uid, 'a plural key needs %s_other in the source' % key))
477
+ for f in unit['forms']:
478
+ if f not in p.plural_forms(p.source):
479
+ out.append(('warning', where, uid + '_' + f, '%s has no "%s" form (its forms: %s)' % (p.source, f, ' '.join(p.plural_forms(p.source)))))
480
+ for form, text in unit['forms'].items():
481
+ label = uid + ('_' + form if form else '')
482
+ if not text.strip():
483
+ out.append(('warning', where, label, 'empty source text'))
484
+ if _LEGACY_PLACEHOLDER.search(text):
485
+ out.append(('warning', where, label, 'single-brace placeholder: the standard is {{name}}'))
486
+ if _PRINTF.search(text):
487
+ out.append(('warning', where, label, 'printf placeholder (%s): the standard is {{name}}'))
488
+ if '$t(' in text:
489
+ out.append(('warning', where, label, '$t() nesting is not portable to the game runtimes'))
490
+ if any(m.group(2) for m in _PLACEHOLDER.finditer(text)):
491
+ out.append(('warning', where, label, 'a {{name, format}} formatter is not portable to the game runtimes'))
492
+ if text != text.strip():
493
+ out.append(('warning', where, label, 'the source text starts or ends with a space'))
494
+ for lang in p.enabled():
495
+ if lang == p.source or (only_lang and lang != only_lang):
496
+ continue
497
+ target = p.load(lang)
498
+ for ns, units in source_units.items():
499
+ flat = target.get(ns, {})
500
+ notes = p.notes(ns)
501
+ for key, unit in units.items():
502
+ check_text(p, lang, ns, key, unit, flat, notes.get(key, {}), glossary, out)
503
+ on_disk = set(l for l, _, _ in p.files())
504
+ for lang in sorted(on_disk - set(p.registry)):
505
+ out.append(('warning', lang, '-', 'a locale folder for a language that is not in the registry'))
506
+ out = p.load_problems + out
507
+ seen, unique = set(), []
508
+ for item in out:
509
+ if item not in seen:
510
+ seen.add(item)
511
+ unique.append(item)
512
+ return unique
513
+
514
+
515
+ # ---------------------------------------------------------------- writing a language
516
+ def write_language(p, lang, changes):
517
+ """changes: {ns: {key: text}} merged into the language's files, written in the source's key order and shape."""
518
+ target = p.load(lang)
519
+ for ns, new in changes.items():
520
+ flat = dict(target.get(ns, {}))
521
+ flat.update(new)
522
+ ordered = {}
523
+ for key, unit in p.source_units().get(ns, {}).items():
524
+ names = [key + '_' + f for f in PLURAL_FORMS] if unit['plural'] else [key]
525
+ for name in names:
526
+ if name in flat:
527
+ ordered[name] = flat[name]
528
+ for name, text in flat.items(): # keys the source no longer has stay at the end until "sync"
529
+ ordered.setdefault(name, text)
530
+ body = unflatten(ordered) if p.nested(ns) else None
531
+ write_json(p.path_for(lang, ns), body if body is not None else ordered)
532
+ target[ns] = ordered
533
+ p._cache[lang] = target
534
+
535
+
536
+ # ---------------------------------------------------------------- commands
537
+ def cmd_init(a):
538
+ root = Path(a.dir).resolve()
539
+ if (root / 'i18n.config.json').exists():
540
+ die('%s already has an i18n.config.json' % root)
541
+ template = SKILL / 'assets' / 'project'
542
+ for src in sorted(template.rglob('*')):
543
+ if src.is_dir():
544
+ continue
545
+ rel = (src.relative_to(template).as_posix().replace('__source__', a.source)
546
+ .replace('gitignore.txt', '.gitignore').replace('gitattributes.txt', '.gitattributes'))
547
+ text = src.read_text(encoding='utf-8').replace('__PRODUCT__', a.product).replace('__SOURCE__', a.source)
548
+ dest = root / rel
549
+ dest.parent.mkdir(parents=True, exist_ok=True)
550
+ dest.write_bytes(text.replace('\r\n', '\n').encode('utf-8'))
551
+ print('created', dest.relative_to(root.parent).as_posix())
552
+ print('next: put the texts in %s, then run "status"' % (root / 'locales' / a.source).as_posix())
553
+
554
+
555
+ def language_row(p, lang):
556
+ entry = p.registry[lang]
557
+ if p.blocked(lang):
558
+ return {'lang': lang, 'name': entry['name'], 'status': 'blocked', 'why': 'the platform has not declared: ' + ', '.join(p.blocked(lang))}
559
+ r = p.report(lang)
560
+ c = r['counts']
561
+ if lang == p.source:
562
+ status = 'source'
563
+ elif r['usable'] == 0 and c['stale'] == 0 and c['incomplete'] == 0:
564
+ status = 'none'
565
+ elif r['usable'] == r['total']:
566
+ status = 'ready'
567
+ else:
568
+ status = 'partial'
569
+ return {'lang': lang, 'name': entry['name'], 'status': status, 'total': r['total'], 'ok': c['ok'],
570
+ 'untracked': c['untracked'], 'stale': c['stale'], 'incomplete': c['incomplete'], 'missing': c['missing'],
571
+ 'coverage': round(r['coverage'], 4)}
572
+
573
+
574
+ def cmd_status(p, a):
575
+ rows = [language_row(p, lang) for lang in p.enabled()]
576
+ if a.json:
577
+ print(json.dumps(rows, ensure_ascii=False, indent=2))
578
+ return 0
579
+ print('%s: source %s, %d texts, compat %d' % (p.cfg['product'] or p.root.name, p.source, rows[0].get('total', 0), p.cfg['compat']))
580
+ print('%-8s %-24s %-8s %6s %6s %6s %6s %6s' % ('lang', 'name', 'status', 'ok', 'new', 'stale', 'plural', 'cover'))
581
+ for r in rows:
582
+ if r['status'] == 'blocked':
583
+ print('%-8s %-24s %-8s %s' % (r['lang'], r['name'], 'blocked', r['why']))
584
+ continue
585
+ print('%-8s %-24s %-8s %6d %6d %6d %6d %5.0f%%%s' % (
586
+ r['lang'], r['name'], r['status'], r['ok'] + r['untracked'], r['missing'], r['stale'], r['incomplete'],
587
+ r['coverage'] * 100, ' (%d untracked: run "stamp" after a review)' % r['untracked'] if r['untracked'] else ''))
588
+ todo = [r['lang'] for r in rows if r['status'] in ('partial', 'none')]
589
+ if todo:
590
+ print('to translate: ' + ' '.join(todo))
591
+ return 0
592
+
593
+
594
+ def cmd_todo(p, a):
595
+ lang = a.lang
596
+ if lang not in p.enabled():
597
+ die('%s is not one of this project\'s languages' % lang)
598
+ if lang == p.source:
599
+ die('%s is the source language' % lang)
600
+ if p.blocked(lang):
601
+ die('%s is blocked: the platform has not declared %s (i18n.config.json -> capabilities)' % (lang, ', '.join(p.blocked(lang))))
602
+ voiced = set(uid for _, uid, _ in voice_lines(p)[0]) if lang in p.cfg['voice']['languages'] else set()
603
+ entry = p.registry[lang]
604
+ report = p.report(lang)
605
+ target = p.load(lang)
606
+ ref_lang = p.cfg['referenceLanguage']
607
+ ref = p.load(ref_lang) if ref_lang not in (p.source, lang) and ref_lang in p.enabled() else None
608
+ ref_report = p.report(ref_lang) if ref is not None else None
609
+ want_ns = set(a.ns.split(',')) if a.ns else None
610
+ locked = set(p.meta(lang)['locked'])
611
+ items = []
612
+ for ns, units in p.source_units().items():
613
+ if want_ns and ns not in want_ns:
614
+ continue
615
+ notes = p.notes(ns)
616
+ for key, unit in units.items():
617
+ uid = ns + ':' + key
618
+ state = report['states'][uid]
619
+ if state in ('ok', 'untracked'):
620
+ continue
621
+ item = {'id': uid, 'state': state,
622
+ 'source': unit['forms'] if unit['plural'] else unit['forms']['']}
623
+ if unit['plural']:
624
+ item['forms'] = entry['plurals']
625
+ if ref is not None and ref_report['states'].get(uid) in ('ok', 'untracked'):
626
+ flat = ref.get(ns, {})
627
+ item['reference'] = ({f: flat[key + '_' + f] for f in p.plural_forms(ref_lang) if key + '_' + f in flat}
628
+ if unit['plural'] else flat.get(key))
629
+ note = notes.get(key)
630
+ if note:
631
+ item['note'] = note
632
+ flat = target.get(ns, {})
633
+ current = ({f: flat[key + '_' + f] for f in PLURAL_FORMS if key + '_' + f in flat} if unit['plural'] else flat.get(key))
634
+ if current:
635
+ item['current'] = current
636
+ if uid in locked:
637
+ item['locked'] = True
638
+ if uid in voiced:
639
+ item['voice'] = True # spoken aloud in this language: translation.md, "Voice lines"
640
+ items.append(item)
641
+ total = len(items)
642
+ if a.limit:
643
+ items = items[:a.limit]
644
+ g = p.glossary()
645
+ doc = {
646
+ 'lang': lang, 'name': entry['name'], 'native': entry['native'], 'dir': entry['dir'],
647
+ 'pluralForms': entry['plurals'], 'sourceLanguage': p.source,
648
+ 'referenceLanguage': ref_lang if ref is not None else None,
649
+ 'glossary': {'keep': g['keep'],
650
+ 'terms': {t: v[lang] for t, v in g['terms'].items() if lang in v},
651
+ 'forbidden': g['forbidden'].get('*', []) + g['forbidden'].get(lang, [])},
652
+ 'remaining': total, 'items': items,
653
+ 'answer': {'lang': lang, 'items': {'<id>': '<translation, or {form: translation} for a plural id>'}},
654
+ }
655
+ if a.out:
656
+ write_json(a.out, doc)
657
+ print('%s: %d of %d texts to translate written to %s' % (lang, len(items), total, a.out))
658
+ else:
659
+ print(json.dumps(doc, ensure_ascii=False, indent=2))
660
+ return 0
661
+
662
+
663
+ def cmd_apply(p, a):
664
+ doc = read_json(a.file)
665
+ lang = doc.get('lang')
666
+ if lang not in p.enabled() or lang == p.source:
667
+ die('"lang" must be one of this project\'s target languages, got %r' % lang)
668
+ meta = p.meta(lang)
669
+ units = p.source_units()
670
+ glossary = p.glossary()
671
+ changes, applied, rejected = {}, [], []
672
+ for uid, value in doc.get('items', {}).items():
673
+ ns, _, key = uid.partition(':')
674
+ unit = units.get(ns, {}).get(key)
675
+ if unit is None:
676
+ rejected.append((uid, 'no such source text'))
677
+ continue
678
+ if uid in meta['locked'] and not a.force:
679
+ rejected.append((uid, 'locked (a person reviewed it): pass --force only if the owner asked'))
680
+ continue
681
+ if unit['plural']:
682
+ if not isinstance(value, dict):
683
+ rejected.append((uid, 'a plural text needs an object of forms: %s' % ' '.join(p.plural_forms(lang))))
684
+ continue
685
+ lack = [f for f in p.plural_forms(lang) if not str(value.get(f, '')).strip()]
686
+ extra = [f for f in value if f not in PLURAL_FORMS]
687
+ if lack or extra:
688
+ rejected.append((uid, 'plural forms: missing %s%s' % (' '.join(lack) or '-', '; unknown ' + ' '.join(extra) if extra else '')))
689
+ continue
690
+ new = {key + '_' + f: value[f] for f in PLURAL_FORMS if f in value}
691
+ else:
692
+ if not isinstance(value, str):
693
+ rejected.append((uid, 'expected a text'))
694
+ continue
695
+ new = {key: value}
696
+ problems = []
697
+ check_text(p, lang, ns, key, unit, new, p.notes(ns).get(key, {}), glossary, problems)
698
+ errors = [m for level, _, _, m in problems if level == 'error']
699
+ if errors:
700
+ rejected.append((uid, '; '.join(errors)))
701
+ continue
702
+ for level, _, where, message in problems:
703
+ print('warning %s %s: %s' % (lang, where, message))
704
+ changes.setdefault(ns, {}).update(new)
705
+ if unit['plural']: # forms the answer no longer has are dropped
706
+ old = p.load(lang).get(ns, {})
707
+ for f in PLURAL_FORMS:
708
+ if key + '_' + f in old and key + '_' + f not in new:
709
+ old.pop(key + '_' + f)
710
+ meta['keys'][uid] = unit_hash(unit)
711
+ if a.lock:
712
+ meta['locked'].append(uid)
713
+ applied.append(uid)
714
+ if changes:
715
+ write_language(p, lang, changes)
716
+ p.save_meta(lang, meta)
717
+ print('%s: applied %d, rejected %d' % (lang, len(applied), len(rejected)))
718
+ for uid, why in rejected:
719
+ print(' rejected %s: %s' % (uid, why))
720
+ return 1 if rejected else 0
721
+
722
+
723
+ def cmd_stamp(p, a):
724
+ langs = [l for l in p.enabled() if l != p.source] if a.all else [a.lang]
725
+ if not a.all and not a.lang:
726
+ die('pass --lang or --all')
727
+ units = p.source_units()
728
+ for lang in langs:
729
+ if lang not in p.enabled() or lang == p.source:
730
+ die('%s is not a target language of this project' % lang)
731
+ report, meta, n = p.report(lang), p.meta(lang), 0
732
+ for uid, state in report['states'].items():
733
+ if state == 'untracked' or (a.stale and state == 'stale'):
734
+ ns, _, key = uid.partition(':')
735
+ meta['keys'][uid] = unit_hash(units[ns][key])
736
+ n += 1
737
+ if n:
738
+ p.save_meta(lang, meta)
739
+ print('%s: %d texts stamped as up to date' % (lang, n))
740
+ return 0
741
+
742
+
743
+ def cmd_sync(p, a):
744
+ units = p.source_units()
745
+ valid = set()
746
+ for ns, us in units.items():
747
+ for key, unit in us.items():
748
+ valid.add(ns + ':' + key)
749
+ changed = False
750
+ for lang in sorted(set(l for l, _, _ in p.files()) - {p.source}):
751
+ if lang not in p.registry:
752
+ continue
753
+ target = p.load(lang)
754
+ for ns, flat in list(target.items()):
755
+ keep = {}
756
+ for name, text in flat.items():
757
+ m = _PLURAL_KEY.match(name)
758
+ base = m.group(1) if m and ns + ':' + m.group(1) in valid and units[ns][m.group(1)]['plural'] else name
759
+ if ns + ':' + base in valid:
760
+ keep[name] = text
761
+ gone = [k for k in flat if k not in keep]
762
+ if gone:
763
+ changed = True
764
+ print('%s %s: %d keys the source no longer has%s' % (lang, ns, len(gone), '' if a.write else ' (' + ', '.join(gone[:5]) + ('…' if len(gone) > 5 else '') + ')'))
765
+ if a.write:
766
+ path = p.path_for(lang, ns)
767
+ if keep:
768
+ body = unflatten(keep) if p.nested(ns) else None
769
+ write_json(path, body if body is not None else keep)
770
+ elif path.is_file():
771
+ path.unlink()
772
+ target[ns] = keep
773
+ meta = p.meta(lang)
774
+ orphans = [uid for uid in meta['keys'] if uid not in valid]
775
+ if orphans or any(uid not in valid for uid in meta['locked']):
776
+ changed = True
777
+ print('%s: %d stamps of texts that are gone' % (lang, len(orphans)))
778
+ if a.write:
779
+ meta['keys'] = {k: v for k, v in meta['keys'].items() if k in valid}
780
+ meta['locked'] = [k for k in meta['locked'] if k in valid]
781
+ p.save_meta(lang, meta)
782
+ if not changed:
783
+ print('in sync: no orphan keys')
784
+ elif not a.write:
785
+ print('nothing written: pass --write to remove them')
786
+ return 0
787
+
788
+
789
+ def cmd_check(p, a):
790
+ problems = check(p, a.lang)
791
+ errors = [x for x in problems if x[0] == 'error']
792
+ warnings = [x for x in problems if x[0] == 'warning']
793
+ for level, lang, where, message in problems:
794
+ print('%-7s %-8s %s: %s' % (level, lang, where, message))
795
+ print('check: %d errors, %d warnings' % (len(errors), len(warnings)))
796
+ return 1 if errors or (a.strict and warnings) else 0
797
+
798
+
799
+ def build_pack(p, lang):
800
+ """The pack of a language: only texts that are translated and up to date (the runtime falls back for the rest)."""
801
+ report = p.report(lang)
802
+ target = p.load(lang)
803
+ strings = {}
804
+ for ns, units in p.source_units().items():
805
+ flat = target.get(ns, {})
806
+ keep = {}
807
+ for key, unit in units.items():
808
+ if report['states'][ns + ':' + key] not in ('ok', 'untracked'):
809
+ continue
810
+ names = [key + '_' + f for f in PLURAL_FORMS] if unit['plural'] else [key]
811
+ for name in names:
812
+ if name in flat:
813
+ keep[name] = flat[name]
814
+ if keep:
815
+ strings[ns] = keep
816
+ return report, {'schema': SCHEMA, 'lang': lang, 'strings': strings}
817
+
818
+
819
+ def pack_body(p, lang):
820
+ """(report, pack, bytes, sha256) of a language's pack as it would be built from the files right now."""
821
+ report, pack = build_pack(p, lang)
822
+ body = json.dumps(pack, ensure_ascii=False, separators=(',', ':'), sort_keys=True).encode('utf-8')
823
+ return report, pack, body, hashlib.sha256(body).hexdigest()
824
+
825
+
826
+ def cmd_versions(p, a):
827
+ """Text version and voice version of every language side by side: what is packed, what changed since, what lags."""
828
+ text_path, voice_path = p.root / 'manifest.json', p.root / 'voice' / 'manifest.json'
829
+ text = read_json(text_path) if text_path.is_file() else {}
830
+ voice = read_json(voice_path) if voice_path.is_file() else {}
831
+ rows = []
832
+ for lang in p.enabled():
833
+ if p.blocked(lang):
834
+ continue
835
+ entry = text.get('languages', {}).get(lang)
836
+ _, pack, _, sha = pack_body(p, lang)
837
+ if not entry and not pack['strings']:
838
+ continue
839
+ v = voice.get('languages', {}).get(lang)
840
+ rows.append({
841
+ 'lang': lang,
842
+ 'text': {'version': entry['version'] if entry else None, 'status': entry['status'] if entry else 'not packed',
843
+ 'editedSincePack': not entry or entry['hash'] != sha},
844
+ 'voice': None if not v else {
845
+ 'madeForTextVersion': v.get('textVersion'),
846
+ 'sets': {name: {k: s.get(k) for k in ('version', 'clips', 'lines', 'behind', 'silent')} for name, s in v['sets'].items()}},
847
+ })
848
+ if a.json:
849
+ print(json.dumps({'product': p.cfg['product'], 'compat': p.cfg['compat'], 'textRevision': text.get('revision'),
850
+ 'voiceRevision': voice.get('revision'), 'languages': rows}, ensure_ascii=False, indent=2))
851
+ return 0
852
+ print('%s: compat %d, text revision %s (%s)%s' % (
853
+ p.cfg['product'] or p.root.name, p.cfg['compat'], text.get('revision', '-'), text.get('updatedAt', 'never packed'),
854
+ ', voice revision %s (%s)' % (voice['revision'], voice.get('updatedAt')) if voice else ', no voice'))
855
+ print('%-8s %-7s %-9s %-16s %-6s %-9s %-7s %-7s %s' % ('lang', 'text', 'state', 'voice set', 'voice', 'for text', 'clips', 'behind', 'silent'))
856
+ notes = set()
857
+ for r in rows:
858
+ t = r['text']
859
+ mark = ''
860
+ if t['editedSincePack']:
861
+ mark = ' *'
862
+ notes.add('* text edited since the last pack: run "i18n.py pack"')
863
+ head = '%-8s %-7s %-9s ' % (r['lang'], ('v%d' % t['version'] if t['version'] else '-') + mark, t['status'])
864
+ if not r['voice']:
865
+ print(head + ' -')
866
+ continue
867
+ for i, (name, s) in enumerate(r['voice']['sets'].items()):
868
+ made = r['voice']['madeForTextVersion']
869
+ lag = ''
870
+ if made is not None and t['version'] and made < t['version']:
871
+ lag = ' !'
872
+ notes.add('! the voice sets were packed for an older text version: run "voice.py pack" and read its report')
873
+ print('%s %-16s %-6s %-9s %-7s %-7s %s' % (
874
+ head if i == 0 else ' ' * len(head), name, 'v%d' % s['version'], ('v%s' % made if made is not None else '?') + lag,
875
+ '%s/%s' % (s['clips'], s['lines']), s.get('behind') or 0, s.get('silent') or 0))
876
+ for n in sorted(notes):
877
+ print(n)
878
+ if voice:
879
+ print('behind = the text changed, the old clip is kept and still plays; silent = no usable clip for the current text')
880
+ return 0
881
+
882
+
883
+ def cmd_pack(p, a):
884
+ errors = [x for x in check(p) if x[0] == 'error']
885
+ if errors:
886
+ for level, lang, where, message in errors[:20]:
887
+ print('%-7s %-8s %s: %s' % (level, lang, where, message))
888
+ die('%d check errors: fix them before packing' % len(errors))
889
+ manifest_path = p.root / 'manifest.json'
890
+ prev = read_json(manifest_path) if manifest_path.is_file() else {}
891
+ prev_langs = prev.get('languages', {}) if prev.get('compat') == p.cfg['compat'] else {}
892
+ packs, entries, regress = {}, {}, []
893
+ enabled = p.enabled()
894
+ for lang in enabled:
895
+ if p.blocked(lang):
896
+ continue
897
+ report, pack, body, sha = pack_body(p, lang)
898
+ if not pack['strings']:
899
+ continue
900
+ old = prev_langs.get(lang)
901
+ status = 'ready' if report['usable'] == report['total'] else 'partial'
902
+ if old and old.get('status') == 'ready' and status != 'ready':
903
+ regress.append('%s (%d of %d)' % (lang, report['usable'], report['total']))
904
+ entry = p.registry[lang]
905
+ entries[lang] = {
906
+ 'name': entry['name'], 'native': entry['native'], 'dir': entry['dir'], 'script': entry['script'],
907
+ 'version': (old['version'] + (0 if old.get('hash') == sha else 1)) if old else 1,
908
+ 'hash': sha, 'file': '%s/%s.%s.json' % (lang, lang, sha[:12]), 'bytes': len(body),
909
+ 'texts': report['usable'], 'coverage': round(report['coverage'], 4), 'status': status,
910
+ }
911
+ if entry.get('aliases'):
912
+ entries[lang]['aliases'] = entry['aliases']
913
+ packs[lang] = body
914
+ for lang in prev_langs:
915
+ if prev_langs[lang].get('status') == 'ready' and lang not in entries:
916
+ regress.append('%s (gone)' % lang)
917
+ if regress and not a.allow_regress:
918
+ die('these languages were ready in the last pack and are not any more: %s.\n'
919
+ 'Translate first (status, todo, apply). Pass --allow-regress only if the owner accepts shipping without them.'
920
+ % ', '.join(regress))
921
+ fallback_all = [l for l in ('en', p.source) if l in entries]
922
+ for lang, e in entries.items():
923
+ chain = [l for l in p.registry[lang].get('fallback', []) + fallback_all if l in entries and l != lang]
924
+ e['fallback'] = list(dict.fromkeys(chain))
925
+ changed = (set(entries) != set(prev_langs)
926
+ or any(entries[l]['hash'] != prev_langs[l].get('hash') or entries[l]['status'] != prev_langs[l].get('status') for l in entries))
927
+ manifest = {
928
+ 'schema': SCHEMA, 'product': p.cfg['product'], 'compat': p.cfg['compat'],
929
+ 'revision': prev.get('revision', 0) + 1 if changed or not prev else prev['revision'],
930
+ 'updatedAt': datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ') if changed or not prev else prev.get('updatedAt'),
931
+ 'sourceLanguage': p.source, 'fallbackLanguage': fallback_all[0] if fallback_all else p.source,
932
+ 'texts': p.report(p.source)['total'], 'languages': entries,
933
+ }
934
+ write_json(manifest_path, manifest)
935
+ prefix = '%s/c%d' % (p.cfg['cdn']['textPrefix'].strip('/'), p.cfg['compat'])
936
+ out = p.root / p.cfg['dist'] / prefix
937
+ if out.is_dir():
938
+ shutil.rmtree(out)
939
+ plan = []
940
+ for lang, body in packs.items():
941
+ dest = out / entries[lang]['file']
942
+ dest.parent.mkdir(parents=True, exist_ok=True)
943
+ dest.write_bytes(body)
944
+ plan.append({'file': (Path(prefix) / entries[lang]['file']).as_posix(), 'key': prefix + '/' + entries[lang]['file'],
945
+ 'contentType': 'application/json; charset=utf-8', 'cacheControl': 'public, max-age=31536000, immutable'})
946
+ write_json(out / 'manifest.json', manifest)
947
+ plan.append({'file': prefix + '/manifest.json', 'key': prefix + '/manifest.json',
948
+ 'contentType': 'application/json; charset=utf-8', 'cacheControl': 'public, max-age=60', 'last': True})
949
+ plan_path = p.root / p.cfg['dist'] / 'upload-plan.text.json'
950
+ write_json(plan_path, {'base': p.cfg['cdn']['baseUrl'], 'order': 'every file first, the manifest last', 'files': plan})
951
+ bundle = p.cfg['bundle']
952
+ if not a.no_bundle:
953
+ want = list(entries) if bundle['languages'] == 'all' else [l for l in entries if l in bundle['languages']]
954
+ for folder in bundle['copyTo']:
955
+ dest = (p.root / folder).resolve()
956
+ dest.mkdir(parents=True, exist_ok=True)
957
+ for old_file in dest.glob('*.json'):
958
+ if old_file.stem in p.registry and old_file.stem not in want:
959
+ old_file.unlink()
960
+ for lang in want:
961
+ (dest / (lang + '.json')).write_bytes(packs[lang])
962
+ local = copy.deepcopy(manifest)
963
+ local['languages'] = {l: dict(e, file=l + '.json') for l, e in manifest['languages'].items() if l in want}
964
+ write_json(dest / 'manifest.json', local)
965
+ print('bundle: %d languages -> %s' % (len(want), dest.as_posix()))
966
+ ready = [l for l, e in entries.items() if e['status'] == 'ready']
967
+ bumped = [l for l in entries if not prev_langs.get(l) or prev_langs[l].get('hash') != entries[l]['hash']]
968
+ print('pack: revision %d, %d languages (%d ready), %d changed%s' % (
969
+ manifest['revision'], len(entries), len(ready), len(bumped), ': ' + ' '.join(bumped) if bumped else ''))
970
+ print('dist: %s upload plan: %s' % (out.as_posix(), plan_path.as_posix()))
971
+ return 0
972
+
973
+
974
+ def cmd_languages(p, a):
975
+ reg = p.registry if p else {e['code']: e for e in read_json(SKILL / 'assets' / 'languages.json')['languages']}
976
+ enabled = p.enabled() if p else []
977
+ print('%-8s %-26s %-22s %-5s %-4s %-6s %-28s %s' % ('code', 'name', 'native', 'voice', 'dir', 'script', 'plural forms', 'project'))
978
+ for code, e in reg.items():
979
+ mark = ''
980
+ if p:
981
+ mark = 'source' if code == p.source else 'blocked: ' + ','.join(p.blocked(code)) if code in enabled and p.blocked(code) else 'on' if code in enabled else '-'
982
+ print('%-8s %-26s %-22s %-5s %-4s %-6s %-28s %s' % (code, e['name'], e['native'], 'yes' if e.get('voice') else '', e['dir'], e['script'], ' '.join(e['plurals']), mark))
983
+ return 0
984
+
985
+
986
+ def main(argv=None):
987
+ for stream in (sys.stdout, sys.stderr):
988
+ if hasattr(stream, 'reconfigure'):
989
+ stream.reconfigure(encoding='utf-8')
990
+ ap = argparse.ArgumentParser(description='Text packs of the i18n-multilang skill.')
991
+ ap.add_argument('--config', help='i18n.config.json or its folder (default: found from the current folder)')
992
+ sub = ap.add_subparsers(dest='cmd', required=True)
993
+ s = sub.add_parser('init', help='scaffold an i18n folder')
994
+ s.add_argument('--dir', default='i18n')
995
+ s.add_argument('--product', required=True)
996
+ s.add_argument('--source', default='en', help='the language the texts are written in first')
997
+ s = sub.add_parser('status', help='coverage of every language')
998
+ s.add_argument('--json', action='store_true')
999
+ s = sub.add_parser('todo', help='the texts a language still needs, as JSON')
1000
+ s.add_argument('--lang', required=True)
1001
+ s.add_argument('--ns', help='only these namespaces (comma separated)')
1002
+ s.add_argument('--limit', type=int, help='at most this many texts (translate in batches)')
1003
+ s.add_argument('--out', help='write to this file instead of the screen')
1004
+ s = sub.add_parser('apply', help='merge a file of translations: {"lang": "ja", "items": {"ns:key": "…"}}')
1005
+ s.add_argument('file')
1006
+ s.add_argument('--force', action='store_true', help='also overwrite locked texts')
1007
+ s.add_argument('--lock', action='store_true', help='lock the applied texts (a person reviewed them)')
1008
+ s = sub.add_parser('stamp', help='mark translations that already exist as up to date with the source')
1009
+ s.add_argument('--lang')
1010
+ s.add_argument('--all', action='store_true')
1011
+ s.add_argument('--stale', action='store_true', help='also re-stamp stale texts (only after checking each one)')
1012
+ s = sub.add_parser('sync', help='find (and with --write remove) keys the source no longer has')
1013
+ s.add_argument('--write', action='store_true')
1014
+ s = sub.add_parser('check', help='validate the files; exit 1 on an error')
1015
+ s.add_argument('--lang')
1016
+ s.add_argument('--strict', action='store_true', help='warnings fail too')
1017
+ s = sub.add_parser('pack', help='build dist/, manifest.json and the bundle copies')
1018
+ s.add_argument('--allow-regress', action='store_true')
1019
+ s.add_argument('--no-bundle', action='store_true')
1020
+ sub.add_parser('languages', help='the language registry')
1021
+ s = sub.add_parser('versions', help='text version and voice version of every language, and what lags')
1022
+ s.add_argument('--json', action='store_true')
1023
+ s = sub.add_parser('plural', help='the plural form of a number in a language')
1024
+ s.add_argument('number', type=int)
1025
+ s.add_argument('--lang', required=True)
1026
+ a = ap.parse_args(argv)
1027
+ if a.cmd == 'init':
1028
+ return cmd_init(a)
1029
+ if a.cmd == 'plural':
1030
+ print(plural_category(a.lang, a.number))
1031
+ return 0
1032
+ if a.cmd == 'languages':
1033
+ cfg = find_config(a.config, required=False)
1034
+ return cmd_languages(Project(cfg) if cfg else None, a)
1035
+ p = Project(find_config(a.config))
1036
+ return {'status': cmd_status, 'todo': cmd_todo, 'apply': cmd_apply, 'stamp': cmd_stamp, 'sync': cmd_sync,
1037
+ 'check': cmd_check, 'pack': cmd_pack, 'versions': cmd_versions}[a.cmd](p, a)
1038
+
1039
+
1040
+ if __name__ == '__main__':
1041
+ sys.exit(main() or 0)