Debian Codegraph @

langs/i18n/translationProvider.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 "encoding/json"
19 "fmt"
20 "sort"
21 "strings"
22
23 "github.com/gohugoio/hugo/common/paths"
24 "github.com/gohugoio/hugo/config"
25 "github.com/gohugoio/hugo/langs"
26 "github.com/gohugoio/hugo/parser/metadecoders"
27
28 "github.com/gohugoio/hugo/common/herrors"
29 "golang.org/x/text/language"
30
31 "github.com/gohugoio/go-i18n/v2/i18n"
32 "github.com/gohugoio/hugo/helpers"
33 toml "github.com/pelletier/go-toml/v2"
34
35 "github.com/gohugoio/hugo/deps"
36 "github.com/gohugoio/hugo/hugofs"
37 "github.com/gohugoio/hugo/source"
38 )
39
40 // TranslationProvider provides translation handling, i.e. loading
41 // of bundles etc.
42 type TranslationProvider struct {
43 t Translator
44 }
45
46 // NewTranslationProvider creates a new translation provider.
47 func NewTranslationProvider() *TranslationProvider {
48 return &TranslationProvider{}
49 }
50
51 // Update updates the i18n func in the provided Deps.
52 func (tp *TranslationProvider) NewResource(dst *deps.Deps) error {
53 defaultLangTag, err := language.Parse(dst.Conf.DefaultContentLanguage())
54 if err != nil {
55 defaultLangTag = language.English
56 }
57 bundle := i18n.NewBundle(defaultLangTag)
58
59 bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)
60 bundle.RegisterUnmarshalFunc("yaml", metadecoders.UnmarshalYaml)
61 bundle.RegisterUnmarshalFunc("yml", metadecoders.UnmarshalYaml)
62 bundle.RegisterUnmarshalFunc("json", json.Unmarshal)
63
64 var files []hugofs.FileMetaInfo
65 w := hugofs.NewWalkway(
66 hugofs.WalkwayConfig{
67 Fs: dst.BaseFs.I18n.Fs,
68 IgnoreFile: dst.SourceSpec.IgnoreFile,
69 PathParser: dst.SourceSpec.Cfg.PathParser(),
70 WalkFn: func(ctx context.Context, path string, info hugofs.FileMetaInfo) error {
71 if info.IsDir() {
72 return nil
73 }
74 files = append(files, info)
75 return nil
76 },
77 })
78
79 if err := w.Walk(); err != nil {
80 return err
81 }
82
83 // Sort translation files so that base tags (e.g. "de") are always registered
84 // before their subtag variants (e.g. "de-DE"); without this ordering the
85 // fallback chain breaks. See https://github.com/gohugoio/hugo/issues/7982.
86 sort.Slice(files, func(i, j int) bool {
87 si := files[i].Meta().PathInfo.NameNoExt()
88 sj := files[j].Meta().PathInfo.NameNoExt()
89 return strings.Count(si, "-") < strings.Count(sj, "-")
90 })
91
92 for _, info := range files {
93 if err := addTranslationFile(bundle, source.NewFileInfo(info)); err != nil {
94 return err
95 }
96 }
97
98 tp.t = NewTranslator(bundle, dst.Conf, dst.Log)
99
100 dst.Translate = tp.getTranslateFunc(dst)
101
102 return nil
103 }
104
105 const artificialLangTagPrefix = "art-x-"
106
107 func addTranslationFile(bundle *i18n.Bundle, r *source.File) error {
108 f, err := r.FileInfo().Meta().Open()
109 if err != nil {
110 return fmt.Errorf("failed to open translations file %q:: %w", r.LogicalName(), err)
111 }
112
113 b := helpers.ReaderToBytes(f)
114 f.Close()
115
116 name := r.LogicalName()
117 lang := paths.Filename(name)
118 tag := language.Make(lang)
119 if tag == language.Und {
120 try := artificialLangTagPrefix + lang
121 _, err = language.Parse(try)
122 if err != nil {
123 return fmt.Errorf("%q: %s", try, err)
124 }
125 name = artificialLangTagPrefix + name
126 }
127
128 _, err = bundle.ParseMessageFileBytes(b, name)
129 if err != nil {
130 if strings.Contains(err.Error(), "no plural rule") {
131 // https://github.com/gohugoio/hugo/issues/7798
132 name = artificialLangTagPrefix + name
133 _, err = bundle.ParseMessageFileBytes(b, name)
134 if err == nil {
135 return nil
136 }
137 }
138 var guidance string
139 if strings.Contains(err.Error(), "mixed with unreserved keys") {
140 guidance = ": see the lang.Translate documentation for a list of reserved keys"
141 }
142 return errWithFileContext(fmt.Errorf("failed to load translations: %w%s", err, guidance), r)
143 }
144
145 return nil
146 }
147
148 // CloneResource sets the language func for the new language.
149 func (tp *TranslationProvider) CloneResource(dst, src *deps.Deps) error {
150 dst.Translate = tp.getTranslateFunc(dst)
151 return nil
152 }
153
154 func defaultLanguage(conf config.AllProvider) *langs.Language {
155 key := conf.DefaultContentLanguage()
156 for _, l := range conf.Languages().(langs.Languages) {
157 if l.Lang == key {
158 return l
159 }
160 }
161 return conf.Language().(*langs.Language)
162 }
163
164 // getTranslateFunc returns the translation function for the language in Deps.
165 // The lookup order is: current locale, current key, default locale, default key.
166 func (tp *TranslationProvider) getTranslateFunc(dst *deps.Deps) func(ctx context.Context, translationID string, templateData any) string {
167 current := dst.Conf.Language().(*langs.Language)
168 defaultLang := defaultLanguage(dst.Conf)
169 for _, l := range []*langs.Language{current, defaultLang} {
170 for _, key := range []string{strings.ToLower(l.Locale()), l.Lang} {
171 if fn, ok := tp.t.Lookup(key); ok {
172 return fn
173 }
174 }
175 }
176 return tp.t.Func("en")
177 }
178
179 func errWithFileContext(inerr error, r *source.File) error {
180 meta := r.FileInfo().Meta()
181 realFilename := meta.Filename
182 f, err := meta.Open()
183 if err != nil {
184 return inerr
185 }
186 defer f.Close()
187
188 return herrors.NewFileErrorFromName(inerr, realFilename).UpdateContent(f, nil)
189 }