Neur0toxine
2cd46585a8
All checks were successful
continuous-integration/drone/push Build is passing
67 lines
1.3 KiB
Go
67 lines
1.3 KiB
Go
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 {
|
|
localizers[tag.String()] = &localizer{loc: i18n.NewLocalizer(bundle, tag.String()), tag: tag}
|
|
}
|
|
}
|
|
|
|
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]
|
|
}
|