-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathoptions.go
100 lines (83 loc) · 2.12 KB
/
options.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
package gommander
import (
"fmt"
"strings"
)
type Option struct {
Name string
HelpStr string
ShortVal string
LongVal string
Arg *Argument
IsRequired bool
}
// A builder method to generate a new option
func NewOption(name string) *Option {
return &Option{
Name: name,
LongVal: "--" + name,
}
}
// Simply sets the shorthand version of the option
func (o *Option) Short(val rune) *Option {
o.ShortVal = "-" + string(val)
return o
}
// A method for setting the help string / description for an option
func (o *Option) Help(val string) *Option {
o.HelpStr = val
return o
}
// Sets whether or not the option is required
func (o *Option) Required(val bool) *Option {
o.IsRequired = val
return o
}
// A method for adding a new argument to an option. Takes as input the name of the argument
func (o *Option) Argument(val string) *Option {
o.AddArgument(newArgument(val, ""))
return o
}
// A builder method for adding an argument. Expects an instance of an argument as input
func (o *Option) AddArgument(arg *Argument) *Option {
id := fmt.Sprintf("opt-%s-arg-%s", o.Name, arg.Name)
if !cache[id] {
cache[id] = true
o.Arg = arg
}
return o
}
func newOption(val string, help string, required bool) Option {
opt := Option{HelpStr: help, IsRequired: required}
values := strings.Split(val, " ")
for _, v := range values {
if strings.HasPrefix(v, "--") {
opt.LongVal = v
} else if strings.HasPrefix(v, "-") {
opt.ShortVal = v
} else {
opt.Arg = newArgument(v, "")
}
}
opt.Name = strings.TrimPrefix(opt.LongVal, "--")
return opt
}
func (o *Option) generate(app *Command) (string, string) {
var leading, floating strings.Builder
if len(o.ShortVal) > 0 {
leading.WriteString(o.ShortVal + ",")
} else {
leading.WriteString(" ")
}
if len(o.LongVal) > 0 {
leading.WriteString(" " + o.LongVal + " ")
}
if o.Arg != nil {
leading.WriteString(fmt.Sprintf("%v ", o.Arg.getRawValue()))
}
floating.WriteString(o.HelpStr)
if o.Arg != nil && o.Arg.hasDefaultValue() {
floating.WriteString(fmt.Sprintf(" (default: %v)", o.Arg.DefaultValue))
}
return leading.String(), floating.String()
}