...
1 package flect
2
3 import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "io"
8 "io/ioutil"
9 "os"
10 "path/filepath"
11 "strings"
12 )
13
14 func init() {
15 loadCustomData("inflections.json", "INFLECT_PATH", "could not read inflection file", LoadInflections)
16 loadCustomData("acronyms.json", "ACRONYMS_PATH", "could not read acronyms file", LoadAcronyms)
17 }
18
19
20
21 type CustomDataParser func(io.Reader) error
22
23 func loadCustomData(defaultFile, env, readErrorMessage string, parser CustomDataParser) {
24 pwd, _ := os.Getwd()
25 path, found := os.LookupEnv(env)
26 if !found {
27 path = filepath.Join(pwd, defaultFile)
28 }
29
30 if _, err := os.Stat(path); err != nil {
31 return
32 }
33
34 b, err := ioutil.ReadFile(path)
35 if err != nil {
36 fmt.Printf("%s %s (%s)\n", readErrorMessage, path, err)
37 return
38 }
39
40 if err = parser(bytes.NewReader(b)); err != nil {
41 fmt.Println(err)
42 }
43 }
44
45
46 func LoadAcronyms(r io.Reader) error {
47 m := []string{}
48 err := json.NewDecoder(r).Decode(&m)
49
50 if err != nil {
51 return fmt.Errorf("could not decode acronyms JSON from reader: %s", err)
52 }
53
54 acronymsMoot.Lock()
55 defer acronymsMoot.Unlock()
56
57 for _, acronym := range m {
58 baseAcronyms[acronym] = true
59 }
60
61 return nil
62 }
63
64
65 func LoadInflections(r io.Reader) error {
66 m := map[string]string{}
67
68 err := json.NewDecoder(r).Decode(&m)
69 if err != nil {
70 return fmt.Errorf("could not decode inflection JSON from reader: %s", err)
71 }
72
73 pluralMoot.Lock()
74 defer pluralMoot.Unlock()
75 singularMoot.Lock()
76 defer singularMoot.Unlock()
77
78 for s, p := range m {
79 if strings.Contains(s, " ") || strings.Contains(p, " ") {
80
81 return fmt.Errorf("inflection elements should be a single word")
82 }
83 singleToPlural[s] = p
84 pluralToSingle[p] = s
85 }
86
87 return nil
88 }
89
View as plain text