-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcommand.go
More file actions
103 lines (83 loc) · 1.85 KB
/
Copy pathcommand.go
File metadata and controls
103 lines (83 loc) · 1.85 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
package stdcli
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/spf13/pflag"
)
type Command struct {
Command []string
Description string
Flags []Flag
Invisible bool
Handler HandlerFunc
Usage string
Validate Validator
engine *Engine
}
type CommandOptions struct {
Flags []Flag
Invisible bool
Usage string
Validate Validator
}
type HandlerFunc func(*Context) error
// func (c *Command) Execute(args []string) error {
// ctx, cancel := context.WithCancel(context.Background())
// defer cancel()
// return c.ExecuteContext(ctx, args)
// }
func (c *Command) ExecuteContext(ctx context.Context, args []string) error {
fs := pflag.NewFlagSet("", pflag.ContinueOnError)
fs.Usage = func() { helpCommand(c.engine, c) }
flags := []*Flag{}
for _, f := range c.Flags {
g := f
flags = append(flags, &g)
flag := fs.VarPF(&g, f.Name, f.Short, f.Description)
if f.Type() == "bool" {
flag.NoOptDefVal = "true"
}
}
if err := fs.Parse(args); err != nil {
if strings.HasPrefix(err.Error(), "unknown shorthand flag") {
parts := strings.Split(err.Error(), " ")
return fmt.Errorf("unknown flag: %s", parts[len(parts)-1])
}
if err == pflag.ErrHelp {
return nil
}
return err
}
cc := &Context{
Context: ctx,
Args: fs.Args(),
Flags: flags,
engine: c.engine,
}
if c.Validate != nil {
if err := c.Validate(cc); err != nil {
return err
}
}
if err := c.Handler(cc); err != nil {
return err
}
return nil
}
func (c *Command) FullCommand() string {
return filepath.Base(os.Args[0]) + " " + strings.Join(c.Command, " ")
}
func (c *Command) Match(args []string) ([]string, bool) {
if len(args) < len(c.Command) {
return args, false
}
for i := range c.Command {
if args[i] != c.Command[i] {
return args, false
}
}
return args[len(c.Command):], true
}