-
Notifications
You must be signed in to change notification settings - Fork 199
/
output_jsonpath.go
84 lines (69 loc) · 2.07 KB
/
output_jsonpath.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package builder
import (
"bytes"
"encoding/json"
"fmt"
"get.porter.sh/porter/pkg/context"
"github.com/PaesslerAG/jsonpath"
"github.com/pkg/errors"
)
type OutputJsonPath interface {
Output
GetJsonPath() string
}
// ProcessJsonPathOutputs evaluates the specified output buffer as JSON, looks through the outputs for
// any that implement the OutputJsonPath and extracts their output.
func ProcessJsonPathOutputs(cxt *context.Context, step StepWithOutputs, stdout string) error {
outputs := step.GetOutputs()
if len(outputs) == 0 {
return nil
}
var outputJson interface{}
for _, o := range outputs {
output, ok := o.(OutputJsonPath)
if !ok {
continue
}
outputName := output.GetName()
outputPath := output.GetJsonPath()
if outputPath == "" {
continue
}
if cxt.Debug {
fmt.Fprintf(cxt.Err, "Processing jsonpath output %s using query %s against document\n%s\n", outputName, outputPath, stdout)
}
var valueB []byte
if outputJson == nil {
if stdout != "" {
d := json.NewDecoder(bytes.NewBuffer([]byte(stdout)))
d.UseNumber()
err := d.Decode(&outputJson)
if err != nil {
return errors.Wrapf(err, "error unmarshaling stdout as json %s", stdout)
}
}
}
// Always write an output, even when there isn't json output to parse (like when stdout is empty)
if outputJson != nil {
value, err := jsonpath.Get(outputPath, outputJson)
if err != nil {
return errors.Wrapf(err, "error evaluating jsonpath %q for output %q against %s", outputPath, outputName, stdout)
}
// Only marshal complex types to json, leave strings, numbers and booleans alone
switch t := value.(type) {
case map[string]interface{}, []interface{}:
valueB, err = json.Marshal(value)
if err != nil {
return errors.Wrapf(err, "error marshaling jsonpath result %v for output %q", valueB, outputName)
}
default:
valueB = []byte(fmt.Sprintf("%v", t))
}
}
err := cxt.WriteMixinOutputToFile(outputName, valueB)
if err != nil {
return errors.Wrapf(err, "error writing mixin output for %q", outputName)
}
}
return nil
}