-
Notifications
You must be signed in to change notification settings - Fork 191
/
optarg.go
79 lines (67 loc) · 1.55 KB
/
optarg.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
package cflag
import (
"github.com/gookit/goutil/errorx"
"github.com/gookit/goutil/structs"
"github.com/gookit/goutil/strutil"
)
// OptCheckFn define
type OptCheckFn func(val any) error
// FlagOpt struct
type FlagOpt struct {
// Shortcuts short names. eg: ["o", "a"]
Shortcuts []string
// Required option
Required bool
// Validator for check option value
Validator OptCheckFn
}
// HelpName string
func (o *FlagOpt) HelpName(name string) string {
return AddPrefixes(name, o.Shortcuts)
}
// FlagArg struct
type FlagArg struct {
// Value for the flag argument
*structs.Value
// default val string
defVal string
// Name of the argument
Name string
// Desc arg description
Desc string
// Index of the argument
Index int
// Required argument
Required bool
// Validator for check value
Validator func(val string) error
}
// NewArg create instance
func NewArg(name, desc string, required bool) *FlagArg {
return &FlagArg{Name: name, Desc: desc, Required: required}
}
// check arg config and init
func (a *FlagArg) check() error {
if a.Name == "" {
return errorx.Rawf("cflag: arg#%d name cannot be empty", a.Index)
}
if a.Required && a.V != nil {
return errorx.Rawf("cflag: cannot set default value for 'required' arg: %s", a.Name)
}
if a.Desc == "" {
a.Desc = "no description"
}
a.defVal = a.String()
return nil
}
// HelpDesc string build
func (a *FlagArg) HelpDesc() string {
desc := strutil.UpperFirst(a.Desc)
if a.Required {
desc = "<red>*</>" + desc
}
if a.defVal != "" {
desc += "(default: <mga>" + a.defVal + "</>)"
}
return desc
}