-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfix_source.go
52 lines (42 loc) · 1.24 KB
/
fix_source.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"regexp"
)
var (
fixUnquotedKeys = regexp.MustCompile(`([\s\{])(\$?\w+)(\s?:)`)
fixSingleQuoteStrings = regexp.MustCompile(`'(\$?\w+)'`)
fixTrailingCommas = regexp.MustCompile(`,(\n?\s*[\]|\}])`)
)
func fixSourceFile(filename string) {
b, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: (%s) Could not read source file for fixing: %s\n", filename, err.Error())
os.Exit(2)
}
if backup {
err = ioutil.WriteFile(filename+".backup", b, 0666)
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: (%s) Could not write backup file before fixing source: %s\n", filename, err.Error())
os.Exit(2)
}
}
b = fixSourceErrors(b)
buf := bytes.NewBuffer([]byte{})
err = json.Indent(buf, b, "", " ")
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: (%s) Could not format JSON after fixing source: %s\n", filename, err.Error())
os.Exit(2)
}
ioutil.WriteFile(filename, buf.Bytes(), 0666)
}
func fixSourceErrors(bytes []byte) []byte {
bytes = fixUnquotedKeys.ReplaceAll(bytes, []byte(`$1"$2"$3`))
bytes = fixSingleQuoteStrings.ReplaceAll(bytes, []byte(`"$1"`))
bytes = fixTrailingCommas.ReplaceAll(bytes, []byte(`$1`))
return bytes
}