okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
5d9f47922
main
1"""The web page's translations: read the English text out of serve/web, write locales/en.json, check the catalogs. 2 3python tools/web_i18n.py # check every catalog against the text in the code (exit 1 on a problem) 4python tools/web_i18n.py --write # also rewrite serve/web/locales/en.json from the code 5 6The English text lives in the code (see serve/web/i18n.js): 7tr("key", "English text", vars) in serve/web/*.js 8tr("key", {one: "{n} chat", other: "{n} chats"}, vars) a plural 9<span data-i18n="key">English text</span> in serve/web/index.html (also data-i18n-title, -label, -placeholder) 10Both must be plain string literals (no template strings, no joined strings), so that this reader and a translator see 11the same text. serve/test_web_i18n.py runs the check. 12""" 13from __future__import annotations 14 15import html .parser 16import json 17import re 18import sys 19from pathlib import Path 20 21WEB = Path (__file__ ).resolve ().parents [1 ]/ "serve" / "web" 22LOCALES = WEB / "locales" 23PLACEHOLDER = re .compile (r"\{(\w+)\}" ) 24CALL = re .compile (r"(?<![\w.$])tr\(\s*\"([\w.\-]+)\"\s*,\s*" ) 25PLURAL_CATEGORIES = ("zero" ,"one" ,"two" ,"few" ,"many" ,"other" ) 26 27 28class Problem (Exception ): 29pass 30 31 32def _string (src :str ,i :int ): 33"""A double-quoted JS string literal at src[i]: (the text, the index after it).""" 34if src [i ]!= '"' : 35raise Problem (f"expected a string literal at: { src [ i : i + 40 ]!r } " ) 36j = i + 1 37while j < len (src ): 38if src [j ]== "\\" : 39j += 2 40continue 41if src [j ]== '"' : 42try : 43return json .loads (src [i :j + 1 ]),j + 1 44except ValueError as e : 45raise Problem (f"not a plain string literal ( { e } ): { src [ i : j + 1 ]!r } " ) 46j += 1 47raise Problem ("unterminated string literal" ) 48 49 50def _plural (src :str ,i :int ): 51"""{one: "...", other: "..."} at src[i].""" 52j = i + 1 53out = {} 54while True : 55m = re .compile (r"\s*(\w+)\s*:\s*" ).match (src ,j ) 56if not m : 57raise Problem (f"expected a plural form at: { src [ j : j + 40 ]!r } " ) 58text ,j = _string (src ,m .end ()) 59out [m .group (1 )]= text 60m = re .compile (r"\s*([,}])" ).match (src ,j ) 61if not m : 62raise Problem (f"expected , or }} after a plural form at: { src [ j : j + 40 ]!r } " ) 63j = m .end () 64if m .group (1 )== "}" : 65break 66if "other" not in out : 67raise Problem (f"a plural needs an 'other' form: { out } " ) 68return out ,j 69 70 71def js_strings (src :str ,name :str = "?" )-> dict : 72found = {} 73for m in CALL .finditer (src ): 74key = m .group (1 ) 75i = m .end () 76try : 77value ,_ = _plural (src ,i )if src [i ]== "{" else _string (src ,i ) 78except Problem as e : 79line = src .count ("\n" ,0 ,m .start ())+ 1 80raise Problem (f" { name } : { line } : tr( { key !r } ): { e } " ) 81found [key ]= value 82return found 83 84 85class _Html (html .parser .HTMLParser ): 86ATTRS = {"data-i18n-title" :"title" ,"data-i18n-label" :"aria-label" ,"data-i18n-placeholder" :"placeholder" } 87 88def __init__ (self ): 89super ().__init__ (convert_charrefs = True ) 90self .found :dict = {} 91self .open = []# [(tag, key, [text])] 92 93def handle_starttag (self ,tag ,attrs ): 94a = dict (attrs ) 95for mark ,attr in self .ATTRS .items (): 96if mark in a : 97self .found [a [mark ]]= a .get (attr )or "" 98if "data-i18n" in a : 99self .open .append ((tag ,a ["data-i18n" ], [])) 100elif self .open : 101self .open .append ((tag ,None ,self .open [- 1 ][2 ])) 102 103def handle_data (self ,data ): 104if self .open : 105self .open [- 1 ][2 ].append (data ) 106 107def handle_endtag (self ,tag ): 108if self .open and self .open [- 1 ][0 ]== tag : 109_ ,key ,text = self .open .pop () 110if key : 111self .found [key ]= " " .join ("" .join (text ).split ()) 112 113 114def html_strings (src :str )-> dict : 115p = _Html () 116p .feed (src ) 117return p .found 118 119 120def english ()-> dict : 121"""Every key in serve/web with its English text; the same key twice must have the same text.""" 122out :dict = {} 123sources = {p .name :js_strings (p .read_text (encoding = "utf-8" ),p .name )for p in sorted (WEB .glob ("*.js" ))if p .name != "i18n.js" } 124sources ["index.html" ]= html_strings ((WEB / "index.html" ).read_text (encoding = "utf-8" )) 125for name ,found in sources .items (): 126for key ,value in found .items (): 127if key in out and out [key ]!= value : 128raise Problem (f" { key !r } has two different English texts (one is in { name } )" ) 129out [key ]= value 130return dict (sorted (out .items ())) 131 132 133def languages ()-> list : 134src = (WEB / "i18n.js" ).read_text (encoding = "utf-8" ) 135block = re .search (r"const LANGUAGES = (\[.*?\]);" ,src ,re .S ).group (1 ) 136return [m for m in re .findall (r'\["([\w-]+)",' ,block )] 137 138 139def placeholders (value )-> set : 140forms = value .values ()if isinstance (value ,dict )else [value ] 141return {name for form in forms for name in PLACEHOLDER .findall (form )} 142 143 144def check_catalog (code :str ,catalog :dict ,en :dict )-> list : 145problems = [] 146for key in sorted (set (en )- set (catalog )): 147problems .append (f" { code } : missing { key !r } " ) 148for key in sorted (set (catalog )- set (en )): 149problems .append (f" { code } : { key !r } is not in the page (renamed or removed?)" ) 150for key ,value in catalog .items (): 151if key not in en : 152continue 153forms = value if isinstance (value ,dict )else {"" :value } 154if isinstance (value ,dict ): 155bad = [c for c in value if c not in PLURAL_CATEGORIES ] 156if bad or "other" not in value : 157problems .append (f" { code } : { key !r } : plural forms must be CLDR names with an 'other' form, got { sorted ( value ) } " ) 158if not isinstance (en [key ],dict ): 159problems .append (f" { code } : { key !r } is a plural here but not in the code" ) 160elif isinstance (en [key ],dict ): 161problems .append (f" { code } : { key !r } is a plain text here but a plural in the code" ) 162for form ,text in forms .items (): 163if not isinstance (text ,str )or not text .strip (): 164problems .append (f" { code } : { key !r } { form } is empty or not a string" ) 165if placeholders (value )!= placeholders (en [key ])and not ( 166isinstance (value ,dict )and isinstance (en [key ],dict ) 167and all (placeholders (f )<= placeholders (en [key ])for f in value .values ())): 168problems .append (f" { code } : { key !r } uses { sorted ( placeholders ( value )) } , the code uses { sorted ( placeholders ( en [ key ])) } " ) 169return problems 170 171 172def check (write :bool = False )-> list : 173en = english () 174if write : 175LOCALES .mkdir (exist_ok = True ) 176 (LOCALES / "en.json" ).write_text (json .dumps (en ,ensure_ascii = False ,indent = 2 )+ "\n" ,encoding = "utf-8" ) 177problems = [] 178on_disk = LOCALES / "en.json" 179if not on_disk .is_file ()or json .loads (on_disk .read_text (encoding = "utf-8" ))!= en : 180problems .append ("en.json is not the text in the code (python tools/web_i18n.py --write)" ) 181for code in languages (): 182if code == "en" : 183continue 184f = LOCALES / f" { code } .json" 185if not f .is_file (): 186problems .append (f" { code } : serve/web/locales/ { code } .json is missing" ) 187continue 188problems += check_catalog (code ,json .loads (f .read_text (encoding = "utf-8" )),en ) 189for f in sorted (LOCALES .glob ("*.json" )): 190if f .stem not in languages (): 191problems .append (f" { f . name } : not in LANGUAGES of serve/web/i18n.js" ) 192return problems 193 194 195if __name__ == "__main__" : 196try : 197problems = check (write = "--write" in sys .argv ) 198except Problem as e : 199f"web_i18n: { e } " ) 200sys .exit (1 ) 201for p in problems : 202"web_i18n:" ,p ) 203sys .exit (1 if problems else 0 )