-
Notifications
You must be signed in to change notification settings - Fork 1
/
sejong.go
218 lines (185 loc) · 4.98 KB
/
sejong.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
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
// Copyright © 2020 Jaeho Cho <jaeho8032@gmail.com>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
// sejong is an simple translate library.
// it was inspired by ruby's i18n module.
package sejong
import (
"fmt"
"regexp"
"strconv"
"strings"
"github.com/pkg/errors"
"github.com/spf13/viper"
)
// Sejong handles locale configurations for translation.
type Sejong struct {
// Locale contains the language to be translate.
Locale string
// v gets the location of the locale file from the environment variable.
// v is also used to get the sentence using the key in each locale file.
v *viper.Viper
// locales is used when using translations in multiple languages
// at the same time to determine whether each locale file is loaded.
locales []string
}
// Locale contains the language to be translate. It is used only if you don't create your Sejong instance.
var Locale string
var sj *Sejong
func init() {
sj, _ = New("")
}
// New returns an initialized sejong instance.
func New(locale string) (*Sejong, error) {
v := viper.New()
v.SetEnvPrefix("SEJONG")
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
v.AutomaticEnv()
path := v.GetString("locale.directory")
if path == "" {
path = "."
}
v.AddConfigPath(path)
v.SetConfigType("yml")
var locales []string
if locale != "" {
v.SetConfigName(locale)
if err := v.ReadInConfig(); err != nil {
return nil, errors.New("sejong.New: locale file is not exist")
}
locales = append(locales, locale)
}
return &Sejong{
v: v,
locales: locales,
Locale: locale,
}, nil
}
// T translate a sentence found by key.
// In words, Each word in turn becomes key, value, key, value, ...
// In the sentence, each %{key} is replaced with a value.
func T(key string, words ...string) (string, error) {
sj.Locale = Locale
return sj.T(key, words...)
}
// T translate a sentence found by key.
// Each word in turn becomes key, value, key, value, ...
// In the sentence, each %{key} is replaced with a value.
func (s *Sejong) T(key string, words ...string) (string, error) {
if s.Locale == "" {
return "", errors.New("sejong.T: locale is not set")
}
var ok bool
for _, l := range s.locales {
if s.Locale == l {
ok = true
break
}
}
if !ok {
s.v.SetConfigName(s.Locale)
if err := s.v.ReadInConfig(); err != nil {
panic("sejong.T: locale file is not exist")
}
s.locales = append(s.locales, s.Locale)
}
dict, err := getDict(words)
if err != nil {
return "", errors.Wrap(err, "sejong.T")
}
key = s.Locale + "." + key
entry := s.v.Get(key)
if entry == nil {
return "", errors.New("sejong.T: not exist key")
}
sentence, err := getSentence(entry, dict)
if err != nil {
return "", errors.Wrap(err, "sejong.T")
}
r := newReplacer(words)
result := r.Replace(sentence)
if matched, _ := regexp.MatchString("%{\\w+}", result); matched {
return result, errors.New("sejong.T: translate is not completed")
}
return result, nil
}
// HasKey checks the key exists.
func HasKey(key string) bool {
return sj.HasKey(key)
}
// HasKey checks the key exists.
func (s *Sejong) HasKey(key string) bool {
key = s.Locale + "." + key
return s.v.IsSet(key)
}
func newReplacer(words []string) *strings.Replacer {
var keywords []string
for i, word := range words {
if i%2 == 0 {
keywords = append(keywords, fmt.Sprintf("%%{%s}", word))
} else {
keywords = append(keywords, word)
}
}
return strings.NewReplacer(keywords...)
}
func getDict(words []string) (map[string]string, error) {
if len(words) == 0 {
return nil, nil
} else if len(words)%2 == 1 {
return nil, errors.New("sejong.getDict: odd word count")
}
dict := make(map[string]string, len(words)/2)
for i := 0; i < len(words)-1; i += 2 {
key := words[i]
value := words[i+1]
dict[key] = value
}
return dict, nil
}
func getSentence(entry interface{}, dict map[string]string) (string, error) {
var sentence string
switch entry := entry.(type) {
case string:
sentence = entry
case map[string]interface{}:
if dict != nil && dict["count"] != "" {
count, err := strconv.ParseInt(dict["count"], 10, 64)
if err != nil {
return "", errors.Wrap(err, "sejong.T")
}
sentence, err = pluralize(entry, count)
if err != nil {
return "", errors.Wrap(err, "sejong.T")
}
} else {
return "", errors.New("sejong.T: count should be provided")
}
}
return sentence, nil
}
func pluralize(entryMap map[string]interface{}, count int64) (string, error) {
strMap := make(map[string]string, 4)
for k, v := range entryMap {
strMap[k] = v.(string)
}
if len(strMap) == 0 {
return "", errors.New("failed to pluralize")
}
key := pluralizationKey(strMap, count)
if strMap[key] != "" {
return strMap[key], nil
} else {
return "", errors.New("failed to pluralize")
}
}
func pluralizationKey(strMap map[string]string, count int64) string {
if count == 0 && strMap["zero"] != "" {
return "zero"
} else if count == 1 && strMap["one"] != "" {
return "one"
} else {
return "other"
}
}