-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd.go
223 lines (185 loc) · 5.63 KB
/
cmd.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
package cmd
import (
"fmt"
"os"
"runtime"
"strings"
"path/filepath"
"code.cloudfoundry.org/cli/cf/commandregistry"
"code.cloudfoundry.org/cli/cf/commandsloader"
"code.cloudfoundry.org/cli/cf/configuration"
"code.cloudfoundry.org/cli/cf/configuration/confighelpers"
"code.cloudfoundry.org/cli/cf/configuration/coreconfig"
"code.cloudfoundry.org/cli/cf/configuration/pluginconfig"
"code.cloudfoundry.org/cli/cf/flags"
. "code.cloudfoundry.org/cli/cf/i18n"
"code.cloudfoundry.org/cli/cf/net"
"code.cloudfoundry.org/cli/cf/requirements"
"code.cloudfoundry.org/cli/cf/terminal"
"code.cloudfoundry.org/cli/cf/trace"
"code.cloudfoundry.org/cli/plugin/rpc"
"code.cloudfoundry.org/cli/util/spellcheck"
netrpc "net/rpc"
)
var cmdRegistry = commandregistry.Commands
func Main(traceEnv string, args []string) {
//handle `cf -v` for cf version
if len(args) == 2 && (args[1] == "-v" || args[1] == "--version") {
args[1] = "version"
}
//handles `cf`
if len(args) == 1 {
args = []string{args[0], "help"}
}
//handles `cf [COMMAND] -h ...`
//rearrange args to `cf help COMMAND` and let `command help` to print out usage
args = append([]string{args[0]}, handleHelp(args[1:])...)
newArgs, isVerbose := handleVerbose(args)
args = newArgs
errFunc := func(err error) {
if err != nil {
ui := terminal.NewUI(
os.Stdin,
Writer,
terminal.NewTeePrinter(Writer),
trace.NewLogger(Writer, isVerbose, traceEnv, ""),
)
ui.Failed(fmt.Sprintf("Config error: %s", err))
os.Exit(1)
}
}
// Only used to get Trace, so our errorHandler doesn't matter, since it's not used
configPath, err := confighelpers.DefaultFilePath()
if err != nil {
errFunc(err)
}
config := coreconfig.NewRepositoryFromFilepath(configPath, errFunc)
defer config.Close()
traceConfigVal := config.Trace()
// Writer is assigned in writer_unix.go/writer_windows.go
traceLogger := trace.NewLogger(Writer, isVerbose, traceEnv, traceConfigVal)
deps := commandregistry.NewDependency(Writer, traceLogger, os.Getenv("CF_DIAL_TIMEOUT"))
defer deps.Config.Close()
warningProducers := []net.WarningProducer{}
for _, warningProducer := range deps.Gateways {
warningProducers = append(warningProducers, warningProducer)
}
warningsCollector := net.NewWarningsCollector(deps.UI, warningProducers...)
commandsloader.Load()
//run core command
cmdName := args[1]
cmd := cmdRegistry.FindCommand(cmdName)
if cmd != nil {
meta := cmd.MetaData()
flagContext := flags.NewFlagContext(meta.Flags)
flagContext.SkipFlagParsing(meta.SkipFlagParsing)
cmdArgs := args[2:]
err = flagContext.Parse(cmdArgs...)
if err != nil {
usage := cmdRegistry.CommandUsage(cmdName)
deps.UI.Failed(T("Incorrect Usage") + "\n\n" + err.Error() + "\n\n" + usage)
}
cmd = cmd.SetDependency(deps, false)
cmdRegistry.SetCommand(cmd)
requirementsFactory := requirements.NewFactory(deps.Config, deps.RepoLocator)
reqs, reqErr := cmd.Requirements(requirementsFactory, flagContext)
if reqErr != nil {
os.Exit(1)
}
for _, req := range reqs {
err = req.Execute()
if err != nil {
deps.UI.Failed(err.Error())
os.Exit(1)
}
}
err = cmd.Execute(flagContext)
if err != nil {
deps.UI.Failed(err.Error())
os.Exit(1)
}
err = warningsCollector.PrintWarnings()
if err != nil {
deps.UI.Failed(err.Error())
os.Exit(1)
}
os.Exit(0)
}
//non core command, try plugin command
server := netrpc.NewServer()
rpcService, err := rpc.NewRpcService(deps.TeePrinter, deps.TeePrinter, deps.Config, deps.RepoLocator, rpc.NewCommandRunner(), deps.Logger, Writer, server)
if err != nil {
deps.UI.Say(T("Error initializing RPC service: ") + err.Error())
os.Exit(1)
}
pluginPath := filepath.Join(confighelpers.PluginRepoDir(), ".cf", "plugins")
pluginConfig := pluginconfig.NewPluginConfig(
func(err error) {
deps.UI.Failed(fmt.Sprintf("Error read/writing plugin config: %s, ", err.Error()))
},
configuration.NewDiskPersistor(filepath.Join(pluginPath, "config.json")),
pluginPath,
)
pluginList := pluginConfig.Plugins()
ran := rpc.RunMethodIfExists(rpcService, args[1:], pluginList)
if !ran {
deps.UI.Say("'" + args[1] + T("' is not a registered command. See 'cf help'"))
suggestCommands(cmdName, deps.UI, append(cmdRegistry.ListCommands(), pluginConfig.ListCommands()...))
os.Exit(1)
}
}
func suggestCommands(cmdName string, ui terminal.UI, cmdsList []string) {
cmdSuggester := spellcheck.NewCommandSuggester(cmdsList)
recommendedCmds := cmdSuggester.Recommend(cmdName)
if len(recommendedCmds) != 0 {
ui.Say("\n" + T("Did you mean?"))
for _, suggestion := range recommendedCmds {
ui.Say(" " + suggestion)
}
}
}
func generateBacktrace() string {
stackByteCount := 0
stackSizeLimit := 1024 * 1024
var bytes []byte
for stackSize := 1024; (stackByteCount == 0 || stackByteCount == stackSize) && stackSize < stackSizeLimit; stackSize = 2 * stackSize {
bytes = make([]byte, stackSize)
stackByteCount = runtime.Stack(bytes, true)
}
stackTrace := "\t" + strings.Replace(string(bytes), "\n", "\n\t", -1)
return stackTrace
}
func handleHelp(args []string) []string {
hIndex := -1
for i, v := range args {
if v == "-h" || v == "--help" || v == "--h" {
hIndex = i
break
}
}
if hIndex == -1 {
return args
} else if len(args) > 1 {
if hIndex == 0 {
return []string{"help", args[1]}
}
return []string{"help", args[0]}
} else {
return []string{"help"}
}
}
func handleVerbose(args []string) ([]string, bool) {
var verbose bool
idx := -1
for i, arg := range args {
if arg == "-v" {
idx = i
break
}
}
if idx != -1 && len(args) > 1 {
verbose = true
args = append(args[:idx], args[idx+1:]...)
}
return args, verbose
}