2024-05-07 23:45:28 +03:00
|
|
|
package locale
|
|
|
|
|
|
|
|
import (
|
|
|
|
"embed"
|
|
|
|
"github.com/nicksnyder/go-i18n/v2/i18n"
|
|
|
|
"golang.org/x/text/language"
|
|
|
|
"gopkg.in/yaml.v3"
|
|
|
|
"os"
|
|
|
|
)
|
|
|
|
|
|
|
|
//go:embed *.yaml
|
|
|
|
var locales embed.FS
|
|
|
|
|
|
|
|
var localizers = map[string]Localizer{}
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
entries, err := locales.ReadDir(".")
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
tags := []language.Tag{}
|
|
|
|
bundle := i18n.NewBundle(language.English)
|
|
|
|
bundle.RegisterUnmarshalFunc("yaml", yaml.Unmarshal)
|
|
|
|
|
|
|
|
for _, entry := range entries {
|
|
|
|
_, err := bundle.LoadMessageFileFS(locales, entry.Name())
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
tags = append(tags, extractTagFromPath(entry.Name()))
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, tag := range tags {
|
2024-05-13 19:08:46 +03:00
|
|
|
localizers[tag.String()] = &localizer{loc: i18n.NewLocalizer(bundle, tag.String()), tag: tag}
|
2024-05-07 23:45:28 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func extractTagFromPath(path string) language.Tag {
|
|
|
|
var langTag string
|
|
|
|
formatStartIdx := -1
|
|
|
|
for i := len(path) - 1; i >= 0; i-- {
|
|
|
|
c := path[i]
|
|
|
|
if os.IsPathSeparator(c) {
|
|
|
|
if formatStartIdx != -1 {
|
|
|
|
langTag = path[i+1 : formatStartIdx]
|
|
|
|
}
|
|
|
|
return language.Make(langTag)
|
|
|
|
}
|
|
|
|
if path[i] == '.' {
|
|
|
|
if formatStartIdx != -1 {
|
|
|
|
langTag = path[i+1 : formatStartIdx]
|
|
|
|
return language.Make(langTag)
|
|
|
|
}
|
|
|
|
formatStartIdx = i
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if formatStartIdx != -1 {
|
|
|
|
return language.Make(path[:formatStartIdx])
|
|
|
|
}
|
|
|
|
return language.English
|
|
|
|
}
|
|
|
|
|
|
|
|
func For(lang string) Localizer {
|
|
|
|
return localizers[lang]
|
|
|
|
}
|