-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmds.go
85 lines (69 loc) · 1.96 KB
/
cmds.go
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
package subcmds
import (
"github.com/urfave/cli"
"gitlab.com/ayufan/golang-cli-helpers"
)
type Executor interface {
Execute(c *cli.Context) error
}
type Collection interface {
Commands() []cli.Command
}
type ExecutorWithCommands interface {
Executor
Collection
}
type RegisterableCollection interface {
Collection
RegisterCommand(cmd cli.Command)
Register(name, usage string, flags ...cli.Flag) RegistrationContext
}
type RegistrationContext interface {
Configure(cfg func(cli.Command)) RegistrationContext
Executor(exec Executor)
Commands(coll Collection)
ExecutorWithCommands(execColl ExecutorWithCommands)
}
type collection struct {
commands []cli.Command
}
func NewCollection() RegisterableCollection {
return &collection{[]cli.Command{}}
}
func (c *collection) Commands() []cli.Command {
return c.commands
}
func (c *collection) RegisterCommand(cmd cli.Command) {
c.commands = append(c.commands, cmd)
}
func (c *collection) Register(name, usage string, flags ...cli.Flag) RegistrationContext {
return &context{c, cli.Command{
Name: name,
Usage: usage,
Flags: flags,
}}
}
type context struct {
collection RegisterableCollection
command cli.Command
}
func (c *context) Configure(cfg func(cli.Command)) RegistrationContext {
cfg(c.command)
return c
}
func (c *context) Executor(exec Executor) {
c.command.Flags = append(c.command.Flags, clihelpers.GetFlagsFromStruct(exec)...)
c.command.Action = exec.Execute
c.collection.RegisterCommand(c.command)
}
func (c *context) Commands(coll Collection) {
c.command.Flags = append(c.command.Flags, clihelpers.GetFlagsFromStruct(coll)...)
c.command.Subcommands = coll.Commands()
c.collection.RegisterCommand(c.command)
}
func (c *context) ExecutorWithCommands(execColl ExecutorWithCommands) {
c.command.Flags = append(c.command.Flags, clihelpers.GetFlagsFromStruct(execColl)...)
c.command.Action = execColl.Execute
c.command.Subcommands = execColl.Commands()
c.collection.RegisterCommand(c.command)
}