-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
115 lines (91 loc) · 1.9 KB
/
main.go
File metadata and controls
115 lines (91 loc) · 1.9 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
import (
"encoding/json"
"flag"
"fmt"
"io"
"os"
"strconv"
"strings"
)
func main() {
for _, arg := range os.Args {
if arg == "--help" || arg == "-h" {
help()
return
}
}
maxDepthPtr := flag.Int("d", 3, "the maximum depth to parse to")
rootPtr := flag.String("r", "", "root of the blob to analyse. '.' seperated keys")
flag.Parse()
cfg := Config{
maxDepth: *maxDepthPtr,
}
blobBytes := getInput()
var jsonBlob interface{}
err := json.Unmarshal(blobBytes, &jsonBlob)
if err != nil {
panic(err)
}
rootBlob := jsonBlob
rootPath := strings.Split(*rootPtr, ".")
for _, key := range rootPath {
if key == "" {
continue
}
switch typedBlob := rootBlob.(type) {
case []interface{}:
index, err := strconv.Atoi(key)
if err != nil {
panic(fmt.Sprintf("invalid path at key: %s. Expecting an index to an array", key))
}
if index < 0 || index >= len(typedBlob) {
panic(fmt.Sprintf("invalid index at key: %s. Index out of range for array", key))
}
rootBlob = typedBlob[index]
case map[string]interface{}:
childBlob, ok := typedBlob[key]
if !ok {
panic(fmt.Sprintf("invalid key: %s", key))
}
rootBlob = childBlob
}
}
blob := newBlob(cfg, "blob", rootBlob)
blobTree := blob.getTree()
fmt.Println(blobTree)
}
func getInput() []byte {
var blobBytes []byte
isPiped, err := isPipedInput()
if err != nil {
panic(err)
}
if isPiped {
blobBytes, err = io.ReadAll(os.Stdin)
if err != nil {
panic(err)
}
return blobBytes
}
args := os.Args[1:]
if len(args) == 0 {
panic("Filename not set.")
}
filename := args[len(args)-1]
if filename == "" {
panic("Filename not set.")
}
fileBlob, err := os.ReadFile(filename)
if err != nil {
panic(err)
}
return fileBlob
}
func isPipedInput() (bool, error) {
fi, err := os.Stdin.Stat()
if err != nil {
return false, err
}
return (fi.Mode() & os.ModeCharDevice) == 0, nil
}