-
Notifications
You must be signed in to change notification settings - Fork 359
/
Copy pathcli.go
191 lines (173 loc) · 5.61 KB
/
cli.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package cmd
import (
"errors"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"github.com/fatih/color"
"github.com/hashicorp/logutils"
flags "github.com/jessevdk/go-flags"
"github.com/terraform-linters/tflint/formatter"
"github.com/terraform-linters/tflint/terraform"
"github.com/terraform-linters/tflint/tflint"
)
// Exit codes are int values that represent an exit code for a particular error.
const (
ExitCodeOK int = iota
ExitCodeError
ExitCodeIssuesFound
)
// CLI is the command line object
type CLI struct {
// outStream and errStream are the stdout and stderr
// to write message from the CLI.
outStream, errStream io.Writer
originalWorkingDir string
sources map[string][]byte
// fields for each module
config *tflint.Config
loader *terraform.Loader
formatter *formatter.Formatter
}
// NewCLI returns new CLI initialized by input streams
func NewCLI(outStream io.Writer, errStream io.Writer) (*CLI, error) {
wd, err := os.Getwd()
return &CLI{
outStream: outStream,
errStream: errStream,
originalWorkingDir: wd,
sources: map[string][]byte{},
}, err
}
// Run invokes the CLI with the given arguments.
func (cli *CLI) Run(args []string) int {
var opts Options
parser := flags.NewParser(&opts, flags.HelpFlag)
parser.Usage = "--chdir=DIR/--recursive [OPTIONS]"
parser.UnknownOptionHandler = unknownOptionHandler
// Parse commandline flag
args, err := parser.ParseArgs(args)
// Set up output formatter
cli.formatter = &formatter.Formatter{
Stdout: cli.outStream,
Stderr: cli.errStream,
Format: opts.Format,
}
if opts.Color {
color.NoColor = false
cli.formatter.NoColor = false
}
if opts.NoColor {
color.NoColor = true
cli.formatter.NoColor = true
}
level := os.Getenv("TFLINT_LOG")
log.SetOutput(&logutils.LevelFilter{
Levels: []logutils.LogLevel{"TRACE", "DEBUG", "INFO", "WARN", "ERROR"},
MinLevel: logutils.LogLevel(strings.ToUpper(level)),
Writer: os.Stderr,
})
log.SetFlags(log.Ltime | log.Lshortfile)
if err != nil {
if flagsErr, ok := err.(*flags.Error); ok && flagsErr.Type == flags.ErrHelp {
fmt.Fprintln(cli.outStream, err)
return ExitCodeOK
}
cli.formatter.Print(tflint.Issues{}, fmt.Errorf("Failed to parse CLI options; %w", err), map[string][]byte{})
return ExitCodeError
}
if len(args) > 1 {
cli.formatter.Print(tflint.Issues{}, fmt.Errorf("Command line arguments support was dropped in v0.47. Use --chdir or --filter instead."), map[string][]byte{})
return ExitCodeError
}
switch {
case opts.Version:
return cli.printVersion(opts)
case opts.Init:
return cli.init(opts)
case opts.Langserver:
return cli.startLanguageServer(opts)
case opts.ActAsBundledPlugin:
return cli.actAsBundledPlugin()
default:
return cli.inspect(opts)
}
}
func unknownOptionHandler(option string, arg flags.SplitArgument, args []string) ([]string, error) {
if option == "debug" {
return []string{}, errors.New("`debug` option was removed in v0.8.0. Please set `TFLINT_LOG` environment variables instead")
}
if option == "fast" {
return []string{}, errors.New("`fast` option was removed in v0.9.0. The `aws_instance_invalid_ami` rule is already fast enough")
}
if option == "error-with-issues" {
return []string{}, errors.New("`error-with-issues` option was removed in v0.9.0. The behavior is now default")
}
if option == "quiet" || option == "q" {
return []string{}, errors.New("`quiet` option was removed in v0.11.0. The behavior is now default")
}
if option == "ignore-rule" {
return []string{}, errors.New("`ignore-rule` option was removed in v0.12.0. Please use `--disable-rule` instead")
}
if option == "deep" {
return []string{}, errors.New("`deep` option was removed in v0.23.0. Deep checking is now a feature of the AWS plugin, so please configure the plugin instead")
}
if option == "aws-access-key" || option == "aws-secret-key" || option == "aws-profile" || option == "aws-creds-file" || option == "aws-region" {
return []string{}, fmt.Errorf("`%s` option was removed in v0.23.0. AWS rules are provided by the AWS plugin, so please configure the plugin instead", option)
}
if option == "loglevel" {
return []string{}, errors.New("`loglevel` option was removed in v0.40.0. Please set `TFLINT_LOG` environment variables instead")
}
return []string{}, fmt.Errorf("`%s` is unknown option. Please run `tflint --help`", option)
}
func findWorkingDirs(opts Options) ([]string, error) {
if opts.Recursive && opts.Chdir != "" {
return []string{}, errors.New("cannot use --recursive and --chdir at the same time")
}
workingDirs := []string{}
if opts.Recursive {
// NOTE: The target directory is always the current directory in recursive mode
err := filepath.WalkDir(".", func(path string, d os.DirEntry, err error) error {
if err != nil {
return err
}
if !d.IsDir() {
return nil
}
// hidden directories are skipped
if path != "." && strings.HasPrefix(d.Name(), ".") {
return filepath.SkipDir
}
workingDirs = append(workingDirs, path)
return nil
})
if err != nil {
return []string{}, err
}
} else {
if opts.Chdir == "" {
workingDirs = []string{"."}
} else {
workingDirs = []string{opts.Chdir}
}
}
return workingDirs, nil
}
func (cli *CLI) withinChangedDir(dir string, proc func() error) (err error) {
if dir != "." {
chErr := os.Chdir(dir)
if chErr != nil {
return fmt.Errorf("Failed to switch to a different working directory; %w", chErr)
}
defer func() {
chErr := os.Chdir(cli.originalWorkingDir)
if chErr != nil {
err = fmt.Errorf("Failed to switch to the original working directory; %s; %w", chErr, err)
}
}()
}
return proc()
}