-
Notifications
You must be signed in to change notification settings - Fork 199
/
output_regex.go
63 lines (52 loc) · 1.51 KB
/
output_regex.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
package builder
import (
"fmt"
"regexp"
"strings"
"get.porter.sh/porter/pkg/portercontext"
"github.com/pkg/errors"
)
type OutputRegex interface {
Output
GetRegex() string
}
// ProcessJsonPathOutputs looks through the outputs for any that implement the OutputRegex,
// applies the regular expression to the output buffer and extracts their output.
func ProcessRegexOutputs(cxt *portercontext.Context, step StepWithOutputs, stdout string) error {
outputs := step.GetOutputs()
if len(outputs) == 0 {
return nil
}
for _, o := range outputs {
output, ok := o.(OutputRegex)
if !ok {
continue
}
outputName := output.GetName()
outputRegex := output.GetRegex()
if outputRegex == "" {
continue
}
if cxt.Debug {
fmt.Fprintf(cxt.Err, "Processing regex output %s...", outputName)
}
r, err := regexp.Compile(outputRegex)
if err != nil {
return errors.Wrapf(err, "invalid regular expression %q for output %q", outputRegex, outputName)
}
// Find every submatch / capture and put it on its own line in the output file
results := r.FindAllStringSubmatch(stdout, -1)
var matches []string
for _, result := range results {
if len(result) > 1 { // Skip the first element which is the full match, we only want the capture groups
matches = append(matches, result[1:]...)
}
}
value := strings.Join(matches, "\n")
err = cxt.WriteMixinOutputToFile(outputName, []byte(value))
if err != nil {
return errors.Wrapf(err, "error writing mixin output for %q", outputName)
}
}
return nil
}