-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathengine.go
More file actions
86 lines (74 loc) · 1.55 KB
/
Copy pathengine.go
File metadata and controls
86 lines (74 loc) · 1.55 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
package stdcli
import (
"context"
"fmt"
"os"
"runtime/pprof"
"strings"
)
type Engine struct {
Commands []Command
Executor Executor
Name string
Profile string
Reader *Reader
Settings string
Version string
Writer *Writer
}
func (e *Engine) Command(command, description string, fn HandlerFunc, opts CommandOptions) {
e.Commands = append(e.Commands, Command{
Command: strings.Split(command, " "),
Description: description,
Handler: fn,
Flags: opts.Flags,
Invisible: opts.Invisible,
Usage: opts.Usage,
Validate: opts.Validate,
engine: e,
})
}
func (e *Engine) Execute(args []string) int {
if e.Profile != "" {
f, err := os.Create(e.Profile)
if err != nil {
panic(fmt.Sprintf("could not create profile: %s", e.Profile))
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
return e.ExecuteContext(ctx, args)
}
func (e *Engine) ExecuteContext(ctx context.Context, args []string) int {
if len(args) > 0 && (args[0] == "-v" || args[0] == "--version") {
fmt.Println(e.Version)
return 0
}
var m *Command
var cargs []string
for _, c := range e.Commands {
d := c
if a, ok := d.Match(args); ok {
if m == nil || len(m.Command) < len(c.Command) {
m = &d
cargs = a
}
}
}
if m == nil {
m = &(e.Commands[0])
}
err := m.ExecuteContext(ctx, cargs)
switch t := err.(type) {
case nil:
return 0
case ExitCoder:
return t.Code()
default:
e.Writer.Errorf("%s", t)
return 1
}
return 0
}