github.com/grahambrereton-form3/tilt@v0.10.18/internal/k8s/json_path.go (about) 1 package k8s 2 3 import ( 4 "bytes" 5 "strings" 6 7 "k8s.io/client-go/util/jsonpath" 8 ) 9 10 // This is just a wrapper around k8s jsonpath, mostly because k8s jsonpath doesn't produce errors containing 11 // the problematic path 12 // (and as long as we're here, deal with some of its other annoyances, like taking a "name" that doesn't do anything, 13 // and having a separate "Parse" step to make an instance actually useful, and making you use an io.Writer, and 14 // wrapping string results in quotes) 15 type JSONPath struct { 16 jp *jsonpath.JSONPath 17 path string 18 } 19 20 func NewJSONPath(s string) (JSONPath, error) { 21 jp := jsonpath.New("jp") 22 err := jp.Parse(s) 23 if err != nil { 24 return JSONPath{}, err 25 } 26 27 return JSONPath{jp, s}, nil 28 } 29 30 // Gets the value at the specified path 31 // NB: currently strips away surrounding quotes, which the underlying parser includes in its return value 32 // If, at some point, we want to distinguish between, e.g., ints and strings by the presence of quotes, this 33 // will need to be revisited. 34 func (jp JSONPath) Execute(obj interface{}) (string, error) { 35 buf := &bytes.Buffer{} 36 err := jp.jp.Execute(buf, obj) 37 if err != nil { 38 return "", err 39 } 40 return strings.Trim(buf.String(), "\""), nil 41 } 42 43 func (jp JSONPath) String() string { 44 return jp.path 45 }