1package i18n 2 3import ( 4 "strings" 5 6 "github.com/cloudfoundry/jibber_jabber" 7 "github.com/go-errors/errors" 8 "github.com/imdario/mergo" 9 "github.com/sirupsen/logrus" 10) 11 12// Localizer will translate a message into the user's language 13type Localizer struct { 14 Log *logrus.Entry 15 S TranslationSet 16} 17 18func NewTranslationSetFromConfig(log *logrus.Entry, configLanguage string) (*TranslationSet, error) { 19 if configLanguage == "auto" { 20 language := detectLanguage(jibber_jabber.DetectLanguage) 21 return NewTranslationSet(log, language), nil 22 } 23 24 for key := range GetTranslationSets() { 25 if key == configLanguage { 26 return NewTranslationSet(log, configLanguage), nil 27 } 28 } 29 30 return NewTranslationSet(log, "en"), errors.New("Language not found: " + configLanguage) 31} 32 33func NewTranslationSet(log *logrus.Entry, language string) *TranslationSet { 34 log.Info("language: " + language) 35 36 baseSet := englishTranslationSet() 37 38 for languageCode, translationSet := range GetTranslationSets() { 39 if strings.HasPrefix(language, languageCode) { 40 _ = mergo.Merge(&baseSet, translationSet, mergo.WithOverride) 41 } 42 } 43 return &baseSet 44} 45 46// GetTranslationSets gets all the translation sets, keyed by language code 47func GetTranslationSets() map[string]TranslationSet { 48 return map[string]TranslationSet{ 49 "pl": polishTranslationSet(), 50 "nl": dutchTranslationSet(), 51 "en": englishTranslationSet(), 52 "zh": chineseTranslationSet(), 53 } 54} 55 56// detectLanguage extracts user language from environment 57func detectLanguage(langDetector func() (string, error)) string { 58 if userLang, err := langDetector(); err == nil { 59 return userLang 60 } 61 62 return "C" 63} 64