-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
main.go
266 lines (230 loc) · 5.93 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
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
package command
import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"sort"
"strings"
"text/tabwriter"
"github.com/fatih/color"
"github.com/hashicorp/vault/api"
"github.com/hashicorp/vault/command/token"
colorable "github.com/mattn/go-colorable"
"github.com/mitchellh/cli"
)
type VaultUI struct {
cli.Ui
format string
}
// setupEnv parses args and may replace them and sets some env vars to known
// values based on format options
func setupEnv(args []string) (retArgs []string, format string, outputCurlString bool) {
var nextArgFormat bool
for _, arg := range args {
if nextArgFormat {
nextArgFormat = false
format = arg
continue
}
if arg == "--" {
break
}
if len(args) == 1 && (arg == "-v" || arg == "-version" || arg == "--version") {
args = []string{"version"}
break
}
if arg == "-output-curl-string" {
outputCurlString = true
continue
}
// Parse a given flag here, which overrides the env var
if strings.HasPrefix(arg, "--format=") {
format = strings.TrimPrefix(arg, "--format=")
}
if strings.HasPrefix(arg, "-format=") {
format = strings.TrimPrefix(arg, "-format=")
}
// For backwards compat, it could be specified without an equal sign
if arg == "-format" || arg == "--format" {
nextArgFormat = true
}
}
envVaultFormat := os.Getenv(EnvVaultFormat)
// If we did not parse a value, fetch the env var
if format == "" && envVaultFormat != "" {
format = envVaultFormat
}
// Lowercase for consistency
format = strings.ToLower(format)
if format == "" {
format = "table"
}
return args, format, outputCurlString
}
type RunOptions struct {
TokenHelper token.TokenHelper
Stdout io.Writer
Stderr io.Writer
Address string
Client *api.Client
}
func Run(args []string) int {
return RunCustom(args, nil)
}
// RunCustom allows passing in a base command template to pass to other
// commands. Currently, this is only used for setting a custom token helper.
func RunCustom(args []string, runOpts *RunOptions) int {
if runOpts == nil {
runOpts = &RunOptions{}
}
var format string
var outputCurlString bool
args, format, outputCurlString = setupEnv(args)
// Don't use color if disabled
useColor := true
if os.Getenv(EnvVaultCLINoColor) != "" || color.NoColor {
useColor = false
}
if runOpts.Stdout == nil {
runOpts.Stdout = os.Stdout
}
if runOpts.Stderr == nil {
runOpts.Stderr = os.Stderr
}
// Only use colored UI if stdout is a tty, and not disabled
if useColor && format == "table" {
if f, ok := runOpts.Stdout.(*os.File); ok {
runOpts.Stdout = colorable.NewColorable(f)
}
if f, ok := runOpts.Stderr.(*os.File); ok {
runOpts.Stderr = colorable.NewColorable(f)
}
} else {
runOpts.Stdout = colorable.NewNonColorable(runOpts.Stdout)
runOpts.Stderr = colorable.NewNonColorable(runOpts.Stderr)
}
uiErrWriter := runOpts.Stderr
if outputCurlString {
uiErrWriter = ioutil.Discard
}
ui := &VaultUI{
Ui: &cli.ColoredUi{
ErrorColor: cli.UiColorRed,
WarnColor: cli.UiColorYellow,
Ui: &cli.BasicUi{
Reader: bufio.NewReader(os.Stdin),
Writer: runOpts.Stdout,
ErrorWriter: uiErrWriter,
},
},
format: format,
}
serverCmdUi := &VaultUI{
Ui: &cli.ColoredUi{
ErrorColor: cli.UiColorRed,
WarnColor: cli.UiColorYellow,
Ui: &cli.BasicUi{
Reader: bufio.NewReader(os.Stdin),
Writer: runOpts.Stdout,
},
},
format: format,
}
if _, ok := Formatters[format]; !ok {
ui.Error(fmt.Sprintf("Invalid output format: %s", format))
return 1
}
initCommands(ui, serverCmdUi, runOpts)
hiddenCommands := []string{"version"}
cli := &cli.CLI{
Name: "vault",
Args: args,
Commands: Commands,
HelpFunc: groupedHelpFunc(
cli.BasicHelpFunc("vault"),
),
HelpWriter: runOpts.Stderr,
HiddenCommands: hiddenCommands,
Autocomplete: true,
AutocompleteNoDefaultFlags: true,
}
exitCode, err := cli.Run()
if outputCurlString {
if exitCode == 0 {
fmt.Fprint(runOpts.Stderr, "Could not generate cURL command")
return 1
} else {
if api.LastOutputStringError == nil {
if exitCode == 127 {
// Usage, just pass it through
return exitCode
}
fmt.Fprint(runOpts.Stderr, "cURL command not set by API operation; run without -output-curl-string to see the generated error\n")
return exitCode
}
if api.LastOutputStringError.Error() != api.ErrOutputStringRequest {
runOpts.Stdout.Write([]byte(fmt.Sprintf("Error creating request string: %s\n", api.LastOutputStringError.Error())))
return 1
}
runOpts.Stdout.Write([]byte(fmt.Sprintf("%s\n", api.LastOutputStringError.CurlString())))
return 0
}
} else if err != nil {
fmt.Fprintf(runOpts.Stderr, "Error executing CLI: %s\n", err.Error())
return 1
}
return exitCode
}
var commonCommands = []string{
"read",
"write",
"delete",
"list",
"login",
"agent",
"server",
"status",
"unwrap",
}
func groupedHelpFunc(f cli.HelpFunc) cli.HelpFunc {
return func(commands map[string]cli.CommandFactory) string {
var b bytes.Buffer
tw := tabwriter.NewWriter(&b, 0, 2, 6, ' ', 0)
fmt.Fprintf(tw, "Usage: vault <command> [args]\n\n")
fmt.Fprintf(tw, "Common commands:\n")
for _, v := range commonCommands {
printCommand(tw, v, commands[v])
}
otherCommands := make([]string, 0, len(commands))
for k := range commands {
found := false
for _, v := range commonCommands {
if k == v {
found = true
break
}
}
if !found {
otherCommands = append(otherCommands, k)
}
}
sort.Strings(otherCommands)
fmt.Fprintf(tw, "\n")
fmt.Fprintf(tw, "Other commands:\n")
for _, v := range otherCommands {
printCommand(tw, v, commands[v])
}
tw.Flush()
return strings.TrimSpace(b.String())
}
}
func printCommand(w io.Writer, name string, cmdFn cli.CommandFactory) {
cmd, err := cmdFn()
if err != nil {
panic(fmt.Sprintf("failed to load %q command: %s", name, err))
}
fmt.Fprintf(w, " %s\t%s\n", name, cmd.Synopsis())
}