-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlokyn.go
More file actions
280 lines (223 loc) · 7.03 KB
/
Copy pathlokyn.go
File metadata and controls
280 lines (223 loc) · 7.03 KB
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
// Package lokyn is a small and lightweight library to help using lower level libs like jeandeaual/go-locale and nicksnyder/go-i18n.
// It's heavily inspired by the Fyne lang package, but in a standalone philosophy. The real deal comes when Lokyn app is used to help
// translating the application.
package lokyn
import (
"context"
"embed"
"encoding/json"
"log"
"sync"
"github.com/jeandeaual/go-locale"
"github.com/nicksnyder/go-i18n/v2/i18n"
"golang.org/x/text/language"
)
var (
bundle *i18n.Bundle
localizer *i18n.Localizer
once sync.Once
currentLang language.Tag
translated []language.Tag
// mu guards the process-wide localizer and currentLang. SetLanguage writes
// them while L reads them, which is a data race in any concurrent program.
mu sync.RWMutex
// localizers caches one Localizer per language. i18n.Localizer and its
// Bundle are read-only once translations are loaded, so a single instance
// per language is safe to share and there is no reason to build more.
localizers sync.Map
)
// Init inits the package, only once.
func Init() {
once.Do(initBundle)
}
// AddTranslationFS registers all the managed languages to lokyn.
func AddTranslationFS(fs embed.FS, dir string) error {
files, err := fs.ReadDir(dir)
if err != nil {
return err
}
for _, f := range files {
name := f.Name()
data, err := fs.ReadFile(dir + "/" + name)
if err != nil {
continue
}
err = addLanguage(data, name)
if err != nil {
return err
}
}
initLanguage()
return nil
}
// GetCurrentLanguage returns the current language as string.
func GetCurrentLanguage() string {
mu.RLock()
defer mu.RUnlock()
return currentLang.String()
}
// SetLanguage helps defining the current language.
//
// This sets it for the whole process. A server handling several languages at
// once wants NewLocalizer and WithContext instead: concurrent requests calling
// SetLanguage overwrite each other, and a request can render in the language
// another request just selected.
func SetLanguage(lang string) {
setupLang(lang)
}
// L returns translation of the given key, in the process-wide language.
func L(key string) string {
return getKey(key, key)
}
// P returns translation with plural management, in the process-wide language.
func P(key string, count int) string {
return getPluralKey(key, key, count)
}
// Localizer translates into one language. It carries no mutable state, so a
// single instance is safe to use from any number of goroutines at once.
type Localizer struct {
tag language.Tag
l *i18n.Localizer
}
// NewLocalizer returns the Localizer for lang, building it on first use. The
// result is cached, so callers may treat this as free and call it per request.
func NewLocalizer(lang string) *Localizer {
Init()
if cached, ok := localizers.Load(lang); ok {
return cached.(*Localizer)
}
created := &Localizer{
tag: language.Make(lang),
l: i18n.NewLocalizer(bundle, lang),
}
actual, _ := localizers.LoadOrStore(lang, created)
return actual.(*Localizer)
}
// Language returns the language this Localizer translates into.
func (lz *Localizer) Language() string {
if lz == nil {
return GetCurrentLanguage()
}
return lz.tag.String()
}
// L returns translation of the given key. A nil Localizer falls back to the
// process-wide language, so a caller that has not been given one still works.
func (lz *Localizer) L(key string) string {
if lz == nil {
return L(key)
}
return localize(lz.l, key, key, nil)
}
// P returns translation with plural management.
func (lz *Localizer) P(key string, count int) string {
if lz == nil {
return P(key, count)
}
return localize(lz.l, key, key, &count)
}
type contextKey struct{}
// WithContext returns a copy of ctx carrying lz, so that handlers and templates
// downstream translate into that language without touching global state.
func WithContext(ctx context.Context, lz *Localizer) context.Context {
return context.WithValue(ctx, contextKey{}, lz)
}
// FromContext returns the Localizer carried by ctx, or nil when there is none.
// The returned value is safe to call methods on either way.
func FromContext(ctx context.Context) *Localizer {
if ctx == nil {
return nil
}
lz, _ := ctx.Value(contextKey{}).(*Localizer)
return lz
}
// LCtx returns translation of the given key in ctx's language, falling back to
// the process-wide one when ctx carries no Localizer. That fallback is what
// lets a codebase migrate to it a file at a time.
func LCtx(ctx context.Context, key string) string {
return FromContext(ctx).L(key)
}
// PCtx returns translation with plural management, in ctx's language.
func PCtx(ctx context.Context, key string, count int) string {
return FromContext(ctx).P(key, count)
}
// initBundle initialize lokyn with english language.
func initBundle() {
bundle = i18n.NewBundle(language.English)
bundle.RegisterUnmarshalFunc("json", json.Unmarshal)
translated = []language.Tag{language.Make("en")}
}
// initLanguage init the language based on the system language.
func initLanguage() {
all, err := locale.GetLocales()
if err != nil {
all = []string{"en"}
}
setupLang(closestSupportedLocale(all).String())
}
// setupLang initialize a new localizer for the requested language.
func setupLang(lang string) {
lz := NewLocalizer(lang)
mu.Lock()
defer mu.Unlock()
currentLang = lz.tag
localizer = lz.l
}
// currentLocalizer reads the process-wide localizer under the lock, so a
// concurrent SetLanguage cannot be observed half-applied.
func currentLocalizer() *i18n.Localizer {
mu.RLock()
defer mu.RUnlock()
return localizer
}
// addLanguage adds a language to lokyn managed languages.
func addLanguage(data []byte, name string) error {
f, err := bundle.ParseMessageFileBytes(data, name)
if err != nil {
return err
}
translated = append(translated, f.Tag)
return nil
}
// getKey gets the requested key, manage a fallback key.
func getKey(key, fallback string) string {
return localize(currentLocalizer(), key, fallback, nil)
}
// getPluralKey gets the requested key, manage a fallback and plural.
func getPluralKey(key, fallback string, count int) string {
return localize(currentLocalizer(), key, fallback, &count)
}
// localize is the single lookup every entry point shares. count is nil for a
// non-plural lookup, which is not the same as a count of zero.
func localize(l *i18n.Localizer, key, fallback string, count *int) string {
if l == nil {
return fallback
}
config := &i18n.LocalizeConfig{
DefaultMessage: &i18n.Message{
ID: key,
Other: fallback,
},
}
if count != nil {
config.PluralCount = *count
}
ret, err := l.Localize(config)
if err != nil {
log.Println("Error in translation")
}
return ret
}
// closestSupportedLocale helps to determine the closest language tag based on the locales given in parameter.
func closestSupportedLocale(locs []string) language.Tag {
matcher := language.NewMatcher(translated)
tags := make([]language.Tag, len(locs))
for i, loc := range locs {
tag, err := language.Parse(loc)
if err != nil {
log.Println("Error in parsing tags")
}
tags[i] = tag
}
best, _, _ := matcher.Match(tags...)
return best
}