From 0e7cfc5e071121542dde064420b923bc19f489f4 Mon Sep 17 00:00:00 2001 From: Alestrix Date: Thu, 22 Apr 2021 17:44:55 +0200 Subject: [PATCH] Add JQ parsing to script provider (#894) Co-authored-by: Alex Stumpf Co-authored-by: Stumpf Co-authored-by: andig --- provider/script.go | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/provider/script.go b/provider/script.go index 2ca8891b5..67660ca50 100644 --- a/provider/script.go +++ b/provider/script.go @@ -3,12 +3,15 @@ package provider import ( "context" "errors" + "fmt" "os/exec" "strconv" "strings" "time" "github.com/andig/evcc/util" + "github.com/andig/evcc/util/jq" + "github.com/itchyny/gojq" "github.com/kballard/go-shellquote" ) @@ -21,6 +24,7 @@ type Script struct { updated time.Time val string err error + jq *gojq.Query } func init() { @@ -33,6 +37,7 @@ func NewScriptProviderFromConfig(other map[string]interface{}) (IntProvider, err Cmd string Timeout time.Duration Cache time.Duration + Jq string }{ Timeout: 5 * time.Second, } @@ -41,18 +46,27 @@ func NewScriptProviderFromConfig(other map[string]interface{}) (IntProvider, err return nil, err } - return NewScriptProvider(cc.Cmd, cc.Timeout, cc.Cache) + return NewScriptProvider(cc.Cmd, cc.Timeout, cc.Jq, cc.Cache) } // NewScriptProvider creates a script provider. // Script execution is aborted after given timeout. -func NewScriptProvider(script string, timeout time.Duration, cache time.Duration) (*Script, error) { +func NewScriptProvider(script string, timeout time.Duration, jq string, cache time.Duration) (*Script, error) { s := &Script{ log: util.NewLogger("script"), script: script, timeout: timeout, cache: cache, } + + if jq != "" { + op, err := gojq.Parse(jq) + if err != nil { + return nil, fmt.Errorf("invalid jq query '%s': %w", jq, err) + } + + s.jq = op + } return s, nil } @@ -83,6 +97,7 @@ func (e *Script) exec(script string) (string, error) { } e.log.TRACE.Printf("%s: %s", strings.Join(args, " "), s) + return s, nil } @@ -92,8 +107,15 @@ func (e *Script) StringGetter() func() (string, error) { if time.Since(e.updated) > e.cache { e.val, e.err = e.exec(e.script) e.updated = time.Now() - } + if e.err == nil && e.jq != nil { + var v interface{} + if v, e.err = jq.Query(e.jq, []byte(e.val)); e.err == nil { + e.val = fmt.Sprintf("%v", v) + } + } + } + return e.val, e.err } }