You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.2 KiB

  1. package script
  2. import (
  3. "log"
  4. "strconv"
  5. "strings"
  6. )
  7. type Condition struct {
  8. Scope string `json:"scope"`
  9. Key string `json:"key"`
  10. Op string `json:"op"`
  11. Value string `json:"value,omitempty"`
  12. Not bool `json:"not,omitempty"`
  13. }
  14. func (c *Condition) Check(set VariableSet, match string, devices []string) bool {
  15. var value string
  16. switch c.Scope {
  17. case "global":
  18. value = set.Global(c.Key)
  19. case "match":
  20. value = set.Match(match, c.Key)
  21. case "devices":
  22. value = set.Devices(devices, c.Key)
  23. default:
  24. return c.Not
  25. }
  26. valueInt, valueIntErr := strconv.ParseInt(value, 10, 64)
  27. targetInt, _ := strconv.ParseInt(c.Value, 10, 64)
  28. switch c.Op {
  29. case "eq":
  30. return !c.Not == (value == c.Value)
  31. case "neq":
  32. return !c.Not == (value != c.Value)
  33. case "gt":
  34. return !c.Not == (valueInt > targetInt)
  35. case "lt":
  36. return !c.Not == (valueInt < targetInt)
  37. case "gte":
  38. log.Println(c.Not, valueInt, targetInt)
  39. return !c.Not == (valueInt >= targetInt)
  40. case "lte":
  41. return !c.Not == (valueInt <= targetInt)
  42. case "exists":
  43. return !c.Not == (value != "")
  44. case "contains":
  45. return !c.Not == strings.Contains(value, c.Value)
  46. case "numerical":
  47. return !c.Not == (valueIntErr == nil)
  48. default:
  49. return c.Not
  50. }
  51. }