github.com/jenkins-x/jx/v2@v2.1.155/pkg/util/json/patch.go (about) 1 package json 2 3 import ( 4 "encoding/json" 5 "errors" 6 7 "github.com/mattbaird/jsonpatch" 8 ) 9 10 // CreatePatch creates a patch as specified in http://jsonpatch.com/. 11 // 12 // 'before' is original, 'after' is the modified struct. 13 // The function will return the patch as byte array. 14 // 15 // An error will be returned if any of the two structs is nil. 16 func CreatePatch(before, after interface{}) ([]byte, error) { 17 if before == nil { 18 return nil, errors.New("'before' cannot be nil when creating a JSON patch") 19 } 20 21 if after == nil { 22 return nil, errors.New("'after' cannot be nil when creating a JSON patch") 23 } 24 25 rawBefore, rawAfter, err := marshallBeforeAfter(before, after) 26 if err != nil { 27 return nil, err 28 } 29 patch, err := jsonpatch.CreatePatch(rawBefore, rawAfter) 30 if err != nil { 31 return nil, err 32 } 33 jsonPatch, err := json.Marshal(patch) 34 if err != nil { 35 return nil, err 36 } 37 return jsonPatch, nil 38 } 39 40 func marshallBeforeAfter(before, after interface{}) ([]byte, []byte, error) { 41 rawBefore, err := json.Marshal(before) 42 if err != nil { 43 return nil, nil, err 44 } 45 46 rawAfter, err := json.Marshal(after) 47 if err != nil { 48 return rawBefore, nil, err 49 } 50 51 return rawBefore, rawAfter, nil 52 } 53 54 // Patch is a slice of JsonPatchOperations 55 type Patch []jsonpatch.JsonPatchOperation 56 57 // MarshalJSON converts the Patch into a byte array 58 func (p Patch) MarshalJSON() ([]byte, error) { 59 return json.Marshal([]jsonpatch.JsonPatchOperation(p)) 60 }