-
Notifications
You must be signed in to change notification settings - Fork 15
/
i18n.go
58 lines (52 loc) 路 1.38 KB
/
i18n.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
package i18n
import (
"fmt"
iso6391 "github.com/iyear/iso-639-1"
"github.com/iyear/searchx/pkg/utils"
"github.com/mitchellh/mapstructure"
"github.com/spf13/viper"
"io/fs"
"path/filepath"
"reflect"
)
func Read(path string, tmpl interface{}, hook mapstructure.DecodeHookFunc) error {
v := viper.New()
v.SetConfigFile(path)
if err := v.ReadInConfig(); err != nil {
return err
}
if err := v.Unmarshal(tmpl, viper.DecodeHook(mapstructure.ComposeDecodeHookFunc(textHook(), hook))); err != nil {
return err
}
return nil
}
func textHook() mapstructure.DecodeHookFunc {
return func(f reflect.Value, t reflect.Value) (interface{}, error) {
if f.Kind() == reflect.String && t.Type() == reflect.TypeOf(Text{}) {
return NewText(f.String())
}
return f.Interface(), nil
}
}
func Walk(dir string) ([]string, error) {
paths := make([]string, 0)
err := filepath.WalkDir(dir, func(path string, entry fs.DirEntry, err error) error {
if err != nil {
return fmt.Errorf("unable to walk template path: %s, err:%v", path, err)
}
if entry.IsDir() {
return nil
}
ext := filepath.Ext(path)
name := utils.GetFileName(path)
if ext != ".toml" || !iso6391.ValidCode(name) {
return fmt.Errorf("invalid template file: %s.Please check extension or name of the file", path)
}
paths = append(paths, path)
return nil
})
if err != nil {
return nil, err
}
return paths, nil
}