Archived
1
0
This repository has been archived on 2023-08-12. You can view files and clone it, but cannot push or open issues or pull requests.
nntpchan/contrib/backends/srndv2/src/srnd/i18n.go

98 lines
2.2 KiB
Go
Raw Normal View History

package srnd
import (
"github.com/majestrate/configparser"
"golang.org/x/text/language"
"io/ioutil"
"log"
"path/filepath"
"strings"
)
2017-10-10 21:17:38 +05:00
type I18N struct {
locale language.Tag
// loaded translations
2017-10-10 21:17:38 +05:00
Translations map[string]string
// loaded formats
2017-10-10 21:17:38 +05:00
Formats map[string]string
// root directory for translations
translation_dir string
2017-10-10 21:17:38 +05:00
// name of locale
name string
}
2017-10-10 21:17:38 +05:00
var I18nProvider *I18N = nil
//Read all .ini files in dir, where the filenames are BCP 47 tags
//Use the language matcher to get the best match for the locale preference
func InitI18n(locale, dir string) {
2017-10-10 21:17:38 +05:00
var err error
I18nProvider, err = NewI18n(locale, dir)
if err != nil {
log.Fatal(err)
}
}
func NewI18n(locale, dir string) (*I18N, error) {
log.Println("get locale", locale)
pref := language.Make(locale) // falls back to en-US on parse error
files, err := ioutil.ReadDir(dir)
if err != nil {
2017-10-10 21:17:38 +05:00
return nil, err
}
serverLangs := make([]language.Tag, 1)
serverLangs[0] = language.AmericanEnglish // en-US fallback
for _, file := range files {
if filepath.Ext(file.Name()) == ".ini" {
name := strings.TrimSuffix(file.Name(), ".ini")
tag, err := language.Parse(name)
if err == nil {
serverLangs = append(serverLangs, tag)
}
}
}
matcher := language.NewMatcher(serverLangs)
tag, _, _ := matcher.Match(pref)
fname := filepath.Join(dir, tag.String()+".ini")
conf, err := configparser.Read(fname)
if err != nil {
2017-10-10 21:17:38 +05:00
return nil, err
}
formats, err := conf.Section("formats")
if err != nil {
2017-10-10 21:17:38 +05:00
return nil, err
}
translations, err := conf.Section("strings")
if err != nil {
2017-10-10 21:17:38 +05:00
return nil, err
}
2017-10-10 21:17:38 +05:00
return &I18N{
name: locale,
translation_dir: dir,
2017-10-10 21:17:38 +05:00
Formats: formats.Options(),
Translations: translations.Options(),
locale: tag,
2017-10-10 21:17:38 +05:00
}, nil
}
2017-10-10 21:17:38 +05:00
func (self *I18N) Translate(key string) string {
return self.Translations[key]
}
2017-10-10 21:17:38 +05:00
func (self *I18N) Format(key string) string {
return self.Formats[key]
}
//this signature seems to be expected by mustache
2017-10-10 21:17:38 +05:00
//func (self *I18N) Translations() (map[string]string, error) {
// return self._translations, nil
//}
2017-10-10 21:17:38 +05:00
//func (self *I18N) Formats() (map[string]string, error) {
// return self.formats, nil
//}