/
root.go
104 lines (86 loc) · 1.91 KB
/
root.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
92
93
94
95
96
97
98
99
100
101
102
103
104
package cmd
import (
"encoding/json"
"errors"
"io/ioutil"
"os"
"github.com/spf13/cobra"
)
var (
hcl bool
tfstate bool
file []byte
path string
rootCmd = &cobra.Command{
Use: "inframap",
Short: "Reads the TFState or HCL to generate a Graphical view",
Long: "Reads the TFState or HCL to generate a Graphical view with Nodes and Edges.",
}
)
// Execute executes the root command.
func Execute() error {
return rootCmd.Execute()
}
// preRunFile checks where the input is, ARGS or STDIN
// also checks if --hcl or --tfstate are setted as one of
// them is required
func preRunFile(cmd *cobra.Command, args []string) error {
var err error
if len(args) == 1 {
path = args[0]
fi, err := os.Stat(path)
if err != nil {
return err
}
if !fi.IsDir() {
file, err = ioutil.ReadFile(path)
if err != nil {
return err
}
} else {
// Only HCL can used with dirs
hcl = true
tfstate = false
}
} else {
fi, err := os.Stdin.Stat()
if err != nil {
return err
}
if fi.Mode()&os.ModeNamedPipe == 0 {
return errors.New("STDIN is empty")
}
file, err = ioutil.ReadAll(os.Stdin)
if err != nil {
return err
}
}
setGenerateType(file)
return err
}
// setGenerateType will try to guess the file content by first parsing it in JSON
// and if it fails fallback to HCL.
// If any of the flags --hcl or --tfstate are set it'll do nothing and use those
// directly as they are setted by the user
func setGenerateType(b []byte) {
if hcl || tfstate {
return
}
var aux map[string]interface{}
if err := json.Unmarshal(b, &aux); err != nil {
hcl = true
tfstate = false
} else {
hcl = false
tfstate = true
}
}
func init() {
rootCmd.AddCommand(
generateCmd,
pruneCmd,
versionCmd,
)
rootCmd.PersistentFlags().BoolVar(&hcl, "hcl", false, "Forces to use HCL parser")
rootCmd.PersistentFlags().BoolVar(&tfstate, "tfstate", false, "Forces to use TFState parser")
}