forked from charmbracelet/mods
-
Notifications
You must be signed in to change notification settings - Fork 0
/
flag.go
82 lines (70 loc) · 1.57 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
package main
import (
"regexp"
"strings"
"time"
"github.com/caarlos0/duration"
)
func newFlagParseError(err error) flagParseError {
var reason, flag string
s := err.Error()
switch {
case strings.HasPrefix(s, "flag needs an argument:"):
reason = "Flag %s needs an argument."
ps := strings.Split(s, "-")
switch len(ps) {
case 2: //nolint:mnd
flag = "-" + ps[len(ps)-1]
case 3: //nolint:mnd
flag = "--" + ps[len(ps)-1]
}
case strings.HasPrefix(s, "unknown flag:"):
reason = "Flag %s is missing."
flag = strings.TrimPrefix(s, "unknown flag: ")
case strings.HasPrefix(s, "invalid argument"):
reason = "Flag %s have an invalid argument."
re := regexp.MustCompile(`invalid argument ".*" for "(.*)" flag: .*`)
parts := re.FindStringSubmatch(s)
if len(parts) > 1 {
flag = parts[1]
}
default:
reason = s
}
return flagParseError{
err: err,
reason: reason,
flag: flag,
}
}
type flagParseError struct {
err error
reason string
flag string
}
func (f flagParseError) Error() string {
return f.err.Error()
}
func (f flagParseError) ReasonFormat() string {
return f.reason
}
func (f flagParseError) Flag() string {
return f.flag
}
func newDurationFlag(val time.Duration, p *time.Duration) *durationFlag {
*p = val
return (*durationFlag)(p)
}
type durationFlag time.Duration
func (d *durationFlag) Set(s string) error {
v, err := duration.Parse(s)
*d = durationFlag(v)
//nolint: wrapcheck
return err
}
func (d *durationFlag) String() string {
return time.Duration(*d).String()
}
func (*durationFlag) Type() string {
return "duration"
}