2022-01-04 17:36:33 -08:00
|
|
|
package patch
|
2020-09-03 08:54:37 -07:00
|
|
|
|
|
|
|
import (
|
2023-06-07 11:45:11 +02:00
|
|
|
"fmt"
|
2020-09-03 08:54:37 -07:00
|
|
|
|
2023-06-08 12:23:20 +02:00
|
|
|
"gomodules.xyz/jsonpatch/v2"
|
2023-06-07 11:45:11 +02:00
|
|
|
"sigs.k8s.io/yaml"
|
2020-09-03 08:54:37 -07:00
|
|
|
)
|
|
|
|
|
2023-04-28 09:31:12 +02:00
|
|
|
func ConvertPatches(in ...jsonpatch.JsonPatchOperation) [][]byte {
|
|
|
|
var out [][]byte
|
|
|
|
for _, patch := range in {
|
|
|
|
if patch, err := patch.MarshalJSON(); err == nil {
|
|
|
|
out = append(out, patch)
|
2020-09-03 08:54:37 -07:00
|
|
|
}
|
|
|
|
}
|
2023-04-28 09:31:12 +02:00
|
|
|
return out
|
|
|
|
}
|
2020-09-03 08:54:37 -07:00
|
|
|
|
2023-06-07 11:45:11 +02:00
|
|
|
func convertPatchesToJSON(patchesJSON6902 string) ([]byte, error) {
|
|
|
|
if len(patchesJSON6902) == 0 {
|
|
|
|
return []byte(patchesJSON6902), nil
|
2023-04-28 09:31:12 +02:00
|
|
|
}
|
2023-06-07 11:45:11 +02:00
|
|
|
if patchesJSON6902[0] != '[' {
|
|
|
|
// If the patch doesn't look like a JSON6902 patch, we
|
|
|
|
// try to parse it to json.
|
|
|
|
op, err := yaml.YAMLToJSON([]byte(patchesJSON6902))
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to convert patchesJSON6902 to JSON: %v", err)
|
2021-01-19 11:08:06 -08:00
|
|
|
}
|
2023-06-07 11:45:11 +02:00
|
|
|
return op, nil
|
2021-01-19 11:08:06 -08:00
|
|
|
}
|
2023-06-07 11:45:11 +02:00
|
|
|
return []byte(patchesJSON6902), nil
|
2021-01-19 11:08:06 -08:00
|
|
|
}
|
|
|
|
|
2023-06-07 11:45:11 +02:00
|
|
|
func generatePatches(src, dst []byte) ([]jsonpatch.JsonPatchOperation, error) {
|
|
|
|
pp, err := jsonpatch.CreatePatch(src, dst)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2021-01-19 11:08:06 -08:00
|
|
|
}
|
2023-06-07 11:45:11 +02:00
|
|
|
return pp, nil
|
2021-01-19 11:08:06 -08:00
|
|
|
}
|