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:
co-authored by
Claude Opus 5.5
parent
4f11f939a0
commit
f1f9c6156c
@@ -0,0 +1,447 @@
|
||||
package locales_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
|
||||
"github.com/noderunners/dlbot/locales"
|
||||
)
|
||||
|
||||
// These tests are the translation checks CI runs. They fail when a catalog
|
||||
// is missing a message, has one the source does not have, changed a
|
||||
// placeholder or a tag, or when the code and the source catalog disagree
|
||||
// about which messages exist.
|
||||
|
||||
const source = "en"
|
||||
|
||||
// required are the languages that must ship complete.
|
||||
var required = []string{"en", "es", "nl"}
|
||||
|
||||
var pluralForms = map[string]bool{"zero": true, "one": true, "two": true, "few": true, "many": true, "other": true}
|
||||
|
||||
// catalog is a flattened catalog: message ID to its forms. A plain
|
||||
// message has the single form "".
|
||||
type catalog map[string]map[string]string
|
||||
|
||||
func flatten(prefix string, in map[string]any, out catalog) {
|
||||
for k, v := range in {
|
||||
key := k
|
||||
if prefix != "" {
|
||||
key = prefix + "." + k
|
||||
}
|
||||
switch x := v.(type) {
|
||||
case string:
|
||||
out[key] = map[string]string{"": x}
|
||||
case map[string]any:
|
||||
plural := len(x) > 0
|
||||
for form, text := range x {
|
||||
if _, ok := text.(string); !ok || !pluralForms[form] {
|
||||
plural = false
|
||||
}
|
||||
}
|
||||
if !plural {
|
||||
flatten(key, x, out)
|
||||
continue
|
||||
}
|
||||
forms := map[string]string{}
|
||||
for form, text := range x {
|
||||
forms[form] = text.(string)
|
||||
}
|
||||
out[key] = forms
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func loadCatalogs(t *testing.T) map[string]catalog {
|
||||
t.Helper()
|
||||
files, err := fs.Glob(locales.FS, "*.toml")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := map[string]catalog{}
|
||||
for _, name := range files {
|
||||
data, err := fs.ReadFile(locales.FS, name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var doc map[string]any
|
||||
if err := toml.Unmarshal(data, &doc); err != nil {
|
||||
t.Fatalf("%s: %v", name, err)
|
||||
}
|
||||
c := catalog{}
|
||||
flatten("", doc, c)
|
||||
out[strings.TrimSuffix(name, ".toml")] = c
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func keys[V any](m map[string]V) []string {
|
||||
out := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
out = append(out, k)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
var (
|
||||
placeholder = regexp.MustCompile(`\{\{\s*\.(\w+)\s*\}\}`)
|
||||
anyBraces = regexp.MustCompile(`\{\{[^}]*\}\}`)
|
||||
htmlTag = regexp.MustCompile(`</?[a-zA-Z][^>]*>`)
|
||||
codeBlock = regexp.MustCompile(`(?s)<code>.*?</code>`)
|
||||
)
|
||||
|
||||
// marks returns the sorted placeholders and tags of all forms of a
|
||||
// message. Placeholders are compared as a set, because a plural form may
|
||||
// leave the number out ("last day"). Tags are compared one by one.
|
||||
func marks(forms map[string]string) (holders, tags string) {
|
||||
set := map[string]bool{}
|
||||
var tagList []string
|
||||
for _, form := range keys(forms) {
|
||||
for _, m := range placeholder.FindAllStringSubmatch(forms[form], -1) {
|
||||
set[m[1]] = true
|
||||
}
|
||||
if form == "" || form == "other" {
|
||||
tagList = htmlTag.FindAllString(forms[form], -1)
|
||||
}
|
||||
}
|
||||
sort.Strings(tagList)
|
||||
return strings.Join(keys(set), ","), strings.Join(tagList, "")
|
||||
}
|
||||
|
||||
func TestRequiredCatalogsExist(t *testing.T) {
|
||||
all := loadCatalogs(t)
|
||||
for _, lang := range required {
|
||||
if all[lang] == nil {
|
||||
t.Errorf("locales/%s.toml is missing", lang)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCatalogsMatchTheSource(t *testing.T) {
|
||||
all := loadCatalogs(t)
|
||||
src := all[source]
|
||||
if len(src) < 300 {
|
||||
t.Fatalf("the source catalog has only %d messages; the loader is broken", len(src))
|
||||
}
|
||||
for _, lang := range keys(all) {
|
||||
if lang == source {
|
||||
continue
|
||||
}
|
||||
cat := all[lang]
|
||||
t.Run(lang, func(t *testing.T) {
|
||||
for _, id := range keys(src) {
|
||||
forms, ok := cat[id]
|
||||
if !ok {
|
||||
t.Errorf("missing: %s", id)
|
||||
continue
|
||||
}
|
||||
srcPlural, plural := src[id][""] == "" && len(src[id]) > 0 && src[id]["other"] != "", forms["other"] != ""
|
||||
if srcPlural != plural {
|
||||
t.Errorf("%s: plural in one catalog and plain in the other", id)
|
||||
continue
|
||||
}
|
||||
if plural && forms["one"] == "" {
|
||||
t.Errorf("%s: plural message without the form \"one\"", id)
|
||||
}
|
||||
for form, text := range forms {
|
||||
if strings.TrimSpace(text) == "" {
|
||||
t.Errorf("%s %s: empty text", id, form)
|
||||
}
|
||||
// Anything in braces must be a well formed placeholder.
|
||||
for _, b := range anyBraces.FindAllString(text, -1) {
|
||||
if !placeholder.MatchString(b) {
|
||||
t.Errorf("%s: broken placeholder %s", id, b)
|
||||
}
|
||||
}
|
||||
if strings.Count(text, "{{") != len(placeholder.FindAllString(text, -1)) || strings.Count(text, "{{") != strings.Count(text, "}}") {
|
||||
t.Errorf("%s: unbalanced braces in %q", id, text)
|
||||
}
|
||||
}
|
||||
wantHolders, wantTags := marks(src[id])
|
||||
gotHolders, gotTags := marks(forms)
|
||||
if gotHolders != wantHolders {
|
||||
t.Errorf("%s: placeholders are {%s}, the source has {%s}", id, gotHolders, wantHolders)
|
||||
}
|
||||
if gotTags != wantTags {
|
||||
t.Errorf("%s: tags are %s, the source has %s", id, gotTags, wantTags)
|
||||
}
|
||||
// Commands are the same in every language.
|
||||
if cmds, want := commandsIn(forms), commandsIn(src[id]); cmds != want {
|
||||
t.Errorf("%s: commands are [%s], the source has [%s]", id, cmds, want)
|
||||
}
|
||||
}
|
||||
for _, id := range keys(cat) {
|
||||
if _, ok := src[id]; !ok {
|
||||
t.Errorf("not in the source catalog: %s", id)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var slashCommand = regexp.MustCompile(`(?:^|[\s(>])(/[a-z_]+)\b`)
|
||||
|
||||
func commandsIn(forms map[string]string) string {
|
||||
set := map[string]bool{}
|
||||
for _, text := range forms {
|
||||
for _, m := range slashCommand.FindAllStringSubmatch(text, -1) {
|
||||
set[m[1]] = true
|
||||
}
|
||||
}
|
||||
return strings.Join(keys(set), " ")
|
||||
}
|
||||
|
||||
// TestCatalogRules checks what holds for every catalog, the source
|
||||
// included: Telegram's length limits and the project's writing rules.
|
||||
func TestCatalogRules(t *testing.T) {
|
||||
all := loadCatalogs(t)
|
||||
names := map[string]string{}
|
||||
for _, lang := range keys(all) {
|
||||
cat := all[lang]
|
||||
text := func(id string) string { return cat[id][""] }
|
||||
limit := func(id string, min, max int) {
|
||||
if n := utf8.RuneCountInString(text(id)); n < min || n > max {
|
||||
t.Errorf("%s: %s is %d characters, Telegram allows %d to %d", lang, id, n, min, max)
|
||||
}
|
||||
}
|
||||
for id, forms := range cat {
|
||||
for _, s := range forms {
|
||||
if strings.Contains(s, "\u2014") {
|
||||
t.Errorf("%s: %s contains an em dash", lang, id)
|
||||
}
|
||||
// Spanish is written without the opening marks here.
|
||||
if strings.HasPrefix(lang, "es") && strings.ContainsAny(s, "¿¡") {
|
||||
t.Errorf("%s: %s has an inverted question or exclamation mark", lang, id)
|
||||
}
|
||||
if s != strings.TrimSpace(s) && !strings.HasPrefix(s, "\n") {
|
||||
t.Errorf("%s: %s has stray space around it", lang, id)
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case strings.HasPrefix(id, "menu."):
|
||||
limit(id, 1, 256)
|
||||
if strings.ContainsAny(text(id), "<>\n") {
|
||||
t.Errorf("%s: %s must be one line of plain text", lang, id)
|
||||
}
|
||||
case strings.HasPrefix(id, "btn.") || strings.HasPrefix(id, "product."):
|
||||
// Button labels share a row; long ones get cut off.
|
||||
if n := utf8.RuneCountInString(text(id)); n > 40 {
|
||||
t.Errorf("%s: %s is %d characters, too long for a button", lang, id, n)
|
||||
}
|
||||
}
|
||||
}
|
||||
limit("profile.name", 1, 64)
|
||||
limit("profile.about", 1, 512)
|
||||
limit("profile.short", 1, 120)
|
||||
if n := len(strings.Split(text("format.months"), ",")); n != 12 {
|
||||
t.Errorf("%s: format.months has %d entries, want 12", lang, n)
|
||||
}
|
||||
name := text("language.name")
|
||||
if other, dup := names[name]; dup || name == "" {
|
||||
t.Errorf("%s: language.name %q is empty or the same as in %s", lang, name, other)
|
||||
}
|
||||
names[name] = lang
|
||||
}
|
||||
}
|
||||
|
||||
// sameEverywhere are messages that are meant to read the same in every
|
||||
// language, such as the brand name in the invoice memo.
|
||||
var sameEverywhere = map[string]bool{"invoice.memo": true}
|
||||
|
||||
// TestCatalogsAreTranslated catches a catalog that is a copy of the
|
||||
// source with a few lines changed. Short labels are often the same in two
|
||||
// languages, so only longer texts count.
|
||||
func TestCatalogsAreTranslated(t *testing.T) {
|
||||
all := loadCatalogs(t)
|
||||
src := all[source]
|
||||
for _, lang := range keys(all) {
|
||||
if lang == source {
|
||||
continue
|
||||
}
|
||||
var same []string
|
||||
long := 0
|
||||
for id, forms := range all[lang] {
|
||||
text := forms[""] + forms["other"]
|
||||
// Code samples, placeholders and markup are the same in every
|
||||
// language; only the words around them count.
|
||||
words := codeBlock.ReplaceAllString(text, " ")
|
||||
words = placeholder.ReplaceAllString(words, " ")
|
||||
words = htmlTag.ReplaceAllString(words, " ")
|
||||
if len(strings.Fields(words)) < 4 {
|
||||
continue
|
||||
}
|
||||
long++
|
||||
if text == src[id][""]+src[id]["other"] && !sameEverywhere[id] {
|
||||
same = append(same, id)
|
||||
}
|
||||
}
|
||||
sort.Strings(same)
|
||||
if len(same) > 0 {
|
||||
t.Errorf("%s: %d of %d longer messages are identical to the source: %s", lang, len(same), long, strings.Join(same, ", "))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- code and catalog agree ------------------------------------------------
|
||||
|
||||
func repoRoot(t *testing.T) string {
|
||||
t.Helper()
|
||||
dir, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for {
|
||||
if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
|
||||
return dir
|
||||
}
|
||||
parent := filepath.Dir(dir)
|
||||
if parent == dir {
|
||||
t.Fatal("go.mod not found")
|
||||
}
|
||||
dir = parent
|
||||
}
|
||||
}
|
||||
|
||||
var stringLiteral = regexp.MustCompile("\"((?:[^\"\\\\\n]|\\\\.)*)\"")
|
||||
|
||||
// literals collects every string literal of the code that could name a
|
||||
// message: Go under cmd and internal (tests excluded), and the Mini App.
|
||||
func literals(t *testing.T) map[string][]string {
|
||||
t.Helper()
|
||||
root := repoRoot(t)
|
||||
out := map[string][]string{}
|
||||
for _, dir := range []string{"cmd", "internal", "web/miniapp/src"} {
|
||||
err := filepath.WalkDir(filepath.Join(root, dir), func(path string, d fs.DirEntry, err error) error {
|
||||
if err != nil || d.IsDir() {
|
||||
return err
|
||||
}
|
||||
ext := filepath.Ext(path)
|
||||
if (ext != ".go" && ext != ".ts" && ext != ".tsx") || strings.HasSuffix(path, "_test.go") {
|
||||
return nil
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rel, _ := filepath.Rel(root, path)
|
||||
for _, m := range stringLiteral.FindAllStringSubmatch(string(data), -1) {
|
||||
// The group commands mark a refusal with a leading "!".
|
||||
lit := strings.TrimPrefix(m[1], "!")
|
||||
out[lit] = append(out[lit], rel)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
var keyShape = regexp.MustCompile(`^[a-z][a-z0-9_]*(\.[a-z0-9_]+)+$`)
|
||||
|
||||
var suffixShape = regexp.MustCompile(`^\.[a-z0-9_]+$`)
|
||||
|
||||
// isPrefix reports whether a literal is the start of message IDs built at
|
||||
// run time: "error." + code, "settings.who_" + value.
|
||||
func isPrefix(lit string) bool {
|
||||
return (strings.HasSuffix(lit, ".") || strings.HasSuffix(lit, "_")) && keyShape.MatchString(lit+"x")
|
||||
}
|
||||
|
||||
// TestEveryMessageIsUsed fails for a message no code asks for. A message
|
||||
// counts as used when its ID is written out in the code, or when the code
|
||||
// builds IDs it would match: from a prefix ("error." + code) or from a
|
||||
// suffix (name + ".list").
|
||||
func TestEveryMessageIsUsed(t *testing.T) {
|
||||
src := loadCatalogs(t)[source]
|
||||
lits := literals(t)
|
||||
var prefixes, suffixes []string
|
||||
for lit := range lits {
|
||||
if isPrefix(lit) {
|
||||
prefixes = append(prefixes, lit)
|
||||
}
|
||||
if suffixShape.MatchString(lit) {
|
||||
suffixes = append(suffixes, lit)
|
||||
}
|
||||
}
|
||||
for _, id := range keys(src) {
|
||||
if _, ok := lits[id]; ok {
|
||||
continue
|
||||
}
|
||||
used := false
|
||||
for _, p := range prefixes {
|
||||
used = used || strings.HasPrefix(id, p)
|
||||
}
|
||||
for _, sfx := range suffixes {
|
||||
used = used || strings.HasSuffix(id, sfx)
|
||||
}
|
||||
if !used {
|
||||
t.Errorf("unused message: %s", id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestEveryUsedMessageExists fails for a message ID written in the code
|
||||
// that the source catalog does not have.
|
||||
func TestEveryUsedMessageExists(t *testing.T) {
|
||||
src := loadCatalogs(t)[source]
|
||||
tables := map[string]bool{}
|
||||
for id := range src {
|
||||
tables[strings.SplitN(id, ".", 2)[0]] = true
|
||||
}
|
||||
for lit, files := range literals(t) {
|
||||
if !keyShape.MatchString(lit) || !tables[strings.SplitN(lit, ".", 2)[0]] {
|
||||
continue
|
||||
}
|
||||
if _, ok := src[lit]; ok {
|
||||
continue
|
||||
}
|
||||
// A literal may also be the start of longer IDs, or something
|
||||
// that only looks like an ID (a file name).
|
||||
starts := false
|
||||
for id := range src {
|
||||
if strings.HasPrefix(id, lit+".") || strings.HasPrefix(id, lit+"_") || (isPrefix(lit) && strings.HasPrefix(id, lit)) {
|
||||
starts = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !starts && !notMessages[lit] {
|
||||
t.Errorf("%s is used in %s but is not in the source catalog", lit, strings.Join(uniq(files), ", "))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// notMessages are string literals that have the shape of a message ID and
|
||||
// start with the name of a catalog table, but are something else.
|
||||
var notMessages = map[string]bool{
|
||||
"invoice.png": true, // the file name of the QR code picture
|
||||
}
|
||||
|
||||
func uniq(in []string) []string {
|
||||
seen := map[string]bool{}
|
||||
var out []string
|
||||
for _, s := range in {
|
||||
if !seen[s] {
|
||||
seen[s] = true
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func Example_flatten() {
|
||||
c := catalog{}
|
||||
flatten("", map[string]any{"unit": map[string]any{"sats": map[string]any{"one": "{{.N}} sat", "other": "{{.N}} sats"}}, "a": map[string]any{"b": "x"}}, c)
|
||||
fmt.Println(len(c), c["a.b"][""], c["unit.sats"]["one"])
|
||||
// Output: 2 x {{.N}} sat
|
||||
}
|
||||
Reference in New Issue
Block a user