-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
91 lines (86 loc) · 2.04 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
// The rjson command reads rjson or JSON from its standard input and
// writes rjson (or JSON if the "-j" flag is given) to its standard output.
// The "-indent" flag specifies an indent string; if this is empty,
// a compact output will be used; otherwise the result will be
// pretty-printed.
package main
import (
"bufio"
"bytes"
"encoding/json"
"flag"
"fmt"
"io"
"github.com/rogpeppe/rjson"
"os"
)
var jsonOut = flag.Bool("j", false, "produce JSON output")
var indent = flag.String("indent", "\t", "indentation string; empty implies compact output")
func main() {
flag.Parse()
if flag.NArg() > 0 {
fmt.Fprintf(os.Stderr, "rjson reads from stdin only")
os.Exit(2)
}
var marshal func(interface{}) ([]byte, error)
if *jsonOut {
if *indent == "" {
marshal = json.Marshal
} else {
marshal = func(v interface{}) ([]byte, error) {
return json.MarshalIndent(v, "", *indent)
}
}
} else {
if *indent == "" {
marshal = func(v interface{}) ([]byte, error) {
data, err := rjson.MarshalIndent(v, "", "")
if err != nil {
return data, err
}
// TODO: use Compact only when it compacts
// identifiers too.
var b bytes.Buffer
if err := rjson.Compact(&b, data); err != nil {
return nil, err
}
return b.Bytes(), nil
}
} else {
marshal = func(v interface{}) ([]byte, error) {
return rjson.MarshalIndent(v, "", *indent)
}
}
}
d := rjson.NewDecoder(os.Stdin)
d.UseNumber()
w := bufio.NewWriter(os.Stdout)
err := stream(w, d, marshal)
if err != nil {
fmt.Fprintf(os.Stderr, "rjson: %v", err)
os.Exit(1)
}
}
func stream(w *bufio.Writer, d *rjson.Decoder, marshal func(v interface{}) ([]byte, error)) error {
var v interface{}
defer w.Flush()
for {
err := d.Decode(&v)
if err == io.EOF {
break
}
if err != nil {
return fmt.Errorf("decode: %v", err)
}
data, err := marshal(v)
if err != nil {
return fmt.Errorf("marshal: %v", err)
}
if _, err := w.Write(data); err != nil {
return fmt.Errorf("write: %v", err)
}
v = nil
w.WriteByte('\n')
}
return nil
}