-
Notifications
You must be signed in to change notification settings - Fork 4
/
util.go
69 lines (53 loc) · 1.53 KB
/
util.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
package util
import (
"fmt"
"github.com/spf13/cobra"
)
const persistentPreRun = "persistent_pre_run"
func PersistentPreRunChain(command *cobra.Command, args []string) error {
return preRunChain(command.Parent(), command, args)
}
func AddGroupedCommands(mainCommand *cobra.Command, group cobra.Group, cmds []*cobra.Command) {
mainCommand.AddGroup(&group)
mainCommand.AddCommand(cmds...)
for _, cmd := range cmds {
cmd.GroupID = group.ID
}
}
func AllComandsHelpFlag(command *cobra.Command) {
flags := command.Flags()
helpFlagName := "help"
if flags.Lookup(helpFlagName) == nil {
flags.BoolP(helpFlagName, "h", false, "Help for "+command.Name())
_ = flags.SetAnnotation(helpFlagName, cobra.FlagSetByCobraAnnotation, []string{StrTrue})
}
for _, command := range command.Commands() {
AllComandsHelpFlag(command)
}
}
func preRunChain(command *cobra.Command, called *cobra.Command, args []string) error {
if command == nil {
return nil
}
if command.Annotations == nil {
command.Annotations = map[string]string{
persistentPreRun: StrTrue,
}
} else {
if command.Annotations[persistentPreRun] == StrTrue {
return nil
}
command.Annotations[persistentPreRun] = StrTrue
}
if err := preRunChain(command.Parent(), called, args); err != nil {
return err
}
if command.PersistentPreRun != nil {
command.PersistentPreRun(called, args)
} else if command.PersistentPreRunE != nil {
if err := command.PersistentPreRunE(called, args); err != nil {
return fmt.Errorf("%s: %w", command.UseLine(), err)
}
}
return nil
}