-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
104 lines (82 loc) · 1.77 KB
/
main.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
100
101
102
103
104
package main
import (
"encoding/json"
"io/ioutil"
"log"
"os"
"regexp"
)
func main() {
if len(os.Args) != 2 {
log.Fatalf("usage: %s filename.json", os.Args[0])
}
filename := os.Args[1]
data, err := readFile(filename)
if err != nil {
log.Fatalf("failed to read file: %v", err)
}
if quickCheckJSON(data) == nil {
log.Printf("already valid json")
return
}
processed, err := cleanTrailingCommas(data)
if err != nil {
log.Fatalf("failed to clean file: %v", err)
}
if err := quickCheckJSON(processed); err != nil {
log.Fatalf("json still invalid: %v\n%s", err, processed)
}
bkpFilename, err := writeBackup(filename, data)
if err != nil {
log.Printf("failed to write backup: %v", err)
}
err = writeFile(filename, processed)
if err != nil {
log.Fatalf("failed to write processed data: %v", err)
}
os.Remove(bkpFilename)
}
func readFile(filename string) ([]byte, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
return ioutil.ReadAll(f)
}
func writeFile(filename string, data []byte) error {
f, err := os.Create(filename)
if err != nil {
return err
}
_, err = f.Write(data)
if err != nil {
f.Close()
return err
}
return f.Close()
}
func writeBackup(filename string, data []byte) (string, error) {
bkpFilename := filename + ".bkp"
f, err := os.Create(bkpFilename)
if err != nil {
return "", err
}
_, err = f.Write(data)
if err != nil {
f.Close()
return "", err
}
return bkpFilename, f.Close()
}
func quickCheckJSON(data []byte) error {
var stuff interface{}
return json.Unmarshal(data, &stuff)
}
func cleanTrailingCommas(data []byte) ([]byte, error) {
re, err := regexp.Compile(`(?ms),(\s*[}\]])`)
if err != nil {
return nil, err
}
return re.ReplaceAll(data, []byte("$1")), nil
}