2018-08-14 14:12:07 +02:00
|
|
|
package i18n
|
2018-08-13 15:33:45 +02:00
|
|
|
|
|
|
|
import (
|
2020-10-04 02:00:48 +02:00
|
|
|
"strings"
|
2020-09-30 13:12:03 +02:00
|
|
|
|
2018-08-14 12:52:26 +02:00
|
|
|
"github.com/cloudfoundry/jibber_jabber"
|
2020-10-04 02:00:48 +02:00
|
|
|
"github.com/imdario/mergo"
|
2018-08-26 07:46:18 +02:00
|
|
|
"github.com/sirupsen/logrus"
|
2018-08-13 15:33:45 +02:00
|
|
|
)
|
|
|
|
|
2018-08-14 14:12:07 +02:00
|
|
|
// Localizer will translate a message into the user's language
|
|
|
|
type Localizer struct {
|
2020-10-04 02:00:48 +02:00
|
|
|
Log *logrus.Entry
|
|
|
|
S TranslationSet
|
2018-08-14 14:12:07 +02:00
|
|
|
}
|
|
|
|
|
2020-10-04 02:00:48 +02:00
|
|
|
// NewTranslationSet creates a new Localizer
|
|
|
|
func NewTranslationSet(log *logrus.Entry) *TranslationSet {
|
2018-08-20 21:04:04 +02:00
|
|
|
userLang := detectLanguage(jibber_jabber.DetectLanguage)
|
2018-08-13 15:33:45 +02:00
|
|
|
|
2018-08-14 14:12:07 +02:00
|
|
|
log.Info("language: " + userLang)
|
2018-08-14 12:56:11 +02:00
|
|
|
|
2020-10-04 02:00:48 +02:00
|
|
|
baseSet := englishTranslationSet()
|
2018-08-14 14:12:07 +02:00
|
|
|
|
2020-10-04 02:00:48 +02:00
|
|
|
for languageCode, translationSet := range GetTranslationSets() {
|
|
|
|
if strings.HasPrefix(userLang, languageCode) {
|
|
|
|
_ = mergo.Merge(&baseSet, translationSet, mergo.WithOverride)
|
|
|
|
}
|
2018-08-17 17:22:30 +02:00
|
|
|
}
|
|
|
|
|
2020-10-04 02:00:48 +02:00
|
|
|
return &baseSet
|
|
|
|
}
|
2018-08-20 21:18:15 +02:00
|
|
|
|
2020-10-04 02:00:48 +02:00
|
|
|
// GetTranslationSets gets all the translation sets, keyed by language code
|
|
|
|
func GetTranslationSets() map[string]TranslationSet {
|
|
|
|
return map[string]TranslationSet{
|
|
|
|
"pl": polishTranslationSet(),
|
|
|
|
"nl": dutchTranslationSet(),
|
|
|
|
"en": englishTranslationSet(),
|
2018-08-20 21:18:15 +02:00
|
|
|
}
|
2018-08-14 14:12:07 +02:00
|
|
|
}
|
2018-08-20 21:04:04 +02:00
|
|
|
|
|
|
|
// detectLanguage extracts user language from environment
|
|
|
|
func detectLanguage(langDetector func() (string, error)) string {
|
|
|
|
if userLang, err := langDetector(); err == nil {
|
|
|
|
return userLang
|
|
|
|
}
|
|
|
|
|
|
|
|
return "C"
|
|
|
|
}
|