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