forked from SAP/jenkins-library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsonApplyPatch.go
59 lines (51 loc) · 1.29 KB
/
jsonApplyPatch.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
package cmd
import (
"bytes"
"encoding/json"
"github.com/SAP/jenkins-library/pkg/log"
"github.com/SAP/jenkins-library/pkg/piperutils"
"github.com/SAP/jenkins-library/pkg/telemetry"
"github.com/evanphx/json-patch"
)
func jsonApplyPatch(config jsonApplyPatchOptions, telemetryData *telemetry.CustomData) {
err := runJsonApplyPatch(&config, &piperutils.Files{})
if err != nil {
log.Entry().WithError(err).Fatal("step execution failed")
}
}
func runJsonApplyPatch(config *jsonApplyPatchOptions, fileUtils piperutils.FileUtils) error {
schema, err := fileUtils.FileRead(config.Input)
if err != nil {
return err
}
patchFile, err := fileUtils.FileRead(config.Patch)
if err != nil {
return err
}
patcher, err := jsonpatch.DecodePatch(patchFile)
if err != nil {
return err
}
patchedSchema, err := patcher.Apply(schema)
if err != nil {
return err
}
formattedJson, err := formatJson(patchedSchema)
if err != nil {
// Ignore error and just use original result.
formattedJson = patchedSchema
}
err = fileUtils.FileWrite(config.Output, formattedJson, 0644)
if err != nil {
return err
}
return nil
}
func formatJson(input []byte) ([]byte, error) {
var output bytes.Buffer
err := json.Indent(&output, input, "", " ")
if err != nil {
return nil, err
}
return output.Bytes(), nil
}