-
Notifications
You must be signed in to change notification settings - Fork 259
/
appcmd.go
363 lines (343 loc) · 12.2 KB
/
appcmd.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
// Copyright 2020-2022 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package appcmd contains helper functionality for applications using commands.
package appcmd
import (
"context"
"errors"
"fmt"
"strings"
"github.com/bufbuild/buf/private/pkg/app"
"github.com/spf13/cobra"
"github.com/spf13/cobra/doc"
"github.com/spf13/pflag"
)
// Command is a command.
type Command struct {
// Use is the one-line usage message.
// Required.
Use string
// Aliases are aliases that can be used instead of the first word in Use.
Aliases []string
// Short is the short message shown in the 'help' output.
// Required if Long is set.
Short string
// Long is the long message shown in the 'help <this-command>' output.
// The Short field will be prepended to the Long field with two newlines.
// Must be unset if short is unset.
Long string
// Args are the expected arguments.
//
// TODO: make specific types for appcmd to limit what can be done.
Args cobra.PositionalArgs
// Deprecated says to print this deprecation string.
Deprecated string
// Hidden says to hide this command.
Hidden bool
// BindFlags allows binding of flags on build.
BindFlags func(*pflag.FlagSet)
// BindPersistentFlags allows binding of flags on build.
BindPersistentFlags func(*pflag.FlagSet)
// NormalizeFlag allows for normalization of flag names.
NormalizeFlag func(*pflag.FlagSet, string) string
// NormalizePersistentFlag allows for normalization of flag names.
NormalizePersistentFlag func(*pflag.FlagSet, string) string
// Run is the command to run.
// Required if there are no sub-commands.
// Must be unset if there are sub-commands.
Run func(context.Context, app.Container) error
// SubCommands are the sub-commands. Optional.
// Must be unset if there is a run function.
SubCommands []*Command
// Version the version of the command.
//
// If this is specified, a flag --version will be added to the command
// that precedes all other functionality, and which prints the version
// to stdout.
Version string
}
// NewInvalidArgumentError creates a new invalidArgumentError, indicating that
// the error was caused by argument validation. This causes us to print the usage
// help text for the command that it is returned from.
func NewInvalidArgumentError(message string) error {
return newInvalidArgumentError(message)
}
// NewInvalidArgumentErrorf creates a new InvalidArgumentError, indicating that
// the error was caused by argument validation. This causes us to print the usage
// help text for the command that it is returned from.
func NewInvalidArgumentErrorf(format string, args ...interface{}) error {
return NewInvalidArgumentError(fmt.Sprintf(format, args...))
}
// Main runs the application using the OS container and calling os.Exit on the return value of Run.
func Main(ctx context.Context, command *Command) {
app.Main(ctx, newRunFunc(command))
}
// Run runs the application using the container.
func Run(ctx context.Context, container app.Container, command *Command) error {
return app.Run(ctx, container, newRunFunc(command))
}
// BindMultiple is a convenience function for binding multiple flag functions.
func BindMultiple(bindFuncs ...func(*pflag.FlagSet)) func(*pflag.FlagSet) {
return func(flagSet *pflag.FlagSet) {
for _, bindFunc := range bindFuncs {
bindFunc(flagSet)
}
}
}
func newRunFunc(command *Command) func(context.Context, app.Container) error {
return func(ctx context.Context, container app.Container) error {
return run(ctx, container, command)
}
}
func run(
ctx context.Context,
container app.Container,
command *Command,
) error {
var runErr error
cobraCommand, err := commandToCobra(ctx, container, command, &runErr)
if err != nil {
return err
}
// Cobra 1.2.0 introduced default completion commands under
// "<binary> completion <bash/zsh/fish/powershell>"". Since we have
// our own completion commands, disable the generation of the default
// commands.
cobraCommand.CompletionOptions.DisableDefaultCmd = true
// If the root command is not the only command, add a hidden manpages command
// and a visible completion command.
if len(command.SubCommands) > 0 {
shellCobraCommand, err := commandToCobra(
ctx,
container,
&Command{
Use: "completion",
Short: "Generate auto-completion scripts for commonly used shells.",
SubCommands: []*Command{
{
Use: "bash",
Short: "Generate auto-completion scripts for bash.",
Args: cobra.NoArgs,
Run: func(ctx context.Context, container app.Container) error {
return cobraCommand.GenBashCompletion(container.Stdout())
},
},
{
Use: "fish",
Short: "Generate auto-completion scripts for fish.",
Args: cobra.NoArgs,
Run: func(ctx context.Context, container app.Container) error {
return cobraCommand.GenFishCompletion(container.Stdout(), true)
},
},
{
Use: "powershell",
Short: "Generate auto-completion scripts for powershell.",
Args: cobra.NoArgs,
Run: func(ctx context.Context, container app.Container) error {
return cobraCommand.GenPowerShellCompletion(container.Stdout())
},
},
{
Use: "zsh",
Short: "Generate auto-completion scripts for zsh.",
Args: cobra.NoArgs,
Run: func(ctx context.Context, container app.Container) error {
return cobraCommand.GenZshCompletion(container.Stdout())
},
},
},
},
&runErr,
)
if err != nil {
return err
}
cobraCommand.AddCommand(shellCobraCommand)
manpagesCobraCommand, err := commandToCobra(
ctx,
container,
&Command{
Use: "manpages",
Args: cobra.ExactArgs(1),
Hidden: true,
Run: func(ctx context.Context, container app.Container) error {
return doc.GenManTree(
cobraCommand,
&doc.GenManHeader{
Title: "Buf",
Section: "1",
},
container.Arg(0),
)
},
},
&runErr,
)
if err != nil {
return err
}
cobraCommand.AddCommand(manpagesCobraCommand)
}
cobraCommand.SetOut(container.Stderr())
args := app.Args(container)[1:]
// cobra will implicitly create __complete and __completeNoDesc subcommands
// https://github.com/spf13/cobra/blob/4590150168e93f4b017c6e33469e26590ba839df/completions.go#L14-L17
// at the very last possible point, to enable them to be overridden. Unfortunately
// the creation of the subcommands uses hidden helper methods (unlike the automatic help command support).
// See https://github.com/spf13/cobra/blob/4590150168e93f4b017c6e33469e26590ba839df/completions.go#L134.
//
// Additionally, the automatically generated commands inherit the output of the root command,
// which we are ensuring is always stderr.
// https://github.com/spf13/cobra/blob/4590150168e93f4b017c6e33469e26590ba839df/completions.go#L175
//
// bash completion has much more detailed code generation and doesn't rely on the __completion command
// in most cases, the zsh and fish completion implementation however exclusively rely on these commands.
// Those completion implementations send stderr to /dev/null
// https://github.com/spf13/cobra/blob/4590150168e93f4b017c6e33469e26590ba839df/zsh_completions.go#L135
// and the automatically generated __complete command sends extra data to /dev/null so we cannot
// work around this by minimally changing the code generation commands, we would have to rewrite the
// __completion command which is much more complicated.
//
// Instead of all that, we can peek at the positionals and if the sub command starts with __complete
// we sets its output to stdout. This would mean that we cannot add a "real" sub-command that starts with
// __complete _and_ has its output set to stderr. This shouldn't ever be a problem.
//
// SetOut sets the output location for usage, help, and version messages by default.
if len(args) > 0 && strings.HasPrefix(args[0], "__complete") {
cobraCommand.SetOut(container.Stdout())
}
cobraCommand.SetArgs(args)
// SetErr sets the output location for error messages.
cobraCommand.SetErr(container.Stderr())
cobraCommand.SetIn(container.Stdin())
if err := cobraCommand.Execute(); err != nil {
return err
}
return runErr
}
func commandToCobra(
ctx context.Context,
container app.Container,
command *Command,
runErrAddr *error,
) (*cobra.Command, error) {
if err := commandValidate(command); err != nil {
return nil, err
}
cobraCommand := &cobra.Command{
Use: command.Use,
Aliases: command.Aliases,
Args: command.Args,
Deprecated: command.Deprecated,
Hidden: command.Hidden,
Short: strings.TrimSpace(command.Short),
}
cobraCommand.SetHelpFunc(
func(c *cobra.Command, _ []string) {
if err := tmpl(container.Stdout(), c.HelpTemplate(), c); err != nil {
c.PrintErrln(err)
}
},
)
if command.Long != "" {
cobraCommand.Long = cobraCommand.Short + "\n\n" + strings.TrimSpace(command.Long)
}
if command.BindFlags != nil {
command.BindFlags(cobraCommand.Flags())
}
if command.BindPersistentFlags != nil {
command.BindPersistentFlags(cobraCommand.PersistentFlags())
}
if command.NormalizeFlag != nil {
cobraCommand.Flags().SetNormalizeFunc(normalizeFunc(command.NormalizeFlag))
}
if command.NormalizePersistentFlag != nil {
cobraCommand.PersistentFlags().SetNormalizeFunc(normalizeFunc(command.NormalizePersistentFlag))
}
if command.Run != nil {
cobraCommand.Run = func(_ *cobra.Command, args []string) {
runErr := command.Run(ctx, app.NewContainerForArgs(container, args...))
if asErr := (&invalidArgumentError{}); errors.As(runErr, &asErr) {
// Print usage for failing command if an args error is returned.
// This has to be done at this level since the usage must relate
// to the command executed.
printUsage(container, cobraCommand.UsageString())
}
*runErrAddr = runErr
}
}
if len(command.SubCommands) > 0 {
// command.Run will not be set per validation
cobraCommand.Run = func(cmd *cobra.Command, args []string) {
printUsage(container, cobraCommand.UsageString())
if len(args) == 0 {
*runErrAddr = errors.New("Sub-command required.")
} else {
*runErrAddr = fmt.Errorf("Unknown sub-command: %s", strings.Join(args, " "))
}
}
for _, subCommand := range command.SubCommands {
subCobraCommand, err := commandToCobra(ctx, container, subCommand, runErrAddr)
if err != nil {
return nil, err
}
cobraCommand.AddCommand(subCobraCommand)
}
}
if command.Version != "" {
doVersion := false
oldRun := cobraCommand.Run
cobraCommand.Flags().BoolVar(
&doVersion,
"version",
false,
"Print the version.",
)
cobraCommand.Run = func(cmd *cobra.Command, args []string) {
if doVersion {
_, err := container.Stdout().Write([]byte(command.Version + "\n"))
*runErrAddr = err
return
}
oldRun(cmd, args)
}
}
// appcommand prints errors, disable to prevent duplicates.
cobraCommand.SilenceErrors = true
return cobraCommand, nil
}
func commandValidate(command *Command) error {
if command.Use == "" {
return errors.New("must set Command.Use")
}
if command.Long != "" && command.Short == "" {
return errors.New("must set Command.Short if Command.Long is set")
}
if command.Run != nil && len(command.SubCommands) > 0 {
return errors.New("cannot set both Command.Run and Command.SubCommands")
}
if command.Run == nil && len(command.SubCommands) == 0 {
return errors.New("must set one of Command.Run and Command.SubCommands")
}
return nil
}
func normalizeFunc(f func(*pflag.FlagSet, string) string) func(*pflag.FlagSet, string) pflag.NormalizedName {
return func(flagSet *pflag.FlagSet, name string) pflag.NormalizedName {
return pflag.NormalizedName(f(flagSet, name))
}
}
func printUsage(container app.StderrContainer, usage string) {
_, _ = container.Stderr().Write([]byte(usage + "\n"))
}