-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
77 lines (64 loc) · 1.24 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
// Python json.tool function implementation.
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
)
var (
override = flag.Bool("w", false, "write result to (source) file instead of stdout")
)
func visitFile(filename string, f os.FileInfo, err error) error {
if err == nil && strings.HasSuffix(f.Name(), ".json") {
err = processFile(filename)
}
if err != nil && !os.IsNotExist(err) {
log.Println(err)
}
return nil
}
func walkDir(filename string) {
_ = filepath.Walk(filename, visitFile)
}
func processFile(filename string) (err error) {
data, err := ioutil.ReadFile(filename)
if err != nil {
return
}
m := []interface{}{}
err = json.Unmarshal(data, &m)
if err != nil {
return
}
dataFmt, _ := json.MarshalIndent(m, "", " ")
if *override {
err = ioutil.WriteFile(filename, dataFmt, 0755)
} else {
fmt.Println(string(dataFmt))
}
return
}
func main() {
flag.Parse()
if len(os.Args) == 1 {
flag.Usage()
}
for i := 0; i < flag.NArg(); i++ {
path := flag.Arg(i)
switch dir, err := os.Stat(path); {
case err != nil:
log.Println(err)
case dir.IsDir():
walkDir(path)
default:
if err := processFile(path); err != nil {
log.Println(err)
}
}
}
}