-
-
Notifications
You must be signed in to change notification settings - Fork 30
/
custom_data.go
88 lines (71 loc) · 1.91 KB
/
custom_data.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
package flect
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
func init() {
loadCustomData("inflections.json", "INFLECT_PATH", "could not read inflection file", LoadInflections)
loadCustomData("acronyms.json", "ACRONYMS_PATH", "could not read acronyms file", LoadAcronyms)
}
//CustomDataParser are functions that parse data like acronyms or
//plurals in the shape of a io.Reader it receives.
type CustomDataParser func(io.Reader) error
func loadCustomData(defaultFile, env, readErrorMessage string, parser CustomDataParser) {
pwd, _ := os.Getwd()
path, found := os.LookupEnv(env)
if !found {
path = filepath.Join(pwd, defaultFile)
}
if _, err := os.Stat(path); err != nil {
return
}
b, err := ioutil.ReadFile(path)
if err != nil {
fmt.Printf("%s %s (%s)\n", readErrorMessage, path, err)
return
}
if err = parser(bytes.NewReader(b)); err != nil {
fmt.Println(err)
}
}
//LoadAcronyms loads rules from io.Reader param
func LoadAcronyms(r io.Reader) error {
m := []string{}
err := json.NewDecoder(r).Decode(&m)
if err != nil {
return fmt.Errorf("could not decode acronyms JSON from reader: %s", err)
}
acronymsMoot.Lock()
defer acronymsMoot.Unlock()
for _, acronym := range m {
baseAcronyms[acronym] = true
}
return nil
}
//LoadInflections loads rules from io.Reader param
func LoadInflections(r io.Reader) error {
m := map[string]string{}
err := json.NewDecoder(r).Decode(&m)
if err != nil {
return fmt.Errorf("could not decode inflection JSON from reader: %s", err)
}
pluralMoot.Lock()
defer pluralMoot.Unlock()
singularMoot.Lock()
defer singularMoot.Unlock()
for s, p := range m {
if strings.Contains(s, " ") || strings.Contains(p, " ") {
// flect works with parts, so multi-words should not be allowed
return fmt.Errorf("inflection elements should be a single word")
}
singleToPlural[s] = p
pluralToSingle[p] = s
}
return nil
}