-
Notifications
You must be signed in to change notification settings - Fork 202
/
output_jsonpath.go
88 lines (72 loc) · 2.23 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
85
86
87
88
package builder
import (
"bytes"
"context"
"encoding/json"
"fmt"
"get.porter.sh/porter/pkg/runtime"
"get.porter.sh/porter/pkg/tracing"
"github.com/PaesslerAG/jsonpath"
)
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(ctx context.Context, cfg runtime.RuntimeConfig, step StepWithOutputs, stdout string) error {
_, span := tracing.StartSpan(ctx)
defer span.EndSpan()
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 cfg.DebugMode {
fmt.Fprintf(cfg.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 span.Error(fmt.Errorf("error unmarshaling stdout as json %s: %w", stdout, err))
}
}
}
// 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 span.Error(fmt.Errorf("error evaluating jsonpath %q for output %q against %s: %w", outputPath, outputName, stdout, err))
}
// 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 span.Error(fmt.Errorf("error marshaling jsonpath result %v for output %q: %w", valueB, outputName, err))
}
default:
valueB = []byte(fmt.Sprintf("%v", t))
}
}
err := cfg.WriteMixinOutputToFile(outputName, valueB)
if err != nil {
return span.Error(fmt.Errorf("error writing mixin output for %q: %w", outputName, err))
}
}
return nil
}