Files
openchamber-android-native/third_party/mygo/internal/i18ngen/gogen.go
T
OpenChamber 6c0ee61750 feat: port the client to MyGo native UI (0.3.0)
Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
2026-11-18 13:22:59 +08:00

213 lines
7.1 KiB
Go

package i18ngen
import (
"bytes"
"encoding/json"
"fmt"
"go/format"
"os"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"unicode"
)
// GoFile is the file of the Go accessors, in the catalogs' directory.
const GoFile = "catalog_gen.go"
// MessagesDir is the directory, in the catalogs', of the catalog of the
// source language without its metadata that the accessors of MyGo's own
// strings embed (Options.Own).
const MessagesDir = "messages"
// MessagesJSON returns the catalog of f without its metadata: its
// messages, in their order, as the accessors of MyGo's own strings embed
// them (Options.Own).
func MessagesJSON(f *File) []byte {
var b bytes.Buffer
b.WriteString("{\n")
for i, key := range f.Keys {
k, _ := json.Marshal(key)
v, _ := json.Marshal(f.Messages[key])
fmt.Fprintf(&b, " %s: %s", k, v)
if i < len(f.Keys)-1 {
b.WriteByte(',')
}
b.WriteByte('\n')
}
b.WriteString("}\n")
return b.Bytes()
}
// Go returns the Go accessors of a catalog, the source of GoFile in
// package pkg: an embed of the catalogs, a function per key that says its
// message in the language the app shows (i18n.Locale), and In, whose
// methods say them in another language. An app's catalog is registered
// with package i18n as the package initializes; a library's is a
// i18n.NewLibraryCatalog.
func Go(c *Catalog, pkg string) ([]byte, error) {
var b bytes.Buffer
w := func(format string, args ...any) { fmt.Fprintf(&b, format, args...) }
w("// Code generated by mygo generate from the catalogs in this directory. DO NOT EDIT.\n\n")
w("package %s\n\n", pkg)
usesTime := false
for _, k := range c.Keys {
for _, p := range k.Params {
usesTime = usesTime || p.Type == "DateTime"
}
}
w("import (\n\t\"embed\"\n")
if usesTime {
w("\t\"time\"\n")
}
if c.Own {
w("\t\"io/fs\"\n")
}
w("\n\t\"github.com/egoist/mygo/i18n\"\n")
if c.Own {
w("\t\"github.com/egoist/mygo/internal/i18nlink\"\n")
}
if len(c.Translations) > 0 {
w("\n\t// MyGo's own strings in the app's languages.\n")
for _, tag := range c.Translations {
w("\t_ \"github.com/egoist/mygo/locales/%s\"\n", tag)
}
}
w(")\n\n")
if c.Own {
w("%s", comment(fmt.Sprintf("messages holds %s, the messages of %s without their descriptions, which go generate writes for the catalog: every app carries it.", path.Join(MessagesDir, c.Source+".json"), c.Source)))
w("//go:embed %s/*.json\nvar messages embed.FS\n\n", MessagesDir)
} else {
w("//go:embed *.json\nvar files embed.FS\n\n")
}
doc := fmt.Sprintf("Catalog holds the messages in %s, the source language, and %s.", c.Source, languageList(c.Languages[1:]))
if len(c.Languages) == 1 && c.Namespace != "" {
doc = fmt.Sprintf("Catalog holds the messages in %s, the source language, and those of the translations added to it (Catalog.Add).", c.Source)
}
if c.Namespace == "" {
doc += " It is registered with package i18n, which makes its languages the app's."
} else {
doc += fmt.Sprintf(" Apps change them, or translate them, with keys %q in their catalogs.", c.Namespace+".<key>")
}
w("%s", comment(doc))
w("var Catalog *i18n.Catalog\n\n")
switch {
case c.Own:
w("func init() {\n\tfiles, err := fs.Sub(messages, %q)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n", MessagesDir)
w("\tc, err := i18nlink.NewLibraryCatalog(files, %q, %q)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tCatalog = c.(*i18n.Catalog)\n}\n\n", c.Source, c.Namespace)
case c.Namespace == "":
w("func init() {\n\tvar err error\n")
w("\tif Catalog, err = i18n.NewCatalog(files, %q); err != nil {\n\t\tpanic(err)\n\t}\n", c.Source)
w("\ti18n.Register(Catalog)\n}\n\n")
default:
w("func init() {\n\tvar err error\n")
w("\tif Catalog, err = i18n.NewLibraryCatalog(files, %q, %q); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n", c.Source, c.Namespace)
}
w("// Messages say the messages in one language.\ntype Messages struct{ locale string }\n\n")
w("// In returns the messages in the language of locale, as \"de\" or\n")
w("// \"zh-Hant\", or of the catalog's language that suits it best, \"\" for the\n// source language.\n")
w("func In(locale string) Messages { return Messages{locale} }\n")
for _, k := range c.Keys {
var params, names, values []string
for _, p := range k.Params {
params = append(params, p.Go+" "+types[p.Type][0])
names = append(names, p.Go)
values = append(values, strconv.Quote(p.Name)+": "+p.Go)
}
args := "nil"
if len(values) > 0 {
args = "map[string]any{" + strings.Join(values, ", ") + "}"
}
w("\n%s", goDoc(k, "the language the app shows"))
w("func %s(%s) string { return In(i18n.Locale()).%s(%s) }\n", k.GoName, strings.Join(params, ", "), k.GoName, strings.Join(names, ", "))
w("\n%s", goDoc(k, "the language of msgs"))
w("func (msgs Messages) %s(%s) string {\n\treturn Catalog.Format(msgs.locale, %q, %s)\n}\n", k.GoName, strings.Join(params, ", "), k.Name, args)
}
src, err := format.Source(b.Bytes())
if err != nil {
return nil, fmt.Errorf("formatting the Go accessors: %v", err)
}
return src, nil
}
// goDoc is the documentation of a key's function that says it in
// where: its message, then its description.
func goDoc(k *Key, where string) string {
var b strings.Builder
msg := k.Message
if len(msg) > 120 {
msg = msg[:strings.LastIndexFunc(msg[:117], func(r rune) bool { return r < 0x80 || unicode.IsSpace(r) })+1] + "…"
}
fmt.Fprintf(&b, "// %s says %s\n// in %s.\n", k.GoName, strconv.Quote(msg), where)
if desc := strings.Join(strings.Fields(k.Description), " "); desc != "" {
b.WriteString("//\n" + comment(desc))
}
return b.String()
}
// comment writes text as a Go comment, its lines wrapped at 76 columns.
func comment(text string) string {
var b strings.Builder
line := "//"
for _, word := range strings.Fields(text) {
if len(line) > 2 && len(line)+1+len(word) > 76 {
b.WriteString(line + "\n")
line = "//"
}
line += " " + word
}
b.WriteString(line + "\n")
return b.String()
}
func languageList(langs []string) string {
switch len(langs) {
case 0:
return "no other language"
case 1:
return langs[0]
}
return strings.Join(langs[:len(langs)-1], ", ") + " and " + langs[len(langs)-1]
}
var packageClause = regexp.MustCompile(`(?m)^package\s+([A-Za-z_][A-Za-z0-9_]*)`)
// PackageName returns the name of the Go package in dir: that of its Go
// files other than GoFile and tests, else one made of the directory's
// name, as "locales".
func PackageName(dir string) (string, error) {
entries, err := os.ReadDir(dir)
if err != nil {
return "", err
}
for _, e := range entries {
name := e.Name()
if e.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") || name == GoFile {
continue
}
data, err := os.ReadFile(filepath.Join(dir, name))
if err != nil {
return "", err
}
if m := packageClause.FindSubmatch(data); m != nil {
pkg := string(m[1])
if pkg == "main" {
return "", fmt.Errorf("%s is the main package: keep the catalogs in a directory of their own, as locales", dir)
}
return pkg, nil
}
}
var b strings.Builder
for _, r := range strings.ToLower(filepath.Base(dir)) {
if r >= 'a' && r <= 'z' || r >= '0' && r <= '9' && b.Len() > 0 {
b.WriteRune(r)
}
}
if b.Len() == 0 {
return "locales", nil
}
return b.String(), nil
}