-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcommand.go
More file actions
70 lines (56 loc) · 1.08 KB
/
command.go
File metadata and controls
70 lines (56 loc) · 1.08 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
package main
import (
"fmt"
"os"
)
type Command struct {
Name string
Usage string
Run func(args []string)
subcommands map[string]*Command
}
func (c *Command) AddCommand(cmds ...*Command) {
if c.subcommands == nil {
c.subcommands = map[string]*Command{}
}
for _, cmd := range cmds {
c.subcommands[cmd.Name] = cmd
}
}
func (c *Command) printHelp() {
fmt.Println(c.Usage)
fmt.Println("\nUsage:")
fmt.Printf(" %s [command]\n", c.Name)
if len(c.subcommands) > 0 {
fmt.Println("\nAvailable Commands:")
for _, cmd := range c.subcommands {
fmt.Printf(" %s\t%s\n", cmd.Name, cmd.Usage)
}
}
}
func (c *Command) execute(args []string) {
if len(args) == 0 {
c.printHelp()
return
}
cmdStr := args[0]
if cmdStr == "help" {
c.printHelp()
return
}
command, exists := c.subcommands[cmdStr]
if !exists {
fmt.Println("Command doesn't exist:", cmdStr, "\n")
c.printHelp()
return
}
if command.Run == nil {
command.execute(args[1:])
return
}
command.Run(args[1:])
}
func (c *Command) Execute() {
args := os.Args[1:]
c.execute(args)
}