github.com/choria-io/go-choria@v0.28.1-0.20240416190746-b3bf9c7d5a45/aagent/watchers/expressionwatcher/matcher.go (about) 1 // Copyright (c) 2024, R.I. Pienaar and the Choria Project contributors 2 // 3 // SPDX-License-Identifier: Apache-2.0 4 5 package expressionwatcher 6 7 import ( 8 "fmt" 9 10 "github.com/expr-lang/expr" 11 ) 12 13 func (w *Watcher) evaluateExpression(e string) (bool, error) { 14 if e == "" { 15 return false, fmt.Errorf("invalid expression") 16 } 17 18 env := map[string]any{ 19 "data": w.machine.Data(), 20 "facts": w.machine.Facts(), 21 "identity": w.machine.Identity(), 22 } 23 24 execEnv := expr.Env(env) 25 prog, err := expr.Compile(e, execEnv, expr.AsBool()) 26 if err != nil { 27 return false, err 28 } 29 30 res, err := expr.Run(prog, env) 31 if err != nil { 32 return false, err 33 } 34 35 b, ok := res.(bool) 36 if !ok { 37 return false, fmt.Errorf("match was non boolean") 38 } 39 40 w.Debugf("Evaluated expression %q returned: %v", e, b) 41 42 return b, nil 43 }