forked from swaggest/assertjson
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
115 lines (92 loc) · 2.35 KB
/
main.go
File metadata and controls
115 lines (92 loc) · 2.35 KB
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
105
106
107
108
109
110
111
112
113
114
115
// Package main provides a tool to compact JSON.
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"github.com/bool64/dev/version"
"github.com/swaggest/assertjson"
)
// The function is a bit lengthy, but I'm not sure if it would be more approachable divided in several functions.
func main() {
var (
input, output string
length int
prefix, indent string
ver, verbose bool
)
flag.StringVar(&output, "output", "", "Path to output json file, if not specified input file is used.")
flag.IntVar(&length, "len", 100, "Line length limit.")
flag.StringVar(&prefix, "prefix", "", "Set prefix.")
flag.StringVar(&indent, "indent", " ", "Set indent.")
flag.BoolVar(&ver, "version", false, "Print version and exit.")
flag.BoolVar(&verbose, "v", false, "Verbose mode.")
flag.Parse()
if ver {
fmt.Println(version.Info().Version)
return
}
input = flag.Arg(0)
if input == "" {
_, _ = fmt.Fprintln(flag.CommandLine.Output(), "Missing input path argument, use `-` for stdin.")
flag.Usage()
return
}
// Read stdin.
if input == "-" {
var v interface{}
dec := json.NewDecoder(os.Stdin)
err := dec.Decode(&v)
if err != nil {
log.Fatalf("could not process input: %v", err)
}
comp, err := assertjson.MarshalIndentCompact(v, prefix, indent, length)
if err != nil {
log.Fatalf("could not process input: %v", err)
}
fmt.Println(string(comp))
return
}
for _, in := range flag.Args() {
matches, err := filepath.Glob(in)
if err != nil {
log.Fatalf("could not read input: %v", err)
}
for _, m := range matches {
if verbose {
log.Printf("compacting %s.\n", m)
}
//nolint:gosec // Intentional file reading.
orig, err := ioutil.ReadFile(m)
if err != nil {
log.Fatalf("could not read input %s: %v", m, err)
}
comp, err := assertjson.MarshalIndentCompact(json.RawMessage(orig), prefix, indent, length)
if err != nil {
log.Fatalf("could not process input: %v", err)
}
if bytes.Equal(orig, comp) {
if verbose {
log.Printf("already compact, skipping %s\n", m)
}
continue
}
out := output
if out == "" {
out = m
}
if verbose {
log.Printf("writing to %s\n", out)
}
err = ioutil.WriteFile(out, comp, 0o600)
if err != nil {
log.Fatalf("could not write output to %s: %v", out, err)
}
}
}
}