-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathjsonfmt.go
82 lines (69 loc) · 1.23 KB
/
jsonfmt.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
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"os"
)
var (
write = flag.Bool("w", false, "write to file")
pfx = flag.String("p", "", "prefix")
sep = flag.String("s", "\t", "separator")
)
func main() {
log.SetFlags(0)
log.SetPrefix("jsonfmt: ")
flag.Usage = usage
flag.Parse()
if flag.NArg() == 0 {
err := format(os.Stdin, os.Stdout, *pfx, *sep)
ck(err)
return
}
r, err := os.Open(flag.Arg(0))
if err != nil {
if *write {
r = os.Stdin
} else {
log.Fatal(err)
}
}
w := new(bytes.Buffer)
err = format(r, w, *pfx, *sep)
ck(err)
if !*write {
os.Stdout.Write(w.Bytes())
} else {
err = os.WriteFile(flag.Arg(0), w.Bytes(), 0644)
ck(err)
}
}
func usage() {
fmt.Fprintln(os.Stderr, "usage: [options] <file>")
flag.PrintDefaults()
os.Exit(1)
}
func format(r io.Reader, w io.Writer, pfx, sep string) error {
b, err := io.ReadAll(r)
if err != nil {
return err
}
p := new(bytes.Buffer)
err = json.Indent(p, b, pfx, sep)
if err != nil {
return err
}
_, err = w.Write(p.Bytes())
if err != nil {
return err
}
return nil
}
func ck(err error) {
if err != nil {
log.Fatal(err)
}
}