-
Notifications
You must be signed in to change notification settings - Fork 263
/
Copy pathmain.go
160 lines (138 loc) · 4.37 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
// 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 main
import (
"fmt"
"math/rand"
"os"
"strings"
"time"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"knative.dev/client/pkg/kn/config"
"knative.dev/client/pkg/kn/plugin"
"knative.dev/client/pkg/kn/root"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func main() {
err := run(os.Args[1:])
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
// This is the only point from where to exit when an error occurs
os.Exit(1)
}
}
// Run the main program. Args are the args as given on the command line (excluding the program name itself)
func run(args []string) error {
// Parse config & plugin flags early to read in configuration file
// and bind to viper. After that you can access all configuration and
// global options via methods on config.GlobalConfig
err := config.BootstrapConfig()
if err != nil {
return err
}
// Strip of all flags to get the non-flag commands only
commands, err := stripFlags(args)
if err != nil {
return err
}
// Find plugin with the commands arguments
pluginManager := plugin.NewManager(config.GlobalConfig.PluginsDir(), config.GlobalConfig.LookupPluginsInPath())
plugin, err := pluginManager.FindPlugin(commands)
if err != nil {
return err
}
// Create kn root command and all sub-commands
rootCmd, err := root.NewRootCommand()
if err != nil {
return err
}
if plugin != nil {
// Validate & Execute plugin
err = validatePlugin(rootCmd, plugin)
if err != nil {
return err
}
return plugin.Execute(argsWithoutCommands(args, plugin.CommandParts()))
} else {
// Execute kn root command
return rootCmd.Execute()
}
}
// Get only the args provided but no options. The extraction
// process is a bit tricky as Cobra doesn't provide such
// functionality out of the box
func stripFlags(args []string) ([]string, error) {
// Store all command
commandsFound := &[]string{}
// Use a canary command that allows all options and only extracts
// commands. Doesn't work with arbitrary boolean flags but is good enough
// for us here
extractCommand := cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
for _, arg := range args {
*commandsFound = append(*commandsFound, arg)
}
},
}
// Filter out --help and -h options to avoid special treatment which we don't
// need here
extractCommand.SetArgs(filterHelpOptions(args))
// Adding all global flags here
config.AddBootstrapFlags(extractCommand.Flags())
// Allow all options
extractCommand.FParseErrWhitelist = cobra.FParseErrWhitelist{UnknownFlags: true}
// Execute to get to the command args
err := extractCommand.Execute()
if err != nil {
return nil, err
}
return *commandsFound, nil
}
// Strip all plugin commands before calling out to the plugin
func argsWithoutCommands(cmdArgs []string, pluginCommandsParts []string) []string {
var ret []string
for _, arg := range cmdArgs {
if len(pluginCommandsParts) > 0 && pluginCommandsParts[0] == arg {
pluginCommandsParts = pluginCommandsParts[1:]
continue
}
ret = append(ret, arg)
}
return ret
}
// Remove all help options
func filterHelpOptions(args []string) []string {
var ret []string
for _, arg := range args {
if arg != "-h" && arg != "--help" {
ret = append(ret, arg)
}
}
return ret
}
// Check if the plugin collides with any command specified in the root command
func validatePlugin(root *cobra.Command, plugin plugin.Plugin) error {
// Check if a given plugin can be identified as a command
cmd, args, err := root.Find(plugin.CommandParts())
if err == nil {
if !cmd.HasSubCommands() || // a leaf command can't be overridden
cmd.HasSubCommands() && len(args) == 0 { // a group can't be overridden either
return errors.Errorf("plugin %s is overriding built-in command '%s' which is not allowed", plugin.Path(), strings.Join(plugin.CommandParts(), " "))
}
}
return nil
}