forked from prasmussen/gdrive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
118 lines (96 loc) · 2.22 KB
/
handler.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package cli
import (
"regexp"
"strings"
)
func NewFlagGroup(name string, flags ...Flag) FlagGroup {
return FlagGroup{
Name: name,
Flags: flags,
}
}
type FlagGroup struct {
Name string
Flags []Flag
}
type FlagGroups []FlagGroup
func (groups FlagGroups) getFlags(name string) []Flag {
for _, group := range groups {
if group.Name == name {
return group.Flags
}
}
return nil
}
var handlers []*Handler
type Handler struct {
Pattern string
FlagGroups FlagGroups
Callback func(Context)
Description string
}
func (self *Handler) getParser() Parser {
var parsers []Parser
for _, pattern := range self.SplitPattern() {
if isFlagGroup(pattern) {
groupName := flagGroupName(pattern)
flags := self.FlagGroups.getFlags(groupName)
parsers = append(parsers, getFlagParser(flags))
} else if isCaptureGroup(pattern) {
parsers = append(parsers, CaptureGroupParser{pattern})
} else {
parsers = append(parsers, EqualParser{pattern})
}
}
return CompleteParser{parsers}
}
// Split on spaces but ignore spaces inside <...> and [...]
func (self *Handler) SplitPattern() []string {
re := regexp.MustCompile(`(<[^>]+>|\[[^\]]+]|\S+)`)
matches := []string{}
for _, value := range re.FindAllStringSubmatch(self.Pattern, -1) {
matches = append(matches, value[1])
}
return matches
}
func SetHandlers(h []*Handler) {
handlers = h
}
func AddHandler(pattern string, groups FlagGroups, callback func(Context), desc string) {
handlers = append(handlers, &Handler{
Pattern: pattern,
FlagGroups: groups,
Callback: callback,
Description: desc,
})
}
func findHandler(args []string) *Handler {
for _, h := range handlers {
if _, ok := h.getParser().Match(args); ok {
return h
}
}
return nil
}
func Handle(args []string) bool {
h := findHandler(args)
if h == nil {
return false
}
_, data := h.getParser().Capture(args)
ctx := Context{
args: data,
handlers: handlers,
}
h.Callback(ctx)
return true
}
func isCaptureGroup(arg string) bool {
return strings.HasPrefix(arg, "<") && strings.HasSuffix(arg, ">")
}
func isFlagGroup(arg string) bool {
return strings.HasPrefix(arg, "[") && strings.HasSuffix(arg, "]")
}
func flagGroupName(s string) string {
return s[1 : len(s)-1]
}