forked from heroku/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.go
281 lines (262 loc) · 7.52 KB
/
cli.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
package main
import (
"errors"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/heroku/heroku-cli/Godeps/_workspace/src/github.com/dickeyxxx/netrc"
)
// ErrHelp means the user didn't type a valid command and we need to display help.
var ErrHelp = errors.New("help")
// ErrAppNeeded means the command needs an app context and one was not found.
var ErrAppNeeded = errors.New("No app specified.\nRun this command from an app folder or specify which app to use with --app APP")
// ErrOrgNeeded means the command needs an org context and one was not found.
var ErrOrgNeeded = errors.New("No org specified.\nRun this command with --org or by setting HEROKU_ORGANIZATION")
// Cli handles parsing and dispatching of commands
type Cli struct {
Topics TopicSet
Commands CommandSet
}
// Run parses command line arguments and runs the associated command or help.
// Also does lookups for app name and/or auth token if the command needs it.
func (cli *Cli) Run(args []string) (err error) {
ctx := &Context{}
if len(args) < 2 {
return ErrHelp
}
ctx.Topic, ctx.Command = cli.ParseCmd(args[1])
if ctx.Command == nil {
return ErrHelp
}
if ctx.Command.VariableArgs {
ctx.Args, ctx.Flags, ctx.App, err = parseVarArgs(ctx.Command, args[2:])
} else {
ctx.Args, ctx.Flags, ctx.App, err = parseArgs(ctx.Command, args[2:])
}
if err != nil {
return err
}
if ctx.Command.NeedsApp || ctx.Command.WantsApp {
if ctx.App == "" {
ctx.App = app()
}
if ctx.App == "" && ctx.Command.NeedsApp {
return ErrAppNeeded
}
}
if ctx.Command.NeedsOrg || ctx.Command.WantsOrg {
if org, ok := ctx.Flags["org"].(string); ok {
ctx.Org = org
} else {
ctx.Org = os.Getenv("HEROKU_ORGANIZATION")
}
if ctx.Org == "" && ctx.Command.NeedsOrg {
return ErrOrgNeeded
}
}
if ctx.Command.NeedsAuth {
ctx.APIToken = auth()
ctx.Auth.Password = ctx.APIToken
}
ctx.Cwd, _ = os.Getwd()
ctx.HerokuDir = AppDir()
ctx.Debug = debugging
ctx.DebugHeaders = debuggingHeaders
ctx.Version = version()
ctx.SupportsColor = supportsColor()
ctx.APIHost = apiHost()
ctx.APIURL = apiURL()
ctx.GitHost = gitHost()
ctx.HTTPGitHost = httpGitHost()
ctx.Command.Run(ctx)
return nil
}
// ParseCmd parses the command argument into a topic and command
func (cli *Cli) ParseCmd(cmd string) (topic *Topic, command *Command) {
if strings.ToLower(cmd) == "--version" || strings.ToLower(cmd) == "-v" {
return versionTopic, versionCmd
}
tc := strings.SplitN(cmd, ":", 2)
topic = cli.Topics.ByName(tc[0])
if topic == nil {
return nil, nil
}
if len(tc) == 2 {
return topic, cli.Commands.ByTopicAndCommand(tc[0], tc[1])
}
return topic, cli.Commands.ByTopicAndCommand(tc[0], "")
}
func parseVarArgs(command *Command, args []string) (result []string, flags map[string]interface{}, appName string, err error) {
result = make([]string, 0, len(args))
flags = map[string]interface{}{}
parseFlags := true
possibleFlags := []*Flag{debuggerFlag}
populateFlagsFromEnvVars(command.Flags, flags)
for _, flag := range command.Flags {
f := flag
possibleFlags = append(possibleFlags, &f)
}
if command.NeedsApp || command.WantsApp {
possibleFlags = append(possibleFlags, appFlag, remoteFlag)
}
if command.NeedsOrg || command.WantsOrg {
possibleFlags = append(possibleFlags, orgFlag)
}
for i := 0; i < len(args); i++ {
switch {
case parseFlags && (args[i] == "--"):
parseFlags = false
case parseFlags && (args[i] == "--help" || args[i] == "-h"):
return nil, nil, "", ErrHelp
case parseFlags && (args[i] == "--no-color"):
continue
case parseFlags && strings.HasPrefix(args[i], "-"):
flag, val, err := parseFlag(args[i], possibleFlags)
if err != nil && strings.HasSuffix(err.Error(), "needs a value") {
i++
if len(args) == i {
return nil, nil, "", err
}
flag, val, err = parseFlag(args[i-1]+"="+args[i], possibleFlags)
}
switch {
case err != nil:
return nil, nil, "", err
case flag == nil && command.VariableArgs:
result = append(result, args[i])
case flag == nil:
return nil, nil, "", errors.New("Unexpected flag: " + args[i])
case flag == appFlag:
appName = val
case flag == remoteFlag:
appName, err = appFromGitRemote(val)
if err != nil {
return nil, nil, "", err
}
case flag.HasValue:
flags[flag.Name] = val
default:
flags[flag.Name] = true
}
default:
result = append(result, args[i])
}
}
for _, flag := range command.Flags {
if flag.Required && flags[flag.Name] == nil {
return nil, nil, "", errors.New("Required flag: " + flag.String())
}
}
return result, flags, appName, nil
}
func parseArgs(command *Command, args []string) (result map[string]string, flags map[string]interface{}, appName string, err error) {
result = map[string]string{}
args, flags, appName, err = parseVarArgs(command, args)
if err != nil {
return nil, nil, "", err
}
if len(args) > len(command.Args) {
return nil, nil, "", errors.New("Unexpected argument: " + strings.Join(args[len(command.Args):], " "))
}
for i, arg := range args {
result[command.Args[i].Name] = arg
}
for _, arg := range command.Args {
if !arg.Optional && result[arg.Name] == "" {
return nil, nil, "", errors.New("Missing argument: " + strings.ToUpper(arg.Name))
}
}
return result, flags, appName, nil
}
func app() string {
app := os.Getenv("HEROKU_APP")
if app != "" {
return app
}
app, err := appFromGitRemote(remoteFromGitConfig())
if err != nil {
PrintError(err)
os.Exit(1)
}
return app
}
func getNetrc() *netrc.Netrc {
n, err := netrc.Parse(netrcPath())
if err != nil {
if _, ok := err.(*os.PathError); ok {
// File not found
return &netrc.Netrc{Path: netrcPath()}
}
Errln("Error parsing netrc at " + netrcPath())
Errln(err.Error())
os.Exit(1)
}
return n
}
func auth() (password string) {
token := apiToken()
if token == "" {
interactiveLogin()
return auth()
}
return token
}
func apiToken() string {
key := os.Getenv("HEROKU_API_KEY")
if key != "" {
return key
}
netrc := getNetrc()
machine := netrc.Machine(apiHost())
if machine != nil {
return machine.Get("password")
}
return ""
}
func netrcPath() string {
base := filepath.Join(HomeDir, ".netrc")
if runtime.GOOS == "windows" {
base = filepath.Join(HomeDir, "_netrc")
}
if exists, _ := fileExists(base + ".gpg"); exists {
base = base + ".gpg"
}
return base
}
// AddTopic adds a Topic to the set of topics.
// It will return false if a topic exists with the same name.
func (cli *Cli) AddTopic(topic *Topic) {
existing := cli.Topics.ByName(topic.Name)
if existing != nil {
existing.Merge(topic)
} else {
cli.Topics = append(cli.Topics, topic)
}
}
// AddCommand adds a Command to the set of commands.
// It will return false if a command exists with the same topic and command name.
// It will also add an empty topic if there is not one already.
func (cli *Cli) AddCommand(command *Command) bool {
if cli.Topics.ByName(command.Topic) == nil {
cli.Topics = append(cli.Topics, &Topic{Name: command.Topic})
}
if cli.Commands.ByTopicAndCommand(command.Topic, command.Command) != nil {
return false
}
cli.Commands = append(cli.Commands, command)
return true
}
func populateFlagsFromEnvVars(flagDefinitons []Flag, flags map[string]interface{}) {
for _, flag := range flagDefinitons {
if strings.ToLower(flag.Name) == "user" && os.Getenv("HEROKU_USER") != "" {
flags[flag.Name] = os.Getenv("HEROKU_USER")
}
if strings.ToLower(flag.Name) == "force" && os.Getenv("HEROKU_FORCE") == "1" {
flags[flag.Name] = true
}
}
}
func processTitle(ctx *Context) string {
return "heroku " + strings.Join(os.Args[1:], " ")
}