-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommando.go
More file actions
108 lines (83 loc) · 1.84 KB
/
commando.go
File metadata and controls
108 lines (83 loc) · 1.84 KB
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
package commando
import (
"fmt"
"os"
"strings"
"github.com/wh64dev/commando/option"
)
type Commando struct {
args []string
internal *CommandoNode
nodes []CommandoNode
}
func CommandoNew() *Commando {
return &Commando{
internal: nil,
args: os.Args,
}
}
func CommandoArgsGet(c *Commando) []string {
return c.args
}
func CommandoNodesGet(c *Commando) []CommandoNode {
return c.nodes
}
func CommandoInternalGet(c *Commando) *CommandoNode {
return c.internal
}
func CommandoInternalSet(c *Commando, h ArgHandler, options ...option.OptionData) {
var n = CommandoNodeNew(c, "", "")
n.options = append(n.options, options...)
n.handler = h
c.internal = n
}
func CommandoNodeAppend(c *Commando, n *CommandoNode) {
c.nodes = append(c.nodes, *n)
}
func handleError(c *Commando) error {
return fmt.Errorf("%s: error: unknown command", c.args[0])
}
func execute(n *CommandoNode) error {
return n.handler(n)
}
func executeSubnode(n *CommandoNode, args []string) error {
if len(args) == 0 {
if n.handler == nil {
return handleError(n.Commando)
}
return execute(n)
}
var next = args[0]
var remaining = args[1:]
for _, sn := range n.subnodes {
if sn.name != next {
continue
}
return executeSubnode(&sn, remaining)
}
if n.handler == nil {
return fmt.Errorf("%s: error: unknown command to '%s'", n.Commando.args[0], next)
}
return execute(n)
}
func CommandoExecute(c *Commando) error {
if len(c.args) == 1 {
if c.internal == nil {
return handleError(c)
}
return execute(c.internal)
}
var current = c.args[1]
var remaining = c.args[2:]
var isOpt = strings.HasPrefix(c.args[1], "--") || strings.HasPrefix(c.args[1], "-")
if isOpt {
return execute(c.internal)
}
for _, n := range c.nodes {
if n.name != current {
continue
}
return executeSubnode(&n, remaining)
}
return handleError(c)
}