From 901756afe5cb8a8a60ddadefc92c4c0051978df0 Mon Sep 17 00:00:00 2001 From: Giorgi Bochorishvili Date: Fri, 13 Jan 2023 13:22:01 +0400 Subject: [PATCH] Add translations support for products --- shared/i18n/i18n.go | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/shared/i18n/i18n.go b/shared/i18n/i18n.go index 5bf0f13bfe..d3c1853c32 100644 --- a/shared/i18n/i18n.go +++ b/shared/i18n/i18n.go @@ -13,6 +13,7 @@ import ( "strings" "github.com/mattermost/go-i18n/i18n" + "github.com/mattermost/go-i18n/i18n/bundle" "github.com/mattermost/mattermost-server/v6/shared/mlog" ) @@ -22,6 +23,9 @@ const defaultLocale = "en" // TranslateFunc is the type of the translate functions type TranslateFunc func(translationID string, args ...any) string +// TranslationFuncByLocal is the type of function that takes local as a string and returns the translation function +type TranslationFuncByLocal func(locale string) TranslateFunc + // T is the translate function using the default server language as fallback language var T TranslateFunc @@ -74,6 +78,40 @@ func initTranslationsWithDir(dir string) error { return nil } +// GetTranslationFuncForDir loads translations from the filesystem into a new instance of the bundle. +// It returns a function to access loaded translations. +func GetTranslationFuncForDir(dir string) (TranslationFuncByLocal, error) { + var locales map[string]string = make(map[string]string) + bundle := bundle.New() + files, _ := os.ReadDir(dir) + for _, f := range files { + if filepath.Ext(f.Name()) == ".json" { + filename := f.Name() + locales[strings.Split(filename, ".")[0]] = filepath.Join(dir, filename) + + if err := bundle.LoadTranslationFile(filepath.Join(dir, filename)); err != nil { + return nil, err + } + } + } + + return func(locale string) TranslateFunc { + if _, ok := locales[locale]; !ok { + locale = defaultLocale + } + + t, _ := bundle.Tfunc(locale) + return func(translationID string, args ...any) string { + if translated := t(translationID, args...); translated != translationID { + return translated + } + + t, _ := bundle.Tfunc(defaultLocale) + return t(translationID, args...) + } + }, nil +} + func getTranslationsBySystemLocale() (TranslateFunc, error) { locale := defaultServerLocale if _, ok := locales[locale]; !ok {