exprlib.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package exprhelpers
  2. import (
  3. "bufio"
  4. "os"
  5. "path"
  6. "regexp"
  7. "strconv"
  8. "strings"
  9. log "github.com/sirupsen/logrus"
  10. )
  11. var dataFile map[string][]string
  12. var dataFileRegex map[string][]*regexp.Regexp
  13. func Atof(x string) float64 {
  14. log.Debugf("debug atof %s", x)
  15. ret, err := strconv.ParseFloat(x, 64)
  16. if err != nil {
  17. log.Warningf("Atof : can't convert float '%s' : %v", x, err)
  18. }
  19. return ret
  20. }
  21. func StartsWith(s string, pref string) bool {
  22. return strings.HasPrefix(s, pref)
  23. }
  24. func EndsWith(s string, suff string) bool {
  25. return strings.HasSuffix(s, suff)
  26. }
  27. func GetExprEnv(ctx map[string]interface{}) map[string]interface{} {
  28. var ExprLib = map[string]interface{}{"Atof": Atof, "JsonExtract": JsonExtract, "JsonExtractLib": JsonExtractLib, "File": File, "RegexpInFile": RegexpInFile}
  29. for k, v := range ctx {
  30. ExprLib[k] = v
  31. }
  32. return ExprLib
  33. }
  34. func Init() error {
  35. log.Infof("Expr helper initiated")
  36. dataFile = make(map[string][]string)
  37. dataFileRegex = make(map[string][]*regexp.Regexp)
  38. return nil
  39. }
  40. func FileInit(fileFolder string, filename string) error {
  41. filepath := path.Join(fileFolder, filename)
  42. file, err := os.Open(filepath)
  43. if err != nil {
  44. log.Fatal(err)
  45. }
  46. defer file.Close()
  47. if _, ok := dataFile[filename]; !ok {
  48. dataFile[filename] = []string{}
  49. }
  50. fileType := "string"
  51. scanner := bufio.NewScanner(file)
  52. scanner.Scan()
  53. if scanner.Text() == "#type: regex" { // if file contains regexps, it should have this header
  54. fileType = "regex"
  55. }
  56. for scanner.Scan() {
  57. if fileType == "regex" {
  58. dataFileRegex[filename] = append(dataFileRegex[filename], regexp.MustCompile(scanner.Text()))
  59. } else {
  60. dataFile[filename] = append(dataFile[filename], scanner.Text())
  61. }
  62. }
  63. if err := scanner.Err(); err != nil {
  64. log.Fatal(err)
  65. }
  66. return nil
  67. }
  68. func File(filename string) []string {
  69. if _, ok := dataFile[filename]; ok {
  70. return dataFile[filename]
  71. }
  72. log.Errorf("file '%s' not found for expr library", filename)
  73. return []string{}
  74. }
  75. func RegexpInFile(data string, filename string) bool {
  76. if _, ok := dataFileRegex[filename]; ok {
  77. for _, re := range dataFileRegex[filename] {
  78. if re.Match([]byte(data)) {
  79. return true
  80. }
  81. }
  82. } else {
  83. log.Errorf("file '%s' not found for expr library", filename)
  84. }
  85. return false
  86. }