-
Notifications
You must be signed in to change notification settings - Fork 8
/
engine.go
83 lines (63 loc) · 1.53 KB
/
engine.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
package tr
import (
"io/ioutil"
"os"
"path/filepath"
"github.com/pkg/errors"
)
// NewEngine constructs a new translation engine.
func NewEngine(path, defaultLocale string, trim bool) (*Engine, error) {
e := &Engine{
Path: path,
Langs: map[string]*Locale{},
}
path, _ = filepath.Abs(path)
if files, err := ioutil.ReadDir(path); err == nil {
for _, file := range files {
if !file.IsDir() {
continue
}
name := file.Name()
paths := []string{}
err = filepath.Walk(path+"/"+name, func(fpath string, info os.FileInfo, err error) error {
if !info.IsDir() {
paths = append(paths, fpath)
}
return err
})
if err != nil {
return nil, errors.Wrap(err, "tr: couldn't walk thru files")
}
var c *Locale
c, err = NewLocale(path, name, paths, trim)
if err != nil {
return nil, err
}
e.Langs[name] = c
}
e.DefaultLocale = e.Langs[defaultLocale]
} else {
return nil, errors.Wrap(err, "tr: couldn't open locales")
}
return e, nil
}
// Engine represent a storage of locales.
type Engine struct {
Path string
DefaultLocale *Locale
Langs map[string]*Locale
}
// Lang returns a *Locale by name.
func (e *Engine) Lang(localeName string) *Locale {
if e.Langs == nil {
panic("tr: default engine is not sent, see tr.Init()")
}
return e.Langs[localeName]
}
// Tr provides default locale's translation of path.
func (e *Engine) Tr(path string) string {
if e.Langs == nil {
panic("tr: default engine is not sent, see tr.Init()")
}
return e.DefaultLocale.Tr(path)
}