| 221 | } |
| 222 | |
| 223 | func ApplyPatchesOnObject(data map[string]interface{}, configPatches []*latest.PatchConfig) (map[string]interface{}, error) { |
| 224 | out, err := yaml.Marshal(data) |
| 225 | if err != nil { |
| 226 | return nil, err |
| 227 | } |
| 228 | |
| 229 | var doc yaml.Node |
| 230 | if err := yaml.Unmarshal(out, &doc); err != nil { |
| 231 | return nil, err |
| 232 | } |
| 233 | |
| 234 | patches := patch.Patch{} |
| 235 | for idx, patchConfig := range configPatches { |
| 236 | if patchConfig.Operation == "" { |
| 237 | return nil, errors.Errorf("patches.%d.op is missing", idx) |
| 238 | } else if patchConfig.Path == "" { |
| 239 | return nil, errors.Errorf("patches.%d.path is missing", idx) |
| 240 | } |
| 241 | |
| 242 | newPatch := patch.Operation{ |
| 243 | Op: patch.Op(patchConfig.Operation), |
| 244 | Path: patch.OpPath(patch.TransformPath(patchConfig.Path)), |
| 245 | } |
| 246 | |
| 247 | if patchConfig.Value != nil { |
| 248 | value, err := patch.NewNode(&patchConfig.Value) |
| 249 | if err != nil { |
| 250 | return nil, errors.Errorf("patches.%d.value is invalid", idx) |
| 251 | } |
| 252 | newPatch.Value = value |
| 253 | } |
| 254 | |
| 255 | if string(newPatch.Op) == "remove" && patchConfig.Path[0] != '/' { |
| 256 | // figure out automatically if the path to remove is not there and just skip the patch |
| 257 | target, _ := findPath(&newPatch.Path, &doc) |
| 258 | if target == nil { |
| 259 | continue |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | if string(newPatch.Op) == "replace" && patchConfig.Path[0] != '/' { |
| 264 | // figure out automatically if to use add or replace based on if the target path exists or not |
| 265 | target, _ := findPath(&newPatch.Path, &doc) |
| 266 | if target == nil { |
| 267 | newPatch.Op = patch.Op("add") |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | patches = append(patches, newPatch) |
| 272 | } |
| 273 | |
| 274 | out, err = patches.Apply(out) |
| 275 | if err != nil { |
| 276 | return nil, errors.Wrap(err, "apply patches") |
| 277 | } |
| 278 | |
| 279 | newConfig := map[string]interface{}{} |
| 280 | err = yaml.Unmarshal(out, &newConfig) |