-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun.go
More file actions
108 lines (90 loc) · 2.29 KB
/
run.go
File metadata and controls
108 lines (90 loc) · 2.29 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 cli_utils
import (
"fmt"
"os"
"strings"
)
func (c *CLI) getRuntimeArgs(argsWithoutProg []string) (RuntimeArgs, error) {
args := RuntimeArgs{}
for _, item := range argsWithoutProg[1:] {
if item[0] != '-' || item[1] != '-' || !strings.Contains(item, "=") || item[3] == '=' || len(item) < 5 {
return nil, fmt.Errorf("invalid argument %s", item)
}
key := item[2:strings.Index(item, "=")]
value := item[strings.Index(item, "=")+1:]
if value == "" {
return nil, fmt.Errorf("invalid value for argument %s", key)
}
args[key] = value
}
return args, nil
}
func (c *CLI) checkRuntimeArgs(commandName string, args *RuntimeArgs) error {
command := c.GetCommand(commandName)
for k, _ := range *args {
isMissing := command.Args.isMissing(k)
if isMissing {
return fmt.Errorf("argument %s is not supported for command %s", k, command.Name)
}
}
commandArgs := command.Args
for _, a := range commandArgs {
_, ok := (*args)[a.Name]
if !ok && a.Required {
return fmt.Errorf("argument %s is required", a.Name)
}
if !ok {
(*args)[a.Name] = a.Default
}
}
for _, a := range commandArgs {
if a.Check != nil {
err := a.Check(&a, (*args)[a.Name].(string))
if err != nil {
return err
}
}
}
return nil
}
func (c *CLI) Run() error {
runtimeArgs := RuntimeArgs{}
c.Commands = append(c.Commands, *c.DefaultCommand)
argsWithoutProg := os.Args[1:]
if len(argsWithoutProg) == 0 {
return c.DefaultCommand.Run(runtimeArgs, c)
}
command := argsWithoutProg[0]
if !c.HasCommand(command) {
fmt.Printf("Command %s is not supported\n", command)
return c.DefaultCommand.Run(runtimeArgs, c)
}
runtimeArgs, err := c.getRuntimeArgs(argsWithoutProg)
if err != nil {
return err
}
err = c.checkRuntimeArgs(command, &runtimeArgs)
if err != nil {
return err
}
fmt.Println("Running command", command)
for _, com := range c.Commands {
if com.Name == command {
err := com.Run(runtimeArgs, c)
if com.CleanUp != nil {
fmt.Printf("Running cleanup for command %s", command)
cleanUpErr := com.CleanUp(runtimeArgs, c)
if err != nil && cleanUpErr != nil {
return fmt.Errorf("run error: %v, cleanup error: %v", err, cleanUpErr)
}
if cleanUpErr != nil {
return cleanUpErr
}
}
if err != nil {
return err
}
}
}
return nil
}