2
0

custom_data.go 1.7 KB

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