This repository has been archived by the owner on Apr 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
handlers_meta.go
95 lines (76 loc) · 2.12 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"fmt"
"github.com/prasmussen/gdrive/cli"
"os"
"runtime"
"strings"
"text/tabwriter"
)
func printVersion(ctx cli.Context) {
fmt.Printf("%s: %s\n", Name, Version)
fmt.Printf("Golang: %s\n", runtime.Version())
fmt.Printf("OS/Arch: %s/%s\n", runtime.GOOS, runtime.GOARCH)
}
func printHelp(ctx cli.Context) {
w := new(tabwriter.Writer)
w.Init(os.Stdout, 0, 0, 3, ' ', 0)
fmt.Fprintf(w, "%s usage:\n\n", Name)
for _, h := range ctx.Handlers() {
fmt.Fprintf(w, "%s %s\t%s\n", Name, h.Pattern, h.Description)
}
w.Flush()
}
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")
}
w := new(tabwriter.Writer)
w.Init(os.Stdout, 0, 0, 3, ' ', 0)
fmt.Fprintf(w, "%s\n", handler.Description)
fmt.Fprintf(w, "%s %s\n", Name, handler.Pattern)
for _, group := range handler.FlagGroups {
fmt.Fprintf(w, "\n%s:\n", group.Name)
for _, flag := range group.Flags {
boolFlag, isBool := flag.(cli.BoolFlag)
if isBool && boolFlag.OmitValue {
fmt.Fprintf(w, " %s\t%s\n", strings.Join(flag.GetPatterns(), ", "), flag.GetDescription())
} else {
fmt.Fprintf(w, " %s <%s>\t%s\n", strings.Join(flag.GetPatterns(), ", "), flag.GetName(), flag.GetDescription())
}
}
}
w.Flush()
}
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
}