summaryrefslogtreecommitdiffstats
path: root/pkg/i18n/i18n.go
blob: 00e015c3df918e6275654798640637b9bb0499e6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package i18n

import (
	"strings"

	"github.com/cloudfoundry/jibber_jabber"
	"github.com/go-errors/errors"
	"github.com/imdario/mergo"
	"github.com/sirupsen/logrus"
)

// Localizer will translate a message into the user's language
type Localizer struct {
	Log *logrus.Entry
	S   TranslationSet
}

func NewTranslationSetFromConfig(log *logrus.Entry, configLanguage string) (*TranslationSet, error) {
	if configLanguage == "auto" {
		language := detectLanguage(jibber_jabber.DetectLanguage)
		return NewTranslationSet(log, language), nil
	}

	for key := range GetTranslationSets() {
		if key == configLanguage {
			return NewTranslationSet(log, configLanguage), nil
		}
	}

	return NewTranslationSet(log, "en"), errors.New("Language not found: " + configLanguage)
}

func NewTranslationSet(log *logrus.Entry, language string) *TranslationSet {
	log.Info("language: " + language)

	baseSet := EnglishTranslationSet()

	for languageCode, translationSet := range GetTranslationSets() {
		if strings.HasPrefix(language, languageCode) {
			_ = mergo.Merge(&baseSet, translationSet, mergo.WithOverride)
		}
	}
	return &baseSet
}

// 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(),
		"zh": chineseTranslationSet(),
		"ja": japaneseTranslationSet(),
	}
}

// detectLanguage extracts user language from environment
func detectLanguage(langDetector func() (string, error)) string {
	if userLang, err := langDetector(); err == nil {
		return userLang
	}

	return "C"
}