This repository was archived by the owner on Dec 25, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommand.go
83 lines (66 loc) · 2.29 KB
/
command.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
package drouter
import (
"regexp"
"strings"
)
type matcherFunc func(input string) bool
// Command defines the structure of a plugin sub-command.
type Command struct {
// Names lists the different aliases of the sub-command.
Names StringSet
// MatchFunc is called whenever a new message
// (starting with the correct prefix) is received by the plugin
// and return true or false if it should be handled by this command or not.
MatchFunc matcherFunc
// HandlerFunc Contains the function to invoke
// whenever the command is requested.
HandlerFunc callbackFunc
// Wrappers Contains the functions to invoke before the command.
Wrappers []callbackFunc
// ShortHelp Contains the short straightforward command help.
ShortHelp string
// LongHelp Contains the long descriptive command documentation.
LongHelp string
}
// Match sets the matching function from a given function.
func (cmd *Command) Match(matcherFunc matcherFunc) *Command {
cmd.MatchFunc = matcherFunc
return cmd
}
// MatchRE defines a matching function from a given regex.
func (cmd *Command) MatchRE(regex string) *Command {
matcher := regexp.MustCompile(regex)
cmd.MatchFunc = func(input string) bool {
return matcher.MatchString(input)
}
return cmd
}
// Handler defines the function to invoke whenever the command
// is being invoked.
func (cmd *Command) Handler(callbackFunc callbackFunc) *Command {
cmd.HandlerFunc = callbackFunc
return cmd
}
// Use appends given callbacks to a command to call
// whenever a command is being invoked.
func (cmd *Command) Use(callbackFuncs ...callbackFunc) *Command {
cmd.Wrappers = append(cmd.Wrappers, callbackFuncs...)
return cmd
}
// Help sets the help text of a command. The first line is
// the short and straightforward documentation. The whole text
// is the long and descriptive documentation.
func (cmd *Command) Help(helpText string) *Command {
if startPos := strings.Index(helpText, "\n"); startPos > -1 {
cmd.ShortHelp = helpText[:startPos]
} else {
cmd.ShortHelp = helpText
}
cmd.LongHelp = helpText
return cmd
}
// IsMatching returns true if the command name exists or
// if it matches the matching function, if provided.
func (cmd *Command) IsMatching(targetCommand string) bool {
return cmd.Names.Contains(targetCommand) || (cmd.MatchFunc != nil && cmd.MatchFunc(targetCommand))
}