-
Notifications
You must be signed in to change notification settings - Fork 15
/
main.go
122 lines (98 loc) · 2.38 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package main
import (
"fmt"
"io"
"log"
"os"
"sync"
"syscall"
"github.com/hashicorp/logutils"
"github.com/minamijoyo/tfschema/command"
"github.com/mitchellh/cli"
"github.com/mitchellh/panicwrap"
)
// Version is a version number.
var version = "0.7.9"
// ui is a user interface which is a global variable for mocking.
var ui cli.Ui
func init() {
ui = &cli.BasicUi{
Writer: os.Stdout,
}
}
func main() {
// abuse panicwrap to discard noisy debug log from go-plugin
var wrapConfig panicwrap.WrapConfig
if !panicwrap.Wrapped(&wrapConfig) {
doneCh := make(chan struct{})
outR, outW := io.Pipe()
go copyOutput(outR, doneCh)
wrapConfig.Handler = panicHandler
wrapConfig.Writer = logOutput()
wrapConfig.Stdout = outW
wrapConfig.IgnoreSignals = []os.Signal{os.Interrupt}
wrapConfig.ForwardSignals = []os.Signal{syscall.SIGTERM}
exitStatus, err := panicwrap.Wrap(&wrapConfig)
if err != nil {
panic(err)
}
if exitStatus >= 0 {
outW.Close()
<-doneCh
os.Exit(exitStatus)
}
}
os.Exit(wrappedMain())
}
func wrappedMain() int {
log.SetOutput(logOutput())
log.Printf("[INFO] CLI args: %#v", os.Args)
commands := command.InitCommands(ui)
args := os.Args[1:]
c := &cli.CLI{
Name: "tfschema",
Version: version,
Args: args,
Commands: commands,
HelpWriter: os.Stdout,
Autocomplete: true,
AutocompleteInstall: "install-autocomplete",
AutocompleteUninstall: "uninstall-autocomplete",
}
exitStatus, err := c.Run()
if err != nil {
ui.Error(fmt.Sprintf("Failed to execute CLI: %s", err))
}
return exitStatus
}
func panicHandler(output string) {
ui.Error(fmt.Sprintf("The child panicked:\n\n%s\n", output))
os.Exit(1)
}
func logOutput() io.Writer {
levels := []logutils.LogLevel{"TRACE", "DEBUG", "INFO", "WARN", "ERROR"}
minLevel := os.Getenv("TFSCHEMA_LOG")
// default log writer is null device.
writer := io.Discard
if minLevel != "" {
writer = os.Stderr
}
filter := &logutils.LevelFilter{
Levels: levels,
MinLevel: logutils.LogLevel(minLevel),
Writer: writer,
}
return filter
}
func copyOutput(r io.Reader, doneCh chan<- struct{}) {
defer close(doneCh)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
// nolint: errcheck
// We should check for errors here, but haven't done yet.
io.Copy(os.Stdout, r)
}()
wg.Wait()
}