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 toml "github.com/pelletier/go-toml/v2"
33
34 "github.com/gohugoio/hugo/deps"
35 "github.com/gohugoio/hugo/hugofs"
36 "github.com/gohugoio/hugo/source"
37 )
38
39 // TranslationProvider provides translation handling, i.e. loading
40 // of bundles etc.
41 type TranslationProvider struct {
42 t Translator
43 }
44
45 // NewTranslationProvider creates a new translation provider.
46 func NewTranslationProvider() *TranslationProvider {
47 return &TranslationProvider{}
48 }
49
50 // Update updates the i18n func in the provided Deps.
51 func (tp *TranslationProvider) NewResource(dst *deps.Deps) error {
52 defaultLangTag, err := language.Parse(dst.Conf.DefaultContentLanguage())
53 if err != nil {
54 defaultLangTag = language.English
55 }
56 bundle := i18n.NewBundle(defaultLangTag)
57
58 bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)
59 bundle.RegisterUnmarshalFunc("yaml", metadecoders.UnmarshalYaml)
60 bundle.RegisterUnmarshalFunc("yml", metadecoders.UnmarshalYaml)
61 bundle.RegisterUnmarshalFunc("json", json.Unmarshal)
62
63 var files []hugofs.FileMetaInfo
64 w := hugofs.NewWalkway(
65 hugofs.WalkwayConfig{
66 Fs: dst.BaseFs.I18n.Fs,
67 IgnoreFile: dst.SourceSpec.IgnoreFile,
68 PathParser: dst.SourceSpec.Cfg.PathParser(),
69 WalkFn: func(ctx context.Context, path string, info hugofs.FileMetaInfo) error {
70 if info.IsDir() {
71 return nil
72 }
73 files = append(files, info)
74 return nil
75 },
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 b, err := r.FileInfo().Meta().ReadAll()
109 if err != nil {
110 return fmt.Errorf("failed to read translations file %q:: %w", r.LogicalName(), err)
111 }
112
113 name := r.LogicalName()
114 lang := paths.Filename(name)
115 tag := language.Make(lang)
116 if tag == language.Und {
117 try := artificialLangTagPrefix + lang
118 _, err = language.Parse(try)
119 if err != nil {
120 return fmt.Errorf("%q: %s", try, err)
121 }
122 name = artificialLangTagPrefix + name
123 }
124
125 _, err = bundle.ParseMessageFileBytes(b, name)
126 if err != nil {
127 if strings.Contains(err.Error(), "no plural rule") {
128 // https://github.com/gohugoio/hugo/issues/7798
129 name = artificialLangTagPrefix + name
130 _, err = bundle.ParseMessageFileBytes(b, name)
131 if err == nil {
132 return nil
133 }
134 }
135 var guidance string
136 if strings.Contains(err.Error(), "mixed with unreserved keys") {
137 guidance = ": see the lang.Translate documentation for a list of reserved keys"
138 }
139 return errWithFileContext(fmt.Errorf("failed to load translations: %w%s", err, guidance), r)
140 }
141
142 return nil
143 }
144
145 // CloneResource sets the language func for the new language.
146 func (tp *TranslationProvider) CloneResource(dst, src *deps.Deps) error {
147 dst.Translate = tp.getTranslateFunc(dst)
148 return nil
149 }
150
151 func defaultLanguage(conf config.AllProvider) *langs.Language {
152 key := conf.DefaultContentLanguage()
153 for _, l := range conf.Languages().(langs.Languages) {
154 if l.Lang == key {
155 return l
156 }
157 }
158 return conf.Language().(*langs.Language)
159 }
160
161 // getTranslateFunc returns the translation function for the language in Deps.
162 // The lookup order is: current locale, current key, default locale, default key.
163 func (tp *TranslationProvider) getTranslateFunc(dst *deps.Deps) func(ctx context.Context, translationID string, templateData any) string {
164 current := dst.Conf.Language().(*langs.Language)
165 defaultLang := defaultLanguage(dst.Conf)
166 for _, l := range []*langs.Language{current, defaultLang} {
167 for _, key := range []string{strings.ToLower(l.Locale()), l.Lang} {
168 if fn, ok := tp.t.Lookup(key); ok {
169 return fn
170 }
171 }
172 }
173 return tp.t.Func("en")
174 }
175
176 func errWithFileContext(inerr error, r *source.File) error {
177 meta := r.FileInfo().Meta()
178 realFilename := meta.Filename
179 f, err := meta.Open()
180 if err != nil {
181 return inerr
182 }
183 defer f.Close()
184
185 return herrors.NewFileErrorFromName(inerr, realFilename).UpdateContent(f, nil)
186 }