-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathargs.go
More file actions
41 lines (36 loc) · 836 Bytes
/
args.go
File metadata and controls
41 lines (36 loc) · 836 Bytes
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
package cmd
import (
"fmt"
"regexp"
"strings"
"github.com/spf13/cobra"
)
var requiredArgRe = regexp.MustCompile(`<(\w+)>`)
func wrapArgsWithNames(cmd *cobra.Command) {
if cmd.Args != nil {
v := cmd.Args
cmd.Args = func(cmd *cobra.Command, args []string) error {
err := v(cmd, args)
if err == nil {
return nil
}
required := requiredArgNames(cmd.Use)
if len(args) < len(required) {
missing := required[len(args):]
return fmt.Errorf(`required argument(s) "%s" not set`, strings.Join(missing, `", "`))
}
return err
}
}
for _, c := range cmd.Commands() {
wrapArgsWithNames(c)
}
}
func requiredArgNames(use string) []string {
matches := requiredArgRe.FindAllStringSubmatch(use, -1)
names := make([]string, len(matches))
for i, m := range matches {
names[i] = m[1]
}
return names
}