-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
loader.go
244 lines (205 loc) · 6.5 KB
/
loader.go
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
package i18n
import (
"encoding/json"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
"github.com/kataras/i18n/internal"
"github.com/BurntSushi/toml"
"gopkg.in/ini.v1"
"gopkg.in/yaml.v3"
)
// LoaderConfig the configuration structure which contains
// some options about how the template loader should act.
//
// See `Glob` and `Assets` package-level functions.
type LoaderConfig = internal.Options
// Glob accepts a glob pattern (see: https://golang.org/pkg/path/filepath/#Glob)
// and loads the locale files based on any "options".
//
// The "globPattern" input parameter is a glob pattern which the default loader should
// search and load for locale files.
//
// See `New` and `LoaderConfig` too.
func Glob(globPattern string, options ...LoaderConfig) Loader {
assetNames, err := filepath.Glob(globPattern)
if err != nil {
panic(err)
}
return load(assetNames, os.ReadFile, options...)
}
// FS is a virtual or local locale file system Loader.
// It accepts embed.FS or fs.FS or http.FileSystem.
// The "pattern" is a classic glob pattern.
//
// See `Glob`, `Assets`, `New` and `LoaderConfig` too.
func FS(fileSystem fs.FS, pattern string, options ...LoaderConfig) (Loader, error) {
pattern = strings.TrimPrefix(pattern, "./")
assetNames, err := fs.Glob(fileSystem, pattern)
if err != nil {
return nil, err
}
assetFunc := func(name string) ([]byte, error) {
f, err := fileSystem.Open(name)
if err != nil {
return nil, err
}
return io.ReadAll(f)
}
return load(assetNames, assetFunc, options...), nil
}
// Assets accepts a function that returns a list of filenames (physical or virtual),
// another a function that should return the contents of a specific file
// and any Loader options. Go-bindata usage.
// It returns a valid `Loader` which loads and maps the locale files.
//
// See `Glob`, `Assets`, `New` and `LoaderConfig` too.
func Assets(assetNames func() []string, asset func(string) ([]byte, error), options ...LoaderConfig) Loader {
return load(assetNames(), asset, options...)
}
// LangMap key as language (e.g. "el-GR") and value as a map of key-value pairs (e.g. "hello": "Γειά").
type LangMap = map[string]Map
// KV is a loader which accepts a map of language(key) and the available key-value pairs.
// Example Code:
//
// m := LangMap{
// "en-US": Map{
// "hello": "Hello",
// },
// "el-GR": Map{
// "hello": "Γειά",
// },
// }
//
// loader := KV(m, i18n.DefaultLoaderConfig)
// I18n, err := New(loader)
// I18N.SetDefault("en-US")
func KV(langMap LangMap, opts ...LoaderConfig) Loader {
return func(m *Matcher) (Localizer, error) {
options := DefaultLoaderConfig
if len(opts) > 0 {
options = opts[0]
}
languageIndexes := make([]int, 0, len(langMap))
keyValuesMulti := make([]Map, 0, len(langMap))
for languageName, pairs := range langMap {
langIndex := parseLanguageName(m, languageName) // matches and adds the language tag to m.Languages.
languageIndexes = append(languageIndexes, langIndex)
keyValuesMulti = append(keyValuesMulti, pairs)
}
cat, err := internal.NewCatalog(m.Languages, options)
if err != nil {
return nil, err
}
for _, langIndex := range languageIndexes {
if langIndex == -1 {
// If loader has more languages than defined for use in New function,
// e.g. when New(KV(m), "en-US") contains el-GR and en-US but only "en-US" passed.
continue
}
kv := keyValuesMulti[langIndex]
err := cat.Store(langIndex, kv)
if err != nil {
return nil, err
}
}
if n := len(cat.Locales); n == 0 {
return nil, fmt.Errorf("locales not found in map")
} else if options.Strict && n < len(m.Languages) {
return nil, fmt.Errorf("locales expected to be %d but %d parsed", len(m.Languages), n)
}
return cat, nil
}
}
// DefaultLoaderConfig represents the default loader configuration.
var DefaultLoaderConfig = LoaderConfig{
Left: "{{",
Right: "}}",
Strict: false,
DefaultMessageFunc: nil,
PluralFormDecoder: internal.DefaultPluralFormDecoder,
Funcs: nil,
}
// load accepts a list of filenames (physical or virtual),
// a function that should return the contents of a specific file
// and any Loader options.
// It returns a valid `Loader` which loads and maps the locale files.
//
// See `FS`, Glob`, `Assets` and `LoaderConfig` too.
func load(assetNames []string, asset func(string) ([]byte, error), opts ...LoaderConfig) Loader {
return func(m *Matcher) (Localizer, error) {
languageFiles, err := m.ParseLanguageFiles(assetNames)
if err != nil {
return nil, err
}
options := DefaultLoaderConfig
if len(opts) > 0 {
options = opts[0]
}
if options.DefaultMessageFunc == nil {
options.DefaultMessageFunc = m.defaultMessageFunc
}
cat, err := internal.NewCatalog(m.Languages, options)
if err != nil {
return nil, err
}
for langIndex, langFiles := range languageFiles {
keyValues := make(map[string]interface{})
for _, fileName := range langFiles {
unmarshal := yaml.Unmarshal
if idx := strings.LastIndexByte(fileName, '.'); idx > 1 {
switch fileName[idx:] {
case ".toml", ".tml":
unmarshal = toml.Unmarshal
case ".json":
unmarshal = json.Unmarshal
case ".ini":
unmarshal = unmarshalINI
}
}
b, err := asset(fileName)
if err != nil {
return nil, err
}
if err = unmarshal(b, &keyValues); err != nil {
return nil, err
}
}
err = cat.Store(langIndex, keyValues)
if err != nil {
return nil, err
}
}
if n := len(cat.Locales); n == 0 {
return nil, fmt.Errorf("locales not found in %s", strings.Join(assetNames, ", "))
} else if options.Strict && n < len(m.Languages) {
return nil, fmt.Errorf("locales expected to be %d but %d parsed", len(m.Languages), n)
}
return cat, nil
}
}
func unmarshalINI(data []byte, v interface{}) error {
f, err := ini.Load(data)
if err != nil {
return err
}
m := *v.(*map[string]interface{})
// Includes the ini.DefaultSection which has the root keys too.
// We don't have to iterate to each section to find the subsection,
// the Sections() returns all sections, sub-sections are separated by dot '.'
// and we match the dot with a section on the translate function, so we just save the values as they are,
// so we don't have to do section lookup on every translate call.
for _, section := range f.Sections() {
keyPrefix := ""
if name := section.Name(); name != ini.DefaultSection {
keyPrefix = name + "."
}
for _, key := range section.Keys() {
m[keyPrefix+key.Name()] = key.Value()
}
}
return nil
}