custom_data.go 1.9 KB

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