github.com/jaylevin/jenkins-library@v1.230.4/cmd/jsonApplyPatch.go (about) 1 package cmd 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "github.com/SAP/jenkins-library/pkg/log" 7 "github.com/SAP/jenkins-library/pkg/piperutils" 8 "github.com/SAP/jenkins-library/pkg/telemetry" 9 "github.com/evanphx/json-patch" 10 ) 11 12 func jsonApplyPatch(config jsonApplyPatchOptions, telemetryData *telemetry.CustomData) { 13 err := runJsonApplyPatch(&config, &piperutils.Files{}) 14 if err != nil { 15 log.Entry().WithError(err).Fatal("step execution failed") 16 } 17 } 18 19 func runJsonApplyPatch(config *jsonApplyPatchOptions, fileUtils piperutils.FileUtils) error { 20 schema, err := fileUtils.FileRead(config.Input) 21 if err != nil { 22 return err 23 } 24 25 patchFile, err := fileUtils.FileRead(config.Patch) 26 if err != nil { 27 return err 28 } 29 patcher, err := jsonpatch.DecodePatch(patchFile) 30 if err != nil { 31 return err 32 } 33 34 patchedSchema, err := patcher.Apply(schema) 35 if err != nil { 36 return err 37 } 38 39 formattedJson, err := formatJson(patchedSchema) 40 if err != nil { 41 // Ignore error and just use original result. 42 formattedJson = patchedSchema 43 } 44 45 err = fileUtils.FileWrite(config.Output, formattedJson, 0644) 46 if err != nil { 47 return err 48 } 49 return nil 50 } 51 52 func formatJson(input []byte) ([]byte, error) { 53 var output bytes.Buffer 54 err := json.Indent(&output, input, "", " ") 55 if err != nil { 56 return nil, err 57 } 58 return output.Bytes(), nil 59 }