-
Notifications
You must be signed in to change notification settings - Fork 263
/
Copy pathroot.go
416 lines (361 loc) · 12.8 KB
/
root.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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
// Copyright © 2018 The Knative Authors
//
// 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 core
import (
"flag"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"golang.org/x/crypto/ssh/terminal"
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
_ "k8s.io/client-go/plugin/pkg/client/auth/oidc"
"knative.dev/client/pkg/kn/commands"
"knative.dev/client/pkg/kn/commands/completion"
cmdflags "knative.dev/client/pkg/kn/commands/flags"
"knative.dev/client/pkg/kn/commands/plugin"
"knative.dev/client/pkg/kn/commands/revision"
"knative.dev/client/pkg/kn/commands/route"
"knative.dev/client/pkg/kn/commands/service"
"knative.dev/client/pkg/kn/commands/source"
"knative.dev/client/pkg/kn/commands/trigger"
"knative.dev/client/pkg/kn/commands/version"
"knative.dev/client/pkg/kn/flags"
)
// NewDefaultKnCommand creates the default `kn` command with a default plugin handler
func NewDefaultKnCommand() (*cobra.Command, error) {
rootCmd := NewKnCommand()
// Needed since otherwise --plugins-dir and --lookup-plugins
// will not be accounted for since the plugin is not a Cobra command
// and will not be parsed
pluginsDir, lookupPluginsInPath, err := extractKnPluginFlags(os.Args)
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
return &cobra.Command{}, fmt.Errorf("%v", err)
}
pluginHandler := plugin.NewDefaultPluginHandler(plugin.ValidPluginFilenamePrefixes,
pluginsDir, lookupPluginsInPath)
return NewDefaultKnCommandWithArgs(rootCmd, pluginHandler,
os.Args, os.Stdin,
os.Stdout, os.Stderr)
}
// NewDefaultKnCommandWithArgs creates the `kn` command with arguments
func NewDefaultKnCommandWithArgs(rootCmd *cobra.Command,
pluginHandler plugin.PluginHandler,
args []string,
in io.Reader,
out,
errOut io.Writer) (*cobra.Command, error) {
if pluginHandler == nil {
return rootCmd, nil
}
// process possible plugin call
if len(args) > 1 {
cmdPathPieces := args[1:]
cmdPathPieces = removeKnPluginFlags(cmdPathPieces) // Plugin does not need these flags
// Return fast if -h or --help is in path pieces
if helpOptionsPresent(cmdPathPieces) {
return rootCmd, nil
}
// only look for suitable extension executables if
// the specified command does not already exist
foundCmd, innerArgs, err := rootCmd.Find(cmdPathPieces)
if err != nil {
err := plugin.HandlePluginCommand(pluginHandler, cmdPathPieces)
if err != nil {
return &cobra.Command{}, fmt.Errorf("unknown command '%s' \nRun 'kn --help' for usage", args[1])
}
}
// when the call is on a leaf command, with sub commands
if foundCmd.HasSubCommands() {
// look for case of a plugin's command that shadows
// an existing command's subcommand
if len(innerArgs) > 0 {
cmdName := innerArgs[0]
for _, subcommand := range foundCmd.Commands() {
if subcommand.Name() == cmdName {
return &cobra.Command{}, fmt.Errorf("Error: sub-command '%s' for '%s' already exists.\nRun 'kn --help' for usage.\n", cmdName, foundCmd.Name())
}
}
// try to handle a plugin for a command extending a core comand group
err = plugin.HandlePluginCommand(pluginHandler, cmdPathPieces)
if err != nil {
return &cobra.Command{}, fmt.Errorf("Error: unknown sub-command '%s' for command '%s'\nRun 'kn --help' for usage.\n", cmdName, foundCmd.Name())
}
} else {
_, _, err := rootCmd.Find(innerArgs)
if err != nil {
return &cobra.Command{}, fmt.Errorf(showSubcommands(foundCmd, cmdPathPieces, innerArgs[0]))
}
}
}
}
return rootCmd, nil
}
// NewKnCommand creates the rootCmd which is the base command when called without any subcommands
func NewKnCommand(params ...commands.KnParams) *cobra.Command {
var p *commands.KnParams
if len(params) == 0 {
p = &commands.KnParams{}
} else if len(params) == 1 {
p = ¶ms[0]
} else {
panic("Too many params objects to NewKnCommand")
}
p.Initialize()
rootCmd := &cobra.Command{
Use: "kn",
Short: "Knative client",
Long: `Manage your Knative building blocks:
* Serving: Manage your services and release new software to them.
* Eventing: Manage event subscriptions and channels. Connect up event sources.`,
// Disable docs header
DisableAutoGenTag: true,
// Affects children as well
SilenceUsage: true,
// Prevents Cobra from dealing with errors as we deal with them in main.go
SilenceErrors: true,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
err := initConfigFlags()
if err != nil {
return err
}
return flags.ReconcileBoolFlags(cmd.Flags())
},
}
if p.Output != nil {
rootCmd.SetOutput(p.Output)
}
// Persistent flags
rootCmd.PersistentFlags().StringVar(&commands.CfgFile, "config", "", "kn config file (default is "+
filepath.Join(commands.Cfg.DefaultConfigDir, "config.yaml")+")")
rootCmd.PersistentFlags().StringVar(&p.KubeCfgPath, "kubeconfig", "", "kubectl config file (default is ~/.kube/config)")
flags.AddBothBoolFlags(rootCmd.PersistentFlags(), &p.LogHTTP, "log-http", "", false, "log http traffic")
plugin.AddPluginFlags(rootCmd)
plugin.BindPluginsFlagToViper(rootCmd)
// root child commands
rootCmd.AddCommand(service.NewServiceCommand(p))
rootCmd.AddCommand(revision.NewRevisionCommand(p))
rootCmd.AddCommand(plugin.NewPluginCommand(p))
rootCmd.AddCommand(route.NewRouteCommand(p))
rootCmd.AddCommand(completion.NewCompletionCommand(p))
rootCmd.AddCommand(version.NewVersionCommand(p))
rootCmd.AddCommand(source.NewSourceCommand(p))
rootCmd.AddCommand(trigger.NewTriggerCommand(p))
// Initialize default `help` cmd early to prevent unknown command errors
rootCmd.InitDefaultHelpCmd()
// Deal with empty and unknown sub command groups
EmptyAndUnknownSubCommands(rootCmd)
// Wrap usage.
w, err := width()
if err == nil {
newUsage := strings.ReplaceAll(rootCmd.UsageTemplate(), "FlagUsages ",
fmt.Sprintf("FlagUsagesWrapped %d ", w))
rootCmd.SetUsageTemplate(newUsage)
}
// For glog parse error.
flag.CommandLine.Parse([]string{})
// Set all current core commands to plugin.CoreCommandNames
for _, cmd := range rootCmd.Commands() {
plugin.CoreCommandNames = append(plugin.CoreCommandNames, cmd.Name())
}
return rootCmd
}
// InitializeConfig initializes the kubeconfig used by all commands
func InitializeConfig() {
cobra.OnInitialize(initConfig)
}
// EmptyAndUnknownSubCommands adds a RunE to all commands that are groups to
// deal with errors when called with empty or unknown sub command
func EmptyAndUnknownSubCommands(cmd *cobra.Command) {
for _, childCmd := range cmd.Commands() {
if childCmd.HasSubCommands() && childCmd.RunE == nil {
childCmd.RunE = func(aCmd *cobra.Command, args []string) error {
aCmd.Help()
if len(args) == 0 {
return fmt.Errorf("please provide a valid sub-command for \"kn %s\"", aCmd.Name())
}
return fmt.Errorf("unknown sub-command \"%s\" for \"kn %s\"", args[0], aCmd.Name())
}
}
// recurse to deal with child commands that are themselves command groups
EmptyAndUnknownSubCommands(childCmd)
}
}
// Private
// initConfig reads in config file and ENV variables if set.
func initConfig() {
if commands.CfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(commands.CfgFile)
} else {
configDir, err := defaultConfigDir()
if err != nil {
// Deprecated path warning message & continue
fmt.Fprintf(os.Stderr, "\n%v\n\n", err)
}
// Search config in home directory with name ".kn" (without extension)
viper.AddConfigPath(configDir)
viper.SetConfigName("config")
}
viper.AutomaticEnv() // read in environment variables that match
// If a config file is found, read it in.
err := viper.ReadInConfig()
if err == nil {
fmt.Fprintln(os.Stderr, "Using kn config file:", viper.ConfigFileUsed())
}
}
func defaultConfigDir() (string, error) {
home, err := homedir.Dir()
if err != nil {
return "", fmt.Errorf("%v", err)
}
// Check the deprecated path first and fallback to it, add warning to error message
if configHome := filepath.Join(home, ".kn"); dirExists(configHome) {
migrationPath := filepath.Join(home, ".config", "kn")
if runtime.GOOS == "windows" {
migrationPath = filepath.Join(os.Getenv("APPDATA"), "kn")
}
return configHome, fmt.Errorf("WARNING: deprecated kn config directory detected. "+
"Please move your configuration to: %s", migrationPath)
}
// Respect %APPDATA% on MS Windows
// C:\Documents and Settings\username\Application JsonData
if runtime.GOOS == "windows" {
return filepath.Join(os.Getenv("APPDATA"), "kn"), nil
}
// Respect XDG_CONFIG_HOME if set
if xdgHome := os.Getenv("XDG_CONFIG_HOME"); xdgHome != "" {
return filepath.Join(xdgHome, "kn"), nil
}
// Fallback to XDG default for both Linux and macOS
// ~/.config/kn
return filepath.Join(home, ".config", "kn"), nil
}
func dirExists(path string) bool {
if _, err := os.Stat(path); !os.IsNotExist(err) {
return true
}
return false
}
func initConfigFlags() error {
if viper.IsSet("plugins-dir") {
commands.Cfg.PluginsDir = viper.GetString("plugins-dir")
}
// Always set the Cfg.LookupPlugins from viper value since default is false both ways
var aBool bool
aBool = viper.GetBool("lookup-plugins")
commands.Cfg.LookupPlugins = &aBool
// set the Cfg.SinkPrefixes from viper if sink is configured
if viper.IsSet("sink") {
err := viper.UnmarshalKey("sink", &commands.Cfg.SinkPrefixes)
if err != nil {
return fmt.Errorf("unable to parse sink prefixes configuration in file %s because of %v",
viper.ConfigFileUsed(), err)
}
cmdflags.ConfigSinkPrefixes(commands.Cfg.SinkPrefixes)
}
return nil
}
func extractKnPluginFlags(args []string) (string, bool, error) {
// Deprecated default path, fallback to it when exist
home, _ := homedir.Dir()
pluginsDir := filepath.Join(home, ".kn", "plugins")
if !dirExists(pluginsDir) {
configDir, _ := defaultConfigDir()
pluginsDir = filepath.Join(configDir, "plugins")
}
lookupPluginsInPath := false
dirFlag := "--plugins-dir"
pathFlag := "--lookup-plugins"
var err error
for _, arg := range args {
if arg == dirFlag {
// They forgot the =...
return "", false, fmt.Errorf("Missing %s flag value", dirFlag)
} else if strings.HasPrefix(arg, dirFlag+"=") {
// Starts with --plugins-dir= so we parse the value
pluginsDir = arg[len(dirFlag)+1:]
if pluginsDir == "" {
// They have a "=" but nothing afer it
return "", false, fmt.Errorf("Missing %s flag value", dirFlag)
}
}
if arg == pathFlag {
// just --lookup-plugins no "="
lookupPluginsInPath = true
} else if strings.HasPrefix(arg, pathFlag+"=") {
// Starts with --lookup-plugins= so we parse value
arg = arg[len(pathFlag)+1:]
if lookupPluginsInPath, err = strconv.ParseBool(arg); err != nil {
return "", false, fmt.Errorf("Invalid boolean value(%q) for %s flag", arg, dirFlag)
}
}
}
return pluginsDir, lookupPluginsInPath, nil
}
func removeKnPluginFlags(args []string) []string {
var remainingArgs []string
// Remove these two flags from the list of args. Even though some of
// of these cases should have resulted in an error, if for some reason
// we got here just remove them anyway.
for _, arg := range args {
if arg == "--plugins-dir" ||
strings.HasPrefix(arg, "--plugins-dir=") ||
arg == "--lookup-plugins" ||
strings.HasPrefix(arg, "--lookup-plugins=") ||
// remove -test.* args which are added when running go test
strings.HasPrefix(arg, "-test.") {
continue
} else {
remainingArgs = append(remainingArgs, arg)
}
}
return remainingArgs
}
func width() (int, error) {
width, _, err := terminal.GetSize(int(os.Stdout.Fd()))
return width, err
}
func getCommands(args []string, innerArg string) string {
commands := []string{"kn"}
for _, arg := range args {
if arg == innerArg {
return strings.Join(commands, " ")
}
commands = append(commands, arg)
}
return ""
}
func showSubcommands(cmd *cobra.Command, args []string, innerArg string) string {
var strs []string
for _, subcmd := range cmd.Commands() {
strs = append(strs, subcmd.Name())
}
return fmt.Sprintf("Error: unknown subcommand '%s' for '%s'.\nAvailable subcommands: %s\nRun 'kn --help' for usage.\n", innerArg, getCommands(args, innerArg), strings.Join(strs, ", "))
}
func helpOptionsPresent(args []string) bool {
for _, arg := range args {
if arg == "-h" || arg == "--help" {
return true
}
}
return false
}