Files

403 lines
17 KiB
Python

#!/usr/bin/env python3
"""A plugin's own strings — the ``i18n`` contract (ai-agent ``docs/plugins.md``
→ "A plugin's own strings").
A plugin that declares ``"i18n": "i18n"`` in its ``plugin.json`` keeps:
* ``i18n/en.json`` — the English source list, **generated** here from:
- the manifest: ``name``, ``description``, ``ui.pages[].label`` /
``description``, ``ui.card[].text`` / ``title`` and a list bit's wording
(``ui.card[].list``), ``settings.subtitle``,
``settings.fields[].label`` / ``help``;
- its frames (``ui/``, ``ui-src/``: ``.html`` ``.js``): the first string
literal of ``t("…")`` / ``msg("…")`` (``aiAgentPlugin.t``, ``P.t`` too) and
both of ``tn(n, "…", "…")``;
- its Python (``handlers/``, ``lib/``, ``jobs/``): ``t(lang, "…")`` /
``tr(lang, "…")`` and ``msg("…")`` (``ast``: implicit concatenation is fine).
Write each English string as **one literal** (no ``+``, no template); a
string that reaches ``t()`` through a variable is marked with ``msg("…")``.
* ``i18n/<lang>.json`` — ``{English: translation}``; ``{placeholders}`` kept.
Commands (stdlib only):
plugin_i18n.py keys [PLUGIN…] rewrite en.json from the sources
plugin_i18n.py check [--strict] [PLUGIN…]
en.json in step, placeholders kept, languages == en + files;
--strict: nothing missing, nothing stale (what a translation pass ends on)
plugin_i18n.py todo [--json] [--plugin P:LANG…] [--translation translation-fr…]
what is missing / stale: a plugin's own files, and a translation
plugin against the core's key lists (AI_AGENT_DIR, default ~/projects/ai-agent)
plugin_i18n.py prune [--plugin P:LANG…] [--translation ID…]
remove the stale entries (their English is gone) — no model needed
plugin_i18n.py apply (--plugin P:LANG | --translation ID --part ui|backend) FILE.json
add the translations in FILE.json ({English: translation}) to that
target: only keys its English list has and it lacks, placeholders kept
(anything else is refused and listed); a plugin's new language is
added to its plugin.json ``languages``
PLUGIN is a folder (``plugins/cron-jobs``) or an id; none = every plugin of
the repo that declares ``i18n``.
"""
from __future__ import annotations
import argparse
import ast
import json
import os
import pathlib
import re
import sys
from typing import Any
REPO = pathlib.Path(__file__).resolve().parents[1]
PLUGINS = REPO / "plugins"
LANG_FILE = re.compile(r"^([a-z]{2,3})\.json$")
VARS = re.compile(r"\{(\w+)\}")
_LIT = r'"((?:[^"\\\n]|\\.)*)"|\'((?:[^\'\\\n]|\\.)*)\''
JS_T = re.compile(r"\b(?:t|msg)\(\s*(?:" + _LIT + r")\s*[,)]")
JS_TN = re.compile(r"\btn\(\s*[^,()]+?,\s*(?:" + _LIT + r")\s*,\s*(?:" + _LIT + r")")
FRAME_EXTS = (".html", ".js")
PY_DIRS = ("handlers", "lib", "jobs")
FRAME_DIRS = ("ui", "ui-src")
def core_dir() -> pathlib.Path:
return pathlib.Path(os.environ.get("AI_AGENT_DIR") or pathlib.Path.home() / "projects" / "ai-agent")
# ── reading a plugin ─────────────────────────────────────────────────────────
def manifest(root: pathlib.Path) -> dict[str, Any]:
return json.loads((root / "plugin.json").read_text(encoding="utf-8"))
def resolve(arg: str) -> pathlib.Path:
p = pathlib.Path(arg)
if (p / "plugin.json").is_file():
return p.resolve()
if (PLUGINS / arg / "plugin.json").is_file():
return PLUGINS / arg
sys.exit(f"no plugin at {arg}")
def contract_plugins(args: list[str] | None = None) -> list[pathlib.Path]:
if args:
return [resolve(a) for a in args]
return [p for p in sorted(PLUGINS.iterdir())
if (p / "plugin.json").is_file() and manifest(p).get("i18n")]
def i18n_dir(root: pathlib.Path) -> pathlib.Path:
return root / manifest(root)["i18n"]
def load(path: pathlib.Path, default: Any) -> Any:
try:
return json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return default
def langs_of(d: pathlib.Path) -> list[str]:
return sorted(m.group(1) for p in d.glob("*.json")
if (m := LANG_FILE.match(p.name)) and m.group(1) != "en")
def _js_unescape(raw: str) -> str:
raw = raw.replace("\\'", "'")
try:
return json.loads('"' + raw + '"')
except ValueError:
return raw
def _js_keys(text: str) -> list[str]:
out = []
for m in JS_T.finditer(text):
out.append(_js_unescape(m.group(1) if m.group(1) is not None else m.group(2)))
for m in JS_TN.finditer(text):
a = m.group(1) if m.group(1) is not None else m.group(2)
b = m.group(3) if m.group(3) is not None else m.group(4)
out += [_js_unescape(a), _js_unescape(b)]
return out
def _py_keys(text: str) -> list[str]:
out = []
try:
tree = ast.parse(text)
except SyntaxError:
return out
for node in ast.walk(tree):
if not isinstance(node, ast.Call):
continue
f = node.func
name = f.id if isinstance(f, ast.Name) else f.attr if isinstance(f, ast.Attribute) else ""
args = node.args
if name == "msg" and args and isinstance(args[0], ast.Constant) and isinstance(args[0].value, str):
out.append(args[0].value)
elif name in ("t", "tr") and args:
# ``t(lang, "…")`` or a bound helper's ``caller.t("…")``
lit = args[0] if isinstance(args[0], ast.Constant) else (args[1] if len(args) > 1 else None)
if isinstance(lit, ast.Constant) and isinstance(lit.value, str):
out.append(lit.value)
return out
def _manifest_keys(mf: dict[str, Any]) -> list[str]:
out = [mf.get("name"), mf.get("description")]
for pg in (mf.get("ui") or {}).get("pages") or []:
out += [pg.get("label"), pg.get("description")]
# the conversation card bits the app draws (``{field|fmt}`` slots kept)
for b in (mf.get("ui") or {}).get("card") or []:
out += [b.get("text"), b.get("title")]
# a list bit's wording (``ui.card[].list``: every text but its tracker)
lst = b.get("list")
if isinstance(lst, dict):
out += [v for k, v in lst.items() if k not in ("tracker", "group")]
st = mf.get("settings") or {}
out.append(st.get("subtitle"))
for f in st.get("fields") or []:
out += [f.get("label"), f.get("help")]
return [s for s in out if isinstance(s, str) and s.strip()]
def source_keys(root: pathlib.Path) -> list[str]:
"""Every English string of the plugin, sorted, once."""
keys = set(_manifest_keys(manifest(root)))
for sub in FRAME_DIRS:
for p in sorted((root / sub).rglob("*")) if (root / sub).is_dir() else []:
# a built document is its sources: read ui-src/, skip the build
if sub == "ui" and (root / "ui-src").is_dir():
continue
if p.suffix in FRAME_EXTS and p.is_file():
keys.update(_js_keys(p.read_text(encoding="utf-8", errors="replace")))
for sub in PY_DIRS:
for p in sorted((root / sub).rglob("*.py")) if (root / sub).is_dir() else []:
keys.update(_py_keys(p.read_text(encoding="utf-8", errors="replace")))
return sorted(k for k in keys if k)
def _vars(s: str) -> list[str]:
return sorted(VARS.findall(re.sub(r"^[^|{]*\|", "", s)))
# ── the targets: (label, english keys, dict path) ────────────────────────────
def plugin_targets(roots: list[pathlib.Path], only: set[str] | None = None) -> list[dict[str, Any]]:
out = []
for root in roots:
d = i18n_dir(root)
keys = load(d / "en.json", [])
pid = manifest(root)["id"]
for lang in langs_of(d):
if only is not None and f"{pid}:{lang}" not in only and pid not in only:
continue
out.append({"kind": "plugin", "plugin": pid, "lang": lang, "keys": keys,
"file": d / f"{lang}.json"})
# a language asked for that has no file yet: start one
for want in (only or set()):
if want.startswith(pid + ":") and want.split(":", 1)[1] not in langs_of(d):
out.append({"kind": "plugin", "plugin": pid, "lang": want.split(":", 1)[1],
"keys": keys, "file": d / f"{want.split(':', 1)[1]}.json"})
return out
def translation_targets(ids: list[str] | None) -> list[dict[str, Any]]:
out = []
keys_dir = core_dir() / "backend" / "core" / "i18n_keys"
for root in sorted(PLUGINS.iterdir()):
if not (root / "plugin.json").is_file():
continue
mf = manifest(root)
if mf.get("kind") != "translation" or (ids is not None and mf["id"] not in ids):
continue
tv = mf["translation"]
for part in ("ui", "backend"):
if tv.get(part):
out.append({"kind": "translation", "plugin": mf["id"], "lang": tv["lang"], "part": part,
"keys": load(keys_dir / f"{part}.json", []), "file": root / tv[part]})
return out
def state(t: dict[str, Any]) -> dict[str, Any]:
d = load(t["file"], {})
keys = t["keys"]
wanted = set(keys)
return {"plugin": t["plugin"], "lang": t["lang"], "part": t.get("part"), "kind": t["kind"],
"file": str(t["file"].relative_to(REPO)) if t["file"].is_relative_to(REPO) else str(t["file"]),
"total": len(keys),
"missing": [k for k in keys if k not in d],
"stale": [k for k in d if k not in wanted],
"placeholders": [k for k, v in d.items() if k in wanted and _vars(k) != _vars(v)]}
def write_dict(path: pathlib.Path, d: dict[str, str]) -> None:
"""Written in the file's own indentation (translation-fr's is 1), so a
pass's diff is only the lines it changed."""
indent, nl = 2, "\n"
try:
old = path.read_text(encoding="utf-8")
m = re.search(r"\n( +)\"", old[:400])
indent = len(m.group(1)) if m else 2
nl = "\n" if old.endswith("\n") else ""
except OSError:
pass
path.write_text(json.dumps(d, ensure_ascii=False, indent=indent) + nl, encoding="utf-8")
# ── commands ─────────────────────────────────────────────────────────────────
def cmd_keys(a) -> int:
for root in contract_plugins(a.plugins):
d = i18n_dir(root)
d.mkdir(exist_ok=True)
keys = source_keys(root)
(d / "en.json").write_text(json.dumps(keys, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(f"{root.name}: {len(keys)} English strings")
return 0
def check_plugin(root: pathlib.Path, strict: bool) -> list[str]:
problems = []
mf = manifest(root)
d = i18n_dir(root)
if not (d / "en.json").is_file():
return [f"{root.name}: {mf['i18n']}/en.json is missing (run `plugin_i18n.py keys {root.name}`)"]
if load(d / "en.json", None) != source_keys(root):
problems.append(f"{root.name}: en.json is out of step with the sources (run `plugin_i18n.py keys {root.name}`)")
want_langs = ["en", *langs_of(d)]
if mf.get("languages", ["en"]) != want_langs:
problems.append(f"{root.name}: languages must be {want_langs} (English + one per file)")
for t in plugin_targets([root]):
s = state(t)
if s["placeholders"]:
problems.append(f"{root.name} {s['lang']}: other placeholders in {s['placeholders'][:5]}")
if strict and s["missing"]:
problems.append(f"{root.name} {s['lang']}: {len(s['missing'])} missing, e.g. {s['missing'][:3]}")
if strict and s["stale"]:
problems.append(f"{root.name} {s['lang']}: {len(s['stale'])} stale, e.g. {s['stale'][:3]}")
return problems
def cmd_check(a) -> int:
problems = [p for root in contract_plugins(a.plugins) for p in check_plugin(root, a.strict)]
for p in problems:
print(p)
if not problems:
print("ok")
return 1 if problems else 0
def _targets(a) -> list[dict[str, Any]]:
out: list[dict[str, Any]] = []
if a.plugin or not a.translation:
only = set(a.plugin) if a.plugin else None
roots = [resolve(p.split(":", 1)[0]) for p in a.plugin] if a.plugin else contract_plugins()
out += plugin_targets(sorted(set(roots)), only)
if a.translation or not a.plugin:
out += translation_targets(a.translation or None)
return out
def cmd_todo(a) -> int:
rows = [state(t) for t in _targets(a)]
if a.json:
print(json.dumps(rows, ensure_ascii=False, indent=2))
return 0
for s in rows:
tag = f"{s['plugin']} {s['lang']}" + (f" ({s['part']})" if s["part"] else "")
print(f"{tag}: {len(s['missing'])} missing, {len(s['stale'])} stale, "
f"{len(s['placeholders'])} placeholder mismatches — {s['file']}")
return 0
def cmd_prune(a) -> int:
for t in _targets(a):
d = load(t["file"], {})
wanted = set(t["keys"])
if not wanted:
print(f"{t['plugin']} {t['lang']}: no English list found, left alone")
continue
kept = {k: v for k, v in d.items() if k in wanted}
if len(kept) != len(d):
write_dict(t["file"], kept)
print(f"{t['plugin']} {t['lang']}{' ' + t['part'] if t.get('part') else ''}: "
f"removed {len(d) - len(kept)} stale")
return 0
def cmd_apply(a) -> int:
if a.translation:
ts = [t for t in translation_targets([a.translation]) if t.get("part") == a.part]
else:
pid, _, lang = a.plugin.partition(":")
root = resolve(pid)
ts = [t for t in plugin_targets([root], {f"{manifest(root)['id']}:{lang}"}) if t["lang"] == lang]
if len(ts) != 1:
sys.exit("name one target: --plugin P:LANG, or --translation ID --part ui|backend")
t = ts[0]
adds = load(pathlib.Path(a.file), None)
if not isinstance(adds, dict):
sys.exit(f"{a.file}: a JSON object {{English: translation}} is expected")
d = load(t["file"], {})
wanted = set(t["keys"])
refused = []
added = 0
for k, v in adds.items():
if k not in wanted:
refused.append(f"not an English string of this target: {k!r}")
elif not isinstance(v, str) or not v.strip():
refused.append(f"empty translation: {k!r}")
elif _vars(k) != _vars(v):
refused.append(f"placeholders differ: {k!r} → {v!r}")
elif k in d:
refused.append(f"already translated (left as is): {k!r}")
else:
d[k] = v
added += 1
if t["kind"] == "plugin":
d = dict(sorted(d.items()))
root = t["file"].parent.parent
mf_path = root / "plugin.json"
mf = manifest(root)
if t["lang"] not in mf.get("languages", ["en"]) and added:
text = mf_path.read_text(encoding="utf-8")
new = ["en", *sorted({*mf.get("languages", ["en"]), t["lang"]} - {"en"})]
text2 = re.sub(r'"languages"\s*:\s*\[[^\]]*\]', '"languages": ' + json.dumps(new), text, count=1)
if text2 == text:
text2 = text.replace('"i18n":', '"languages": ' + json.dumps(new) + ',\n "i18n":', 1)
mf_path.write_text(text2, encoding="utf-8")
t["file"].parent.mkdir(parents=True, exist_ok=True)
write_dict(t["file"], d)
print(f"{t['plugin']} {t['lang']}{' ' + t['part'] if t.get('part') else ''}: added {added}")
for r in refused:
print(" refused —", r)
return 1 if refused else 0
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
sub = ap.add_subparsers(dest="cmd", required=True)
k = sub.add_parser("keys")
k.add_argument("plugins", nargs="*")
c = sub.add_parser("check")
c.add_argument("--strict", action="store_true")
c.add_argument("plugins", nargs="*")
for name in ("todo", "prune"):
p = sub.add_parser(name)
p.add_argument("--plugin", action="append", default=[], help="PLUGIN:LANG (or PLUGIN)")
p.add_argument("--translation", action="append", default=[], help="a translation plugin's id")
if name == "todo":
p.add_argument("--json", action="store_true")
ap_ = sub.add_parser("apply")
ap_.add_argument("--plugin", default="")
ap_.add_argument("--translation", default="")
ap_.add_argument("--part", choices=("ui", "backend"))
ap_.add_argument("file")
a = ap.parse_args(argv)
return {"keys": cmd_keys, "check": cmd_check, "todo": cmd_todo, "prune": cmd_prune,
"apply": cmd_apply}[a.cmd](a)
if __name__ == "__main__":
sys.exit(main())