/
patch.go
75 lines (60 loc) · 1.77 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package rest
import (
"encoding/json"
jsonpatch "github.com/evanphx/json-patch"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
)
type patch struct {
patchType types.PatchType
data []byte
}
// Type implements Patch.
func (s *patch) Type() types.PatchType {
return s.patchType
}
// Data implements Patch.
func (s *patch) Data(obj Object) ([]byte, error) {
return s.data, nil
}
// ConstantPatch constructs a new Patch with the given PatchType and data.
func ConstantPatch(patchType types.PatchType, data []byte) Patch {
return &patch{patchType, data}
}
type mergeFromPatch struct {
from runtime.Object
}
// Type implements patch.
func (s *mergeFromPatch) Type() types.PatchType {
return types.MergePatchType
}
// Data implements Patch.
func (s *mergeFromPatch) Data(obj Object) ([]byte, error) {
originalJSON, err := json.Marshal(s.from)
if err != nil {
return nil, err
}
modifiedJSON, err := json.Marshal(obj)
if err != nil {
return nil, err
}
return jsonpatch.CreateMergePatch(originalJSON, modifiedJSON)
}
// MergeFrom creates a Patch that patches using the merge-patch strategy with the given object as base.
func MergeFrom(obj runtime.Object) Patch {
return &mergeFromPatch{obj}
}
// applyPatch uses server-side apply to patch the object.
type applyPatch struct{}
// Type implements Patch.
func (p applyPatch) Type() types.PatchType {
return types.ApplyPatchType
}
// Data implements Patch.
func (p applyPatch) Data(obj runtime.Object) ([]byte, error) {
// NB(directxman12): we might technically want to be using an actual encoder
// here (in case some more performant encoder is introduced) but this is
// correct and sufficient for our uses (it's what the JSON serializer in
// client-go does, more-or-less).
return json.Marshal(obj)
}