-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprettyjson.go
88 lines (80 loc) · 1.89 KB
/
prettyjson.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
/*
prettyjson.go
author: TimH96
*/
// Shell tool to pretty print json.
package main
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"os"
"strings"
"github.com/akamensky/argparse"
)
const VERSION = "1.0"
// Command line arguments for script
type CLArgs struct {
Indent int
Version bool
}
// Read piped stdin and return resulting string.
// Inspired by: https://flaviocopes.com/go-shell-pipes/
func readStdin() (out []byte, err error) {
info, err := os.Stdin.Stat()
// throw piped error
if err != nil {
panic(err)
}
// return error when no piped stdin
if (info.Mode() & os.ModeNamedPipe) == 0 {
return []byte{}, errors.New("No piped input for prettyjson, use prettyjson --help for usage information")
}
// read bytestream
reader := bufio.NewReader(os.Stdin)
raw, _, err := reader.ReadLine()
return raw, err
}
// Parses command line arguments and returns them.
func getArgs() (args CLArgs, err error) {
// define parse
parser := argparse.NewParser("prettyjson", "Pretty prints provided json string to stdout")
indent := parser.Int("i", "indent", &argparse.Options{Required: false, Help: "Indent per recursion level", Default: 4})
version := parser.Flag("v", "version", &argparse.Options{Required: false, Help: "Get script version"})
err = parser.Parse(os.Args)
// return resulting struct
return CLArgs{
Indent: *indent,
Version: *version,
}, err
}
// Script entrypoint.
func main() {
// get args
args, err := getArgs()
if err != nil {
fmt.Print(err)
return
}
if args.Version == true {
fmt.Print("prettyjson version " + VERSION)
return
}
// get piped input
input, err := readStdin()
if err != nil {
fmt.Print(err)
return
}
// prettify json string
var prettyJSON bytes.Buffer
err = json.Indent(&prettyJSON, input, "", strings.Repeat(" ", args.Indent))
if err != nil {
fmt.Print(err)
return
}
// print result
fmt.Print(string(prettyJSON.Bytes()))
}