-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathl10n.go
106 lines (86 loc) · 1.91 KB
/
l10n.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
package l10n
import (
"path/filepath"
"github.com/gobuffalo/envy"
"github.com/iafan/Plurr/go/plurr"
"github.com/pkg/errors"
"github.com/ungerik/go-dry"
"github.com/xelaj/v"
)
var (
AppName = ""
LocalesPath = ""
builtinPool *Pool
mainContext Translator
)
func Init() {
if builtinPool != nil {
return
}
if AppName == "" {
AppName = v.AppName
}
if LocalesPath == "" {
LocalesPath = "/usr/share/locale"
}
var err error
builtinPool, err = NewPool(LocalesPath, AppName, false)
dry.PanicIfErr(err)
mainContext, err = GetContext(envy.Get("LANGUAGE", "en_US"))
dry.PanicIfErr(err)
}
func SetLanguage(lang string) error {
Init()
ctx, err := builtinPool.GetContext(lang)
if err != nil {
return errors.Wrap(err, "getting language context")
}
mainContext = ctx
return nil
}
func Tr(key string) string {
Init()
return mainContext.Tr(key)
}
func Trf(key string, params plurr.Params) (string, error) {
Init()
return mainContext.Trf(key, params)
}
func Strf(key string, params plurr.Params) string {
Init()
return mainContext.Strf(key, params)
}
func GetContext(lang string) (Translator, error) {
Init()
err := LoadResource(lang)
if err != nil {
return nil, errors.Wrap(err, "loading resource")
}
return &Context{
pool: builtinPool,
lang: lang,
plurr: plurr.New().SetLocale(lang),
}, nil
}
func LoadResource(lang string) error {
Init()
res, err := walkDir(filepath.Join(builtinPool.resourcePath, lang, builtinPool.appName))
if err == nil {
builtinPool.Resources[lang] = res
}
return errors.Wrap(err, "can't load '"+lang+"'")
}
func MustAll(items []string) error {
Init()
return mainContext.MustAll(items)
}
func Message(key string) MessageCode {
return ImplicitCtxMessage(&mainContext, key)
}
func MessageWithParams(key string) MessageWithParamsCode {
return ImplicitCtxMessageWithParams(&mainContext, key)
}
func DefaultTranslator() Translator {
Init()
return mainContext
}