Vestmore_GO/translator/translator_test.go

163 lines
3.0 KiB
Go

package translator
import (
"bytes"
"go/format"
"log"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"testing"
"text/template"
"unicode"
"github.com/nicksnyder/go-i18n/v2/i18n"
"github.com/pelletier/go-toml/v2"
)
var trTemplateStr = `
package translator
type TrCode string
// 翻译对应的标志字符串ID
const (
{{- range .}}
// {{.MessageID}}
// description: "{{.Desc}}"
{{.MessageCamelID}} TrCode = "{{.MessageID}}"
{{end}}
)
`
// type TrCode string
// const (
// a TrCode = "1"
// )
type TrCodeData struct {
MessageID string
MessageCamelID string
Desc string
}
func TestGenTrCode(t *testing.T) {
_, currentFile, _, _ := runtime.Caller(0)
currentDir := filepath.Dir(currentFile)
// 解析模板文件
tfile := filepath.Join(currentDir, "/zh_cn.toml")
createTrCode(tfile)
// log.Println(string(buf.Bytes()))
}
func TestCase(t *testing.T) {
a := TomlFileToMap("./zh_cn.toml")
b := TomlFileToMap("./en.toml")
c := TomlFileToMap("./ja.toml")
for k1, v1 := range a {
if v2, ok := b[k1]; ok {
log.Println(v1, v2)
} else {
log.Panicln("k1:", k1, "不存在")
}
if v2, ok := c[k1]; ok {
log.Println(v1, v2)
} else {
log.Panicln("k1:", k1, "不存在")
}
}
}
func createTrCode(filePath string) {
tomlFile, err := os.Open(filePath)
if err != nil {
panic(err)
}
var tomlMap map[string]any
err = toml.NewDecoder(tomlFile).Decode(&tomlMap)
if err != nil {
panic(err)
}
var datas []*TrCodeData
for key, valuesMap := range tomlMap {
values := valuesMap.(map[string]any)
data := &TrCodeData{}
data.MessageID = key
data.MessageCamelID = toCamelCase(key)
data.Desc = values["description"].(string)
datas = append(datas, data)
}
sort.Slice(datas, func(i, j int) bool {
return datas[i].MessageID < datas[j].MessageID
})
tpl := template.New("translator")
tpl.Parse(trTemplateStr)
var buf bytes.Buffer
err = tpl.Execute(&buf, datas)
if err != nil {
panic(err)
}
wdata, err := format.Source(buf.Bytes())
if err != nil {
panic(err)
}
err = os.WriteFile("./translator_gen.go", wdata, 0644)
if err != nil {
panic(err)
}
}
func TestTrOnline(t *testing.T) {
var localizer = i18n.NewLocalizer(Bundle, "zh_cn")
log.Println(localizer.Localize(&i18n.LocalizeConfig{
MessageID: string("account_not_registered"),
}))
}
func TestTrOnlinex(t *testing.T) {
var localizer = i18n.NewLocalizer(Bundle, "zh_cn")
log.Println(localizer.Localize(&i18n.LocalizeConfig{
MessageID: string("account_not_registered"),
}))
}
func toCamelCase(s string) string {
var sb strings.Builder
capitalizeNext := true
for _, r := range s {
if r == '_' || r == '/' || r == '-' {
capitalizeNext = true
} else if capitalizeNext {
sb.WriteRune(unicode.ToUpper(r))
capitalizeNext = false
} else {
sb.WriteRune(unicode.ToLower(r))
}
}
return sb.String()
}
func TomlFileToMap(tomlfile string) map[string]any {
f, err := os.Open(tomlfile)
if err != nil {
panic(err)
}
var m map[string]any
err = toml.NewDecoder(f).Decode(&m)
if err != nil {
panic(err)
}
return m
}