forked from heroku/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
flag.go
85 lines (77 loc) · 1.79 KB
/
flag.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
package main
import (
"errors"
"strings"
)
// Flag defines a flag for a command.
// These will be parsed in Go and passed to the Run method in the Context struct.
type Flag struct {
Name string `json:"name"`
Char string `json:"char"`
Description string `json:"description"`
HasValue bool `json:"hasValue"`
Hidden bool `json:"hidden"`
Required bool `json:"required"`
}
var appFlag = &Flag{
Name: "app",
Char: "a",
HasValue: true,
Description: "app to run command against",
}
var remoteFlag = &Flag{
Name: "remote",
Char: "r",
HasValue: true,
Description: "git remote of app to run command against",
}
var orgFlag = &Flag{
Name: "org",
Char: "o",
HasValue: true,
Description: "organization to use",
}
var debuggerFlag = &Flag{
Name: "debugger",
}
func (f *Flag) String() string {
s := " "
switch {
case f.Char != "" && f.Name != "":
s = s + "-" + f.Char + ", --" + f.Name
case f.Char != "":
s = s + "-" + f.Char
case f.Name != "":
s = s + "--" + f.Name
}
if f.HasValue {
s = s + " " + strings.ToUpper(f.Name)
}
return s
}
func parseFlag(input string, flags []*Flag) (*Flag, string, error) {
keyvalue := strings.SplitN(input, "=", 2)
key := keyvalue[0]
value := ""
if len(keyvalue) == 2 {
value = keyvalue[1]
}
if len(key) > 2 && key[1] != '-' {
return parseFlag(key[:2]+"="+key[2:], flags)
}
for _, flag := range flags {
if (flag.Char != "" && key == "-"+flag.Char) || key == "--"+flag.Name {
if flag.HasValue {
if value == "" {
return nil, "", errors.New(flag.String() + " needs a value")
}
return flag, value, nil
}
if value != "" {
return nil, "", errors.New(flag.String() + " does not take a value")
}
return flag, "", nil
}
}
return nil, "", nil
}