-
Notifications
You must be signed in to change notification settings - Fork 244
/
appcmd.go
176 lines (160 loc) · 5.13 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
// Copyright 2020 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"
"strings"
"github.com/bufbuild/buf/internal/pkg/app"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
// Command is a command.
type Command struct {
// Use is the one-line usage message.
// Required.
Use 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 a newline.
// 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
// BindFlags allows binding of flags on build.
BindFlags func(*pflag.FlagSet)
// 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
}
// 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, version string) {
app.Main(ctx, newRunFunc(command, version))
}
// Run runs the application using the container.
func Run(ctx context.Context, container app.Container, command *Command, version string) error {
return app.Run(ctx, container, newRunFunc(command, version))
}
// 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, version string) func(context.Context, app.Container) error {
return func(ctx context.Context, container app.Container) error {
return run(ctx, container, command, version)
}
}
func run(
ctx context.Context,
container app.Container,
command *Command,
version string,
) error {
var runErr error
cobraCommand, err := commandToCobra(ctx, container, command, &runErr)
if err != nil {
return err
}
cobraCommand.SetVersionTemplate("{{.Version}}\n")
cobraCommand.Version = version
// If the root command is not the only command, add hidden bash-completion
// and zsh-completion commands.
if len(command.SubCommands) > 0 {
cobraCommand.AddCommand(&cobra.Command{
Use: "bash-completion",
Args: cobra.NoArgs,
Hidden: true,
Run: func(*cobra.Command, []string) {
runErr = cobraCommand.GenBashCompletion(container.Stdout())
},
})
cobraCommand.AddCommand(&cobra.Command{
Use: "zsh-completion",
Args: cobra.NoArgs,
Hidden: true,
Run: func(*cobra.Command, []string) {
runErr = cobraCommand.GenZshCompletion(container.Stdout())
},
})
}
cobraCommand.SetArgs(app.Args(container)[1:])
cobraCommand.SetOut(container.Stderr())
cobraCommand.SetErr(container.Stderr())
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,
Args: command.Args,
Short: strings.TrimSpace(command.Short),
}
if command.Long != "" {
cobraCommand.Long = cobraCommand.Short + "\n" + strings.TrimSpace(command.Long)
}
if command.BindFlags != nil {
command.BindFlags(cobraCommand.PersistentFlags())
}
if command.Run != nil {
cobraCommand.Run = func(_ *cobra.Command, args []string) {
*runErrAddr = command.Run(ctx, app.NewContainerForArgs(container, args...))
}
}
for _, subCommand := range command.SubCommands {
subCobraCommand, err := commandToCobra(ctx, container, subCommand, runErrAddr)
if err != nil {
return nil, err
}
cobraCommand.AddCommand(subCobraCommand)
}
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("cannot set both Command.Run and Command.SubCommands")
}
return nil
}