forked from krishicks/yaml-patch
/
patching.go
63 lines (50 loc) · 1.21 KB
/
patching.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
package yamlpatch
import (
"log"
"strings"
"unicode/utf8"
zlog "github.com/rs/zerolog/log"
)
func trimFirstRune(s string) string {
_, i := utf8.DecodeRuneInString(s)
return s[i:]
}
func CreatePatch(patch string) (ops []byte) {
var patchOp string
var patchValue string
zlog.Debug().Msg("Received patch string " + patch)
patchPath := strings.Split(patch, "=")[0]
if len(strings.Split(patch, "=")) == 2 {
patchValue = strings.Split(patch, "=")[1]
}
if strings.HasPrefix(patchPath, "+") {
patchOp = "add"
patchPath = trimFirstRune(patchPath)
} else if strings.HasPrefix(patchPath, "-") {
patchOp = "remove"
patchPath = trimFirstRune(patchPath)
} else {
patchOp = "replace"
}
patchPath = "/" + strings.Replace(patchPath, ".", "/", -1)
ops = []byte(`---
- op: ` + patchOp + `
path: ` + patchPath + `
value: ` + patchValue)
return
}
func PatchFile(patchLine string, yfile []byte) (bs []byte){
for _, p := range strings.Split(patchLine, ";") {
ops := CreatePatch(p)
patch, err := DecodePatch(ops)
if err != nil {
log.Fatalf("decoding patch failed: %s", err)
}
bs, err = patch.Apply(yfile)
if err != nil {
log.Fatalf("applying patch failed: %s", err)
}
yfile = bs
}
return
}