forked from go-prompt/prompt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommand.go
69 lines (51 loc) · 1.21 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
package prompt
import (
"fmt"
"sort"
)
// Command is a representation of a valid command.
type Command struct {
Cmd string
Desc string
Action func([]string)
}
func (c *Command) run(args []string) bool {
if c.Cmd == "quit" {
return true
} else if c.Cmd == "" {
return false
}
if c.Action != nil {
defer func() { // handling panic
if r := recover(); r != nil {
fmt.Println("Ops! ["+c.Cmd+"] -", r)
}
}()
c.Action(args)
return false
}
fmt.Printf("%s: command not found. Try 'help'.\n", c.Cmd)
return false
}
type commandList []Command
func (c commandList) Len() int { return len(c) }
func (c commandList) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
func (c commandList) Less(i, j int) bool { return c[i].Cmd < c[j].Cmd }
var commands commandList
func findCommand(txt string) *Command {
for _, cmd := range commands {
if cmd.Cmd == txt {
return &cmd
}
}
return &Command{Cmd: txt, Action: nil}
}
// Add provides a new Command.
func Add(c Command) {
commands = append(commands, c)
sort.Sort(commands)
}
// AddCommand constructs a new Command and provides it.
func AddCommand(name string, desc string, action func([]string)) {
Add(Command{name, desc, action})
}