This repository has been archived by the owner on Aug 14, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
update_json.go
99 lines (76 loc) · 1.83 KB
/
update_json.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package ver
import (
"bytes"
jsonImpl "encoding/json"
"fmt"
"io/ioutil"
"github.com/Jeffail/gabs"
log "github.com/Sirupsen/logrus"
)
type UpdateActions map[string]string
func UpdateJsonFile(filePath string, updates UpdateActions, vi *VersionInformation, indent string) error {
// parse the json file
json, err := gabs.ParseJSONFile(filePath)
if err != nil {
log.Errorf("Failed to parse %v file: %v", filePath, err)
return err
}
// apply updates
for _, u := range orderUpdates(updates) {
update := u.Update
path := u.Path
switch update {
case "$delete$":
if json.ExistsP(path) {
err = json.DeleteP(path)
if err != nil {
return err
}
log.Debugf("Deleted element: %v", path)
}
case "$null$":
log.Debugf("Updating element %v: null", path)
_, err = json.SetP(nil, path)
if err != nil {
return err
}
default:
// render value
newValue, err := RenderTemplate(update, path, vi)
if err != nil {
return err
}
// parse the value
log.Debugf("Updating element %v: %v", path, newValue)
var newValueObj interface{}
if true {
newValueBuf := bytes.NewBufferString(newValue)
decoder := jsonImpl.NewDecoder(newValueBuf)
token, err := decoder.Token()
if err != nil {
log.Errorf("Failed to parse JSON value '%v': %v", newValue, err)
return err
}
switch v := token.(type) {
case jsonImpl.Delim:
return fmt.Errorf("Failed to parse JSON value '%v': got delimiter", newValue)
default:
newValueObj = v
}
}
// update the value
_, err = json.SetP(newValueObj, path)
if err != nil {
return err
}
}
}
// write back the file
var newContent []byte
if indent == "" {
newContent = json.Bytes()
} else {
newContent = json.BytesIndent("", indent)
}
return ioutil.WriteFile(filePath, newContent, 0644)
}