forked from qor/qor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
yaml.go
82 lines (70 loc) · 1.97 KB
/
yaml.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
package yaml
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"gopkg.in/yaml.v2"
"github.com/qor/qor/i18n"
)
func New(paths ...string) i18n.Backend {
backend := &Backend{}
for _, p := range paths {
if file, err := os.Open(p); err == nil {
defer file.Close()
if fileInfo, err := file.Stat(); err == nil {
if fileInfo.IsDir() {
yamlFiles, _ := filepath.Glob(path.Join(p, "*.yaml"))
backend.files = append(backend.files, yamlFiles...)
ymlFiles, _ := filepath.Glob(path.Join(p, "*.yml"))
backend.files = append(backend.files, ymlFiles...)
} else if fileInfo.Mode().IsRegular() {
backend.files = append(backend.files, p)
}
}
}
}
return backend
}
type Backend struct {
files []string
}
func loadTranslationsFromYaml(locale string, value interface{}, scopes []string) (translations []*i18n.Translation) {
switch v := value.(type) {
case yaml.MapSlice:
for _, s := range v {
results := loadTranslationsFromYaml(locale, s.Value, append(scopes, fmt.Sprintf("%v", s.Key)))
translations = append(translations, results...)
}
default:
var translation = &i18n.Translation{
Locale: locale,
Key: strings.Join(scopes, "."),
Value: fmt.Sprintf("%v", v),
}
translations = append(translations, translation)
}
return
}
func (backend *Backend) LoadTranslations() (translations []*i18n.Translation) {
for _, file := range backend.files {
if content, err := ioutil.ReadFile(file); err == nil {
var slice yaml.MapSlice
if err := yaml.Unmarshal(content, &slice); err == nil {
for _, item := range slice {
translations = append(translations, loadTranslationsFromYaml(item.Key.(string) /* locale */, item.Value, []string{})...)
}
}
}
}
return translations
}
func (backend *Backend) SaveTranslation(t *i18n.Translation) error {
return errors.New("not implemented")
}
func (backend *Backend) DeleteTranslation(t *i18n.Translation) error {
return errors.New("not implemented")
}