forked from prasmussen/gdrive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers_meta.go
79 lines (64 loc) · 1.98 KB
/
handlers_meta.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 main
import (
"fmt"
"strings"
"./cli"
)
func printVersion(ctx cli.Context) {
fmt.Printf("%s v%s\n", Name, Version)
}
func printHelp(ctx cli.Context) {
fmt.Printf("%s usage:\n\n", Name)
for _, h := range ctx.Handlers() {
fmt.Printf("%s %s (%s)\n", Name, h.Pattern, h.Description)
}
}
func printCommandHelp(ctx cli.Context) {
args := ctx.Args()
printCommandPrefixHelp(ctx, args.String("command"))
}
func printSubCommandHelp(ctx cli.Context) {
args := ctx.Args()
printCommandPrefixHelp(ctx, args.String("command"), args.String("subcommand"))
}
func printCommandPrefixHelp(ctx cli.Context, prefix ...string) {
handler := getHandler(ctx.Handlers(), prefix)
if handler == nil {
ExitF("Command not found")
}
fmt.Printf("%s %s (%s)\n", Name, handler.Pattern, handler.Description)
for name, flags := range handler.Flags {
fmt.Printf("\n%s:\n", name)
for _, flag := range flags {
boolFlag, isBool := flag.(cli.BoolFlag)
if isBool && boolFlag.OmitValue {
fmt.Printf(" %s (%s)\n", strings.Join(flag.GetPatterns(), ", "), flag.GetDescription())
} else {
fmt.Printf(" %s <%s> (%s)\n", strings.Join(flag.GetPatterns(), ", "), flag.GetName(), flag.GetDescription())
}
}
}
}
func getHandler(handlers []*cli.Handler, prefix []string) *cli.Handler {
for _, h := range handlers {
pattern := stripOptionals(h.SplitPattern())
if len(prefix) > len(pattern) {
continue
}
if equal(prefix, pattern[:len(prefix)]) {
return h
}
}
return nil
}
// Strip optional groups (<...>) from pattern
func stripOptionals(pattern []string) []string {
newArgs := []string{}
for _, arg := range pattern {
if strings.HasPrefix(arg, "[") && strings.HasSuffix(arg, "]") {
continue
}
newArgs = append(newArgs, arg)
}
return newArgs
}