This repository was archived by the owner on Jan 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathpatch.go
More file actions
83 lines (68 loc) · 1.58 KB
/
patch.go
File metadata and controls
83 lines (68 loc) · 1.58 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package yamlpatch
import (
"bytes"
"fmt"
"io"
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) {
decoder := yaml.NewDecoder(bytes.NewReader(doc))
buf := bytes.NewBuffer([]byte{})
encoder := yaml.NewEncoder(buf)
for {
var iface interface{}
err := decoder.Decode(&iface)
if err != nil {
if err == io.EOF {
break
}
return nil, fmt.Errorf("failed to decode 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 i := len(paths) - 1; i >= 0; i-- {
path := paths[i]
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
}
}
}
err = encoder.Encode(c)
if err != nil {
return nil, fmt.Errorf("failed to encode container: %s", err)
}
}
err := encoder.Close()
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}