Debian Codegraph @

langs/i18n/i18n.go

raw
1 // Copyright 2017 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package i18n
15
16 import (
17 "context"
18 "fmt"
19 "reflect"
20 "strings"
21
22 "github.com/spf13/cast"
23
24 "github.com/gohugoio/hugo/common/hreflect"
25 "github.com/gohugoio/hugo/common/loggers"
26 "github.com/gohugoio/hugo/config"
27 "github.com/gohugoio/hugo/resources/page"
28
29 "github.com/gohugoio/go-i18n/v2/i18n"
30 )
31
32 type translateFunc func(ctx context.Context, translationID string, templateData any) string
33
34 // Translator handles i18n translations.
35 type Translator struct {
36 translateFuncs map[string]translateFunc
37 cfg config.AllProvider
38 logger loggers.Logger
39 }
40
41 // NewTranslator creates a new Translator for the given language bundle and configuration.
42 func NewTranslator(b *i18n.Bundle, cfg config.AllProvider, logger loggers.Logger) Translator {
43 t := Translator{cfg: cfg, logger: logger, translateFuncs: make(map[string]translateFunc)}
44 t.initFuncs(b)
45 return t
46 }
47
48 // Lookup looks up the translate func for the given language.
49 func (t Translator) Lookup(lang string) (translateFunc, bool) {
50 f, ok := t.translateFuncs[lang]
51 return f, ok
52 }
53
54 // Func gets the translate func for the given language, or for the default
55 // configured language if not found.
56 func (t Translator) Func(lang string) translateFunc {
57 if f, ok := t.translateFuncs[lang]; ok {
58 return f
59 }
60 t.logger.Infof("Translation func for language %v not found, use default.", lang)
61 if f, ok := t.translateFuncs[t.cfg.DefaultContentLanguage()]; ok {
62 return f
63 }
64
65 t.logger.Infoln("i18n not initialized; if you need string translations, check that you have a bundle in /i18n that matches the site language or the default language.")
66 return func(ctx context.Context, translationID string, args any) string {
67 return ""
68 }
69 }
70
71 func (t Translator) initFuncs(bndl *i18n.Bundle) {
72 enableMissingTranslationPlaceholders := t.cfg.EnableMissingTranslationPlaceholders()
73 for _, lang := range bndl.LanguageTags() {
74 currentLang := lang
75 currentLangStr := currentLang.String()
76 // This may be pt-BR; make it case insensitive.
77 currentLangKey := strings.ToLower(strings.TrimPrefix(currentLangStr, artificialLangTagPrefix))
78 localizer := i18n.NewLocalizer(bndl, currentLangStr)
79 t.translateFuncs[currentLangKey] = func(ctx context.Context, translationID string, templateData any) string {
80 pluralCount := getPluralCount(templateData)
81
82 if templateData != nil {
83 tp := reflect.TypeOf(templateData)
84 if hreflect.IsInt(tp.Kind()) {
85 // This was how go-i18n worked in v1,
86 // and we keep it like this to avoid breaking
87 // lots of sites in the wild.
88 templateData = intCount(cast.ToInt(templateData))
89 } else {
90 if p, ok := templateData.(page.Page); ok {
91 // See issue 10782.
92 // The i18n has its own template handling and does not know about
93 // the context.Context.
94 // A common pattern is to pass Page to i18n, and use .ReadingTime etc.
95 // We need to improve this, but that requires some upstream changes.
96 // For now, just create a wrapper.
97 templateData = page.PageWithContext{Page: p, Ctx: ctx}
98 }
99 }
100 }
101
102 translated, translatedLang, err := localizer.LocalizeWithTag(&i18n.LocalizeConfig{
103 MessageID: translationID,
104 TemplateData: templateData,
105 PluralCount: pluralCount,
106 })
107
108 sameLang := currentLang == translatedLang
109
110 if err == nil && sameLang {
111 return translated
112 }
113
114 if err != nil && sameLang && translated != "" {
115 // See #8492
116 // TODO(bep) this needs to be improved/fixed upstream,
117 // but currently we get an error even if the fallback to
118 // "other" succeeds.
119 if fmt.Sprintf("%T", err) == "i18n.pluralFormNotFoundError" {
120 return translated
121 }
122 }
123
124 if _, ok := err.(*i18n.MessageNotFoundErr); !ok {
125 t.logger.Warnf("Failed to get translated string for language %q and ID %q: %s", currentLangStr, translationID, err)
126 }
127
128 if t.cfg.PrintI18nWarnings() {
129 t.logger.Warnf("i18n|MISSING_TRANSLATION|%s|%s", currentLangStr, translationID)
130 }
131
132 if enableMissingTranslationPlaceholders {
133 return "[i18n] " + translationID
134 }
135
136 return translated
137 }
138 }
139 }
140
141 // intCount wraps the Count method.
142 type intCount int
143
144 func (c intCount) Count() int {
145 return int(c)
146 }
147
148 const countFieldName = "Count"
149
150 // getPluralCount gets the plural count as a string (floats) or an integer.
151 // If v is nil, nil is returned.
152 func getPluralCount(v any) any {
153 if v == nil {
154 // i18n called without any argument, make sure it does not
155 // get any plural count.
156 return nil
157 }
158
159 switch v := v.(type) {
160 case map[string]any:
161 for k, vv := range v {
162 if strings.EqualFold(k, countFieldName) {
163 return toPluralCountValue(vv)
164 }
165 }
166 default:
167 vv, isNil := hreflect.IndirectElem(reflect.ValueOf(v))
168 if isNil {
169 return nil
170 }
171 tp := vv.Type()
172 if tp.Kind() == reflect.Struct {
173 f := vv.FieldByName(countFieldName)
174 if f.IsValid() {
175 return toPluralCountValue(f.Interface())
176 }
177 m := hreflect.GetMethodByName(vv, countFieldName)
178 if m.IsValid() && m.Type().NumIn() == 0 && m.Type().NumOut() == 1 {
179 c := m.Call(nil)
180 return toPluralCountValue(c[0].Interface())
181 }
182 }
183 }
184
185 return toPluralCountValue(v)
186 }
187
188 // go-i18n expects floats to be represented by string.
189 func toPluralCountValue(in any) any {
190 k := reflect.TypeOf(in).Kind()
191 switch {
192 case hreflect.IsFloat(k):
193 f := cast.ToString(in)
194 if !strings.Contains(f, ".") {
195 f += ".0"
196 }
197 return f
198 case k == reflect.String:
199 if _, err := cast.ToFloat64E(in); err == nil {
200 return in
201 }
202 // A non-numeric value.
203 return nil
204 default:
205 if i, err := cast.ToIntE(in); err == nil {
206 return i
207 }
208 return nil
209 }
210 }