forked from cloudfoundry/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
249 lines (214 loc) · 6.79 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
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
// +build go1.12
package main
import (
"errors"
"fmt"
"os"
"reflect"
"strings"
"code.cloudfoundry.org/cli/cf/cmd"
"code.cloudfoundry.org/cli/command"
"code.cloudfoundry.org/cli/command/common"
"code.cloudfoundry.org/cli/command/flag"
"code.cloudfoundry.org/cli/command/translatableerror"
"code.cloudfoundry.org/cli/util/configv3"
"code.cloudfoundry.org/cli/util/panichandler"
"code.cloudfoundry.org/cli/util/ui"
"github.com/jessevdk/go-flags"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh"
)
type UI interface {
DisplayError(err error)
DisplayWarning(template string, templateValues ...map[string]interface{})
DisplayText(template string, templateValues ...map[string]interface{})
FlushDeferred()
}
type DisplayUsage interface {
DisplayUsage()
}
type TriggerLegacyMain interface {
LegacyMain()
error
}
const switchToV2 = -3
var ErrFailed = errors.New("command failed")
var ParseErr = errors.New("incorrect type for arg")
func main() {
defer panichandler.HandlePanic()
exitStatus := parse(os.Args[1:], &common.Commands)
if exitStatus == switchToV2 {
exitStatus = parse(os.Args[1:], &common.FallbackCommands)
}
if exitStatus != 0 {
os.Exit(exitStatus)
}
}
func parse(args []string, commandList interface{}) int {
parser := flags.NewParser(commandList, flags.HelpFlag)
parser.CommandHandler = executionWrapper
extraArgs, err := parser.ParseArgs(args)
if err == nil {
return 0
} else if _, ok := err.(translatableerror.V3V2SwitchError); ok {
return switchToV2
} else if flagErr, ok := err.(*flags.Error); ok {
return handleFlagErrorAndCommandHelp(flagErr, parser, extraArgs, args, commandList)
} else if err == ErrFailed {
return 1
} else if err == ParseErr {
fmt.Println()
parse([]string{"help", args[0]}, commandList)
return 1
} else if exitError, ok := err.(*ssh.ExitError); ok {
return exitError.ExitStatus()
}
fmt.Fprintf(os.Stderr, "Unexpected error: %s\n", err.Error())
return 1
}
func handleFlagErrorAndCommandHelp(flagErr *flags.Error, parser *flags.Parser, extraArgs []string, originalArgs []string, commandList interface{}) int {
switch flagErr.Type {
case flags.ErrHelp, flags.ErrUnknownFlag, flags.ErrExpectedArgument, flags.ErrInvalidChoice:
_, found := reflect.TypeOf(common.Commands).FieldByNameFunc(
func(fieldName string) bool {
field, _ := reflect.TypeOf(common.Commands).FieldByName(fieldName)
return parser.Active != nil && parser.Active.Name == field.Tag.Get("command")
},
)
if found && flagErr.Type == flags.ErrUnknownFlag && (parser.Active.Name == "set-env" || parser.Active.Name == "v3-set-env") {
newArgs := []string{}
for _, arg := range originalArgs {
if arg[0] == '-' {
newArgs = append(newArgs, fmt.Sprintf("%s%s", flag.WorkAroundPrefix, arg))
} else {
newArgs = append(newArgs, arg)
}
}
parse(newArgs, commandList)
return 0
}
if flagErr.Type == flags.ErrUnknownFlag || flagErr.Type == flags.ErrExpectedArgument || flagErr.Type == flags.ErrInvalidChoice {
fmt.Fprintf(os.Stderr, "Incorrect Usage: %s\n\n", flagErr.Error())
}
var helpErrored int
if found {
helpErrored = parse([]string{"help", parser.Active.Name}, commandList)
} else {
switch len(extraArgs) {
case 0:
helpErrored = parse([]string{"help"}, commandList)
case 1:
if !isOption(extraArgs[0]) || (len(originalArgs) > 1 && extraArgs[0] == "-a") {
helpErrored = parse([]string{"help", extraArgs[0]}, commandList)
} else {
helpErrored = parse([]string{"help"}, commandList)
}
default:
if isCommand(extraArgs[0]) {
helpErrored = parse([]string{"help", extraArgs[0]}, commandList)
} else {
helpErrored = parse(extraArgs[1:], commandList)
}
}
}
if helpErrored > 0 || flagErr.Type == flags.ErrUnknownFlag || flagErr.Type == flags.ErrExpectedArgument || flagErr.Type == flags.ErrInvalidChoice {
return 1
}
case flags.ErrRequired, flags.ErrMarshal:
fmt.Fprintf(os.Stderr, "Incorrect Usage: %s\n\n", flagErr.Error())
parse([]string{"help", originalArgs[0]}, commandList)
return 1
case flags.ErrUnknownCommand:
cmd.Main(os.Getenv("CF_TRACE"), os.Args)
case flags.ErrCommandRequired:
if common.Commands.VerboseOrVersion {
parse([]string{"version"}, commandList)
} else {
parse([]string{"help"}, commandList)
}
default:
fmt.Fprintf(os.Stderr, "Unexpected flag error\ntype: %s\nmessage: %s\n", flagErr.Type, flagErr.Error())
}
return 0
}
func isCommand(s string) bool {
_, found := reflect.TypeOf(common.Commands).FieldByNameFunc(
func(fieldName string) bool {
field, _ := reflect.TypeOf(common.Commands).FieldByName(fieldName)
return s == field.Tag.Get("command") || s == field.Tag.Get("alias")
})
return found
}
func isOption(s string) bool {
return strings.HasPrefix(s, "-")
}
func executionWrapper(cmd flags.Commander, args []string) error {
cfConfig, configErr := configv3.LoadConfig(configv3.FlagOverride{
Verbose: common.Commands.VerboseOrVersion,
})
if configErr != nil {
if _, ok := configErr.(translatableerror.EmptyConfigError); !ok {
return configErr
}
}
commandUI, err := ui.NewUI(cfConfig)
if err != nil {
return err
}
defer commandUI.FlushDeferred()
err = preventExtraArgs(args)
if err != nil {
return handleError(err, commandUI)
}
err = cfConfig.CreatePluginHome()
if err != nil {
return handleError(err, commandUI)
}
defer func() {
configWriteErr := cfConfig.WriteConfig()
if configWriteErr != nil {
fmt.Fprintf(os.Stderr, "Error writing config: %s", configWriteErr.Error())
}
}()
if extendedCmd, ok := cmd.(command.ExtendedCommander); ok {
log.SetOutput(os.Stderr)
log.SetLevel(log.Level(cfConfig.LogLevel()))
err = extendedCmd.Setup(cfConfig, commandUI)
if err != nil {
return handleError(err, commandUI)
}
return handleError(extendedCmd.Execute(args), commandUI)
}
return fmt.Errorf("command does not conform to ExtendedCommander")
}
func handleError(passedErr error, commandUI UI) error {
if passedErr == nil {
return nil
}
translatedErr := translatableerror.ConvertToTranslatableError(passedErr)
switch typedErr := translatedErr.(type) {
case translatableerror.V3V2SwitchError:
log.Info("Received a V3V2SwitchError - switch to the V2 version of the command")
return passedErr
case TriggerLegacyMain:
if typedErr.Error() != "" {
commandUI.DisplayWarning("")
commandUI.DisplayWarning(typedErr.Error())
}
cmd.Main(os.Getenv("CF_TRACE"), os.Args)
case *ssh.ExitError:
exitStatus := typedErr.ExitStatus()
if sig := typedErr.Signal(); sig != "" {
commandUI.DisplayText("Process terminated by signal: {{.Signal}}. Exited with {{.ExitCode}}", map[string]interface{}{
"Signal": sig,
"ExitCode": exitStatus,
})
}
return passedErr
}
commandUI.DisplayError(translatedErr)
if _, ok := translatedErr.(DisplayUsage); ok {
return ParseErr
}
return ErrFailed
}