Phase 7: languages

- Complete Spanish (neutral Latin American, Paraguay friendly, no
  inverted marks) and Dutch catalogs, including the Mini App and owner texts
- Command menus per language in three scopes (private, group members,
  group admins); per-chat menus follow a user's /language and a group's
  /grouplang, from chat and from the Mini App
- Bot name, description and short description per language, sent only
  when the catalog text changes (TELEGRAM_SET_PROFILE)
- Dates from the catalog, numbers, sizes and durations per locale
- Pseudo-locale en-XA generated from English (I18N_PSEUDO), owners only
- Catalog checks: completeness, placeholders, tags, commands, plurals,
  Telegram length limits, untranslated text, unused and missing IDs
- CI workflow; make i18n-check; docs/TRANSLATING.md
- Test fix: the queued-download helper could match another chat's status

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-11-18 17:42:31 +00:00
co-authored by Claude Opus 5.5
parent 4f11f939a0
commit f1f9c6156c
27 changed files with 3217 additions and 71 deletions
+24 -4
View File
@@ -2,6 +2,8 @@ package i18n
import (
"fmt"
"strconv"
"strings"
"time"
)
@@ -77,8 +79,26 @@ func (b *Bundle) Sats(lang string, n int64) string {
return b.T(lang, "unit.sats", Args{"Count": n, "N": b.Number(lang, n)})
}
// DateTime formats a point in time. The numeric form reads the same in
// every language and always states the time zone.
func (b *Bundle) DateTime(_ string, t time.Time) string {
return t.UTC().Format("2006-01-02 15:04") + " UTC"
// DateTime formats a point in time the way the language writes dates,
// from format.datetime and format.months in its catalog. It is always in
// UTC and says so: the bot does not know the reader's time zone.
func (b *Bundle) DateTime(lang string, t time.Time) string {
return b.T(lang, "format.datetime", b.dateArgs(lang, t))
}
// Date formats a day, from format.date and format.months.
func (b *Bundle) Date(lang string, t time.Time) string {
return b.T(lang, "format.date", b.dateArgs(lang, t))
}
func (b *Bundle) dateArgs(lang string, t time.Time) Args {
t = t.UTC()
month := strconv.Itoa(int(t.Month()))
if names := strings.Split(b.T(lang, "format.months", nil), ","); len(names) == 12 {
month = strings.TrimSpace(names[t.Month()-1])
}
return Args{
"Day": t.Day(), "Month": month, "MonthNumber": fmt.Sprintf("%02d", int(t.Month())), "Year": t.Year(),
"Hour": fmt.Sprintf("%02d", t.Hour()), "Minute": fmt.Sprintf("%02d", t.Minute()),
}
}
+29 -2
View File
@@ -3,6 +3,7 @@
package i18n
import (
"bytes"
"fmt"
"html"
"io/fs"
@@ -34,6 +35,7 @@ type Bundle struct {
names []string
matcher language.Matcher
log *slog.Logger
opts []Option
// raw keeps each catalog as parsed TOML, for exporting the Mini App's
// messages to the browser.
raw map[string]map[string]any
@@ -43,13 +45,27 @@ type Bundle struct {
printers map[string]*message.Printer
}
// Option changes how catalogs are loaded.
type Option func(*options)
type options struct{ pseudo bool }
// WithPseudo adds the pseudo-locale (Pseudo), made from the English
// catalog, for testing translations.
func WithPseudo() Option { return func(o *options) { o.pseudo = true } }
// Load reads every *.toml catalog in fsys. The file name is the language
// tag, for example en.toml or es.toml.
func Load(fsys fs.FS, log *slog.Logger) (*Bundle, error) {
func Load(fsys fs.FS, log *slog.Logger, opts ...Option) (*Bundle, error) {
if log == nil {
log = slog.Default()
}
var o options
for _, opt := range opts {
opt(&o)
}
b := &Bundle{
opts: opts,
bundle: goi18n.NewBundle(language.English),
log: log,
localizers: map[string]*goi18n.Localizer{},
@@ -83,6 +99,17 @@ func Load(fsys fs.FS, log *slog.Logger) (*Bundle, error) {
if !hasDefault {
return nil, fmt.Errorf("i18n: the %s catalog is missing", Default)
}
if o.pseudo {
doc := pseudoDoc(b.raw[Default], "")
var buf bytes.Buffer
if err := toml.NewEncoder(&buf).Encode(doc); err != nil {
return nil, fmt.Errorf("i18n: pseudo-locale: %w", err)
}
if _, err := b.bundle.ParseMessageFileBytes(buf.Bytes(), Pseudo+".toml"); err != nil {
return nil, fmt.Errorf("i18n: pseudo-locale: %w", err)
}
b.raw[Pseudo] = doc
}
// English first, so it is the matcher's default.
b.tags = []language.Tag{language.English}
for _, t := range b.bundle.LanguageTags() {
@@ -109,7 +136,7 @@ func (b *Bundle) Hidden(lang string) bool { return strings.EqualFold(lang, Pseud
// Reload replaces the catalogs with the ones in fsys. When they do not
// load, the old ones stay in use and the error says why.
func (b *Bundle) Reload(fsys fs.FS) error {
fresh, err := Load(fsys, b.log)
fresh, err := Load(fsys, b.log, b.opts...)
if err != nil {
return err
}
+93
View File
@@ -200,3 +200,96 @@ func TestDir(t *testing.T) {
}
}
}
func TestPseudoLocale(t *testing.T) {
b, err := i18n.Load(locales.FS, nil, i18n.WithPseudo())
if err != nil {
t.Fatal(err)
}
if !b.Hidden(i18n.Pseudo) {
t.Fatal("the pseudo-locale must be hidden from users")
}
found := false
for _, l := range b.Langs() {
found = found || l == i18n.Pseudo
}
if !found {
t.Fatalf("languages = %v, want %s among them", b.Langs(), i18n.Pseudo)
}
got := b.HTML(i18n.Pseudo, "start.private", i18n.Args{"Name": "Ana"})
if !strings.Contains(got, "<b>") || !strings.Contains(got, "Ana") || !strings.Contains(got, "/help") ||
strings.Contains(got, "welcome") || !strings.Contains(got, "[") {
t.Fatalf("pseudo start = %q", got)
}
// Plurals keep working.
if one, many := b.T(i18n.Pseudo, "unit.sats", i18n.Args{"Count": 1, "N": "1"}), b.T(i18n.Pseudo, "unit.sats", i18n.Args{"Count": 5, "N": "5"}); one == many || !strings.Contains(many, "5") {
t.Fatalf("pseudo plurals = %q, %q", one, many)
}
if d := b.DateTime(i18n.Pseudo, time.Date(2026, 3, 4, 5, 6, 0, 0, time.UTC)); !strings.Contains(d, "Ṁáŕ") || !strings.Contains(d, "05:06") {
t.Fatalf("pseudo date = %q", d)
}
// The Mini App gets it too.
if s, _ := b.Section(i18n.Pseudo, "app")["tab.home"].(string); !strings.HasPrefix(s, "[Ĥöḿé") {
t.Fatalf("pseudo app text = %q", s)
}
// Without the option it does not exist.
plain := load(t)
for _, l := range plain.Langs() {
if l == i18n.Pseudo {
t.Fatal("the pseudo-locale is loaded without being asked for")
}
}
}
func TestPseudolocalizeKeepsMarkup(t *testing.T) {
for in, want := range map[string]string{
"Hi {{.Name}}": "[Ĥî {{.Name}} ~]",
"<b>Paid</b> &amp; done": "[<b>Þáîð</b> &amp; ðöñé ~~~]",
"Try /help or https://x.y/a?b=c": "[Ţŕý /help öŕ https://x.y/a?b=c ~~]",
"\nTwo\nlines\n": "\n[Ţŵö\nļîñéš ~~~]\n",
} {
if got := i18n.Pseudolocalize(in); got != want {
t.Errorf("Pseudolocalize(%q) = %q, want %q", in, got, want)
}
}
}
func TestDatesFollowTheCatalog(t *testing.T) {
b := load(t)
at := time.Date(2026, 11, 18, 9, 5, 0, 0, time.FixedZone("PYT", -3*3600))
if got := b.DateTime("en", at); got != "18 Nov 2026, 12:05 UTC" {
t.Errorf("en = %q", got)
}
if got := b.Date("en", at); got != "18 Nov 2026" {
t.Errorf("en date = %q", got)
}
for lang, want := range map[string]string{"es": "18 nov 2026, 12:05 UTC", "es-PY": "18 nov 2026, 12:05 UTC", "nl": "18 nov 2026, 12:05 UTC"} {
if got := b.DateTime(lang, at); got != want {
t.Errorf("%s = %q, want %q", lang, got, want)
}
}
if got := b.DateTime("nl", time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC)); got != "1 mrt 2026, 00:00 UTC" {
t.Errorf("nl March = %q", got)
}
}
func TestNumbersAndUnitsPerLanguage(t *testing.T) {
b := load(t)
cases := []struct{ lang, got, want string }{
{"en", b.Sats("en", 10000), "10,000 sats"},
{"es", b.Sats("es", 10000), "10.000 sats"},
{"nl", b.Sats("nl", 10000), "10.000 sats"},
{"es", b.Sats("es", 1), "1 sat"},
{"es", b.Size("es", 5<<20), "5,0 MB"},
{"nl", b.Size("nl", 3<<29), "1,50 GB"},
{"es", b.Span("es", 5*time.Minute), "5 minutos"},
{"nl", b.Span("nl", time.Minute), "1 minuut"},
{"nl", b.Span("nl", 3*time.Hour), "3 uur"},
{"es-PY", b.T("es-PY", "status.done", nil), "Listo. Que lo disfrutes."},
}
for _, c := range cases {
if c.got != c.want {
t.Errorf("%s: %q, want %q", c.lang, c.got, c.want)
}
}
}
+87
View File
@@ -0,0 +1,87 @@
package i18n
import (
"regexp"
"strings"
)
// The pseudo-locale is made from the English catalog when the bundle is
// loaded with WithPseudo. Every letter gets an accent and every message is
// wrapped in brackets and made about a third longer. Switch to it and any
// text that still looks like plain English did not come from the catalog,
// any text cut off at the bracket is too long for its place, and broken
// accents point at an encoding problem.
var accents = map[rune]rune{
'a': 'á', 'b': 'ƀ', 'c': 'ç', 'd': 'ð', 'e': 'é', 'f': 'ƒ', 'g': 'ĝ', 'h': 'ĥ', 'i': 'î', 'j': 'ĵ',
'k': 'ķ', 'l': 'ļ', 'm': 'ḿ', 'n': 'ñ', 'o': 'ö', 'p': 'þ', 'q': 'ǫ', 'r': 'ŕ', 's': 'š', 't': 'ţ',
'u': 'û', 'v': 'ṽ', 'w': 'ŵ', 'x': 'ẋ', 'y': 'ý', 'z': 'ž',
'A': 'Å', 'B': 'Ɓ', 'C': 'Ç', 'D': 'Ð', 'E': 'É', 'F': 'Ƒ', 'G': 'Ĝ', 'H': 'Ĥ', 'I': 'Î', 'J': 'Ĵ',
'K': 'Ķ', 'L': 'Ļ', 'M': 'Ṁ', 'N': 'Ñ', 'O': 'Ö', 'P': 'Þ', 'Q': 'Ǫ', 'R': 'Ŕ', 'S': 'Š', 'T': 'Ţ',
'U': 'Û', 'V': 'Ṽ', 'W': 'Ŵ', 'X': 'Ẋ', 'Y': 'Ý', 'Z': 'Ž',
}
// keep matches what must survive unchanged: placeholders, HTML tags and
// entities, bot commands, links, and the list separators of format.months.
var keep = regexp.MustCompile(`\{\{[^}]*\}\}|</?[a-zA-Z][^>]*>|&[a-z]+;|/[a-z_]+|https?://\S+|@\w+|,`)
// Pseudolocalize turns one English message into its pseudo-locale form.
func Pseudolocalize(s string) string {
var sb strings.Builder
letters := 0
last := 0
for _, loc := range keep.FindAllStringIndex(s, -1) {
letters += accentInto(&sb, s[last:loc[0]])
sb.WriteString(s[loc[0]:loc[1]])
last = loc[1]
}
letters += accentInto(&sb, s[last:])
body := sb.String()
// Leading and trailing line breaks stay outside the brackets.
trimmed := strings.Trim(body, "\n")
lead := body[:strings.Index(body, trimmed)]
trail := body[len(lead)+len(trimmed):]
pad := strings.Repeat("~", (letters+2)/3)
return lead + "[" + trimmed + " " + pad + "]" + trail
}
func accentInto(sb *strings.Builder, s string) int {
n := 0
for _, r := range s {
if a, ok := accents[r]; ok {
sb.WriteRune(a)
n++
} else {
sb.WriteRune(r)
}
}
return n
}
// pseudoDoc applies Pseudolocalize to every text of a parsed catalog.
// format.months is a list, not a sentence: its names are accented without
// brackets so it still splits into twelve.
func pseudoDoc(in map[string]any, path string) map[string]any {
out := make(map[string]any, len(in))
for k, v := range in {
key := k
if path != "" {
key = path + "." + k
}
switch x := v.(type) {
case string:
if key == "format.months" {
var sb strings.Builder
accentInto(&sb, x)
out[k] = sb.String()
} else {
out[k] = Pseudolocalize(x)
}
case map[string]any:
out[k] = pseudoDoc(x, key)
default:
out[k] = v
}
}
return out
}