forked from vmware-archive/yaml-patch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
patch.go
60 lines (49 loc) · 1.17 KB
/
patch.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
60
package yamlpatch
import (
"fmt"
yaml "gopkg.in/yaml.v2"
)
// Patch is an ordered collection of operations.
type Patch []Operation
// DecodePatch decodes the passed YAML document as if it were an RFC 6902 patch
func DecodePatch(bs []byte) (Patch, error) {
var p Patch
err := yaml.Unmarshal(bs, &p)
if err != nil {
return nil, err
}
return p, nil
}
// Apply returns a YAML document that has been mutated per the patch
func (p Patch) Apply(doc []byte) ([]byte, error) {
var iface interface{}
err := yaml.Unmarshal(doc, &iface)
if err != nil {
return nil, fmt.Errorf("failed unmarshaling doc: %s\n\n%s", string(doc), err)
}
var c Container
c = NewNode(&iface).Container()
for _, op := range p {
pathfinder := NewPathFinder(c)
if op.Path.ContainsExtendedSyntax() {
paths := pathfinder.Find(string(op.Path))
if paths == nil {
return nil, fmt.Errorf("could not expand pointer: %s", op.Path)
}
for _, path := range paths {
newOp := op
newOp.Path = OpPath(path)
err = newOp.Perform(c)
if err != nil {
return nil, err
}
}
} else {
err = op.Perform(c)
if err != nil {
return nil, err
}
}
}
return yaml.Marshal(c)
}