-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinterpol.go
94 lines (80 loc) · 1.95 KB
/
interpol.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
package interpol
import (
"fmt"
"io/ioutil"
"regexp"
"sort"
yaml "gopkg.in/yaml.v2"
)
func Check(configFilePath string) Result {
config := parseConfig(configFilePath)
result := Result{}
masterTranslations := getTranslations(&result, config.Master)
for _, locale := range config.Locales {
for k, v := range getTranslations(&result, locale) {
if masterValue, ok := masterTranslations[k]; ok {
if differentInterpolations(masterValue, v) {
result.Errors = append(result.Errors, Issue{
Locale: locale.Name,
Message: fmt.Sprintf("Inconsistent interpolation for %s", k),
})
}
}
}
}
return result
}
func getTranslations(result *Result, l locale) translations {
fileContents, err := translationsPerFileFor(l)
if err != nil {
result.Errors = append(result.Errors, Issue{
Locale: l.Name,
Message: err.Error(),
})
}
normalized := translations{}
for i := 0; i < len(fileContents); i++ {
normalized.addMap("", fileContents[i])
}
return normalized
}
func translationsPerFileFor(l locale) ([]map[interface{}]interface{}, error) {
translations := make([]map[interface{}]interface{}, len(l.Files))
for _, file := range l.Files {
data, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
var i map[interface{}]interface{}
err = yaml.Unmarshal([]byte(data), &i)
if err != nil {
return nil, err
}
translations = append(translations, i)
}
return translations, nil
}
func differentInterpolations(m, v string) bool {
mi := interpolations(m)
mv := interpolations(v)
if len(mi) != len(mv) {
return true
}
if len(mi) > 0 {
for i, v := range mi {
if v != mv[i] {
return true
}
}
}
return false
}
func interpolations(text string) []string {
re := regexp.MustCompile("%{(\\w+)}")
interpolations := make([]string, 0)
for _, key := range re.FindAllStringSubmatch(text, -1) {
interpolations = append(interpolations, key[1])
}
sort.Strings(interpolations)
return interpolations
}