-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand.go
More file actions
101 lines (81 loc) · 2.32 KB
/
command.go
File metadata and controls
101 lines (81 loc) · 2.32 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
package command
import "fmt"
type CommandHandle = func(cmd *SCommand)
type SCommand struct {
Name string `json:"name"`
Description string `json:"description"`
Summary string `json:"summary"`
Args []ICommandArgValue `json:"args"`
Flags []ICommandFlagValue `json:"flags"`
SubCommand []*SCommand `json:"subCommand"`
Handle CommandHandle `json:"-"`
}
type ICommand interface {
ChangeName(name string) *SCommand
ChangeDescription(description string) *SCommand
ChangeSummary(summary string) *SCommand
AddArgs(args ...*SCommandArg[any]) *SCommand
AddFlags(flags ...*SCommandFlag[any]) *SCommand
AddSubCommand(subCommand ...*SCommand) *SCommand
RegisterHandler(handle CommandHandle) *SCommand
GetArgsCount(onlyEmpty bool) int
}
func (cmd *SCommand) ChangeName(name string) *SCommand {
cmd.Name = name
return cmd
}
func (cmd *SCommand) ChangeDescription(description string) *SCommand {
cmd.Description = description
return cmd
}
func (cmd *SCommand) ChangeSummary(summary string) *SCommand {
cmd.Summary = summary
return cmd
}
func (cmd *SCommand) AddArgs(args ...ICommandArgValue) *SCommand {
cmd.Args = append(cmd.Args, args...)
flag := false
for i, arg := range cmd.Args {
arg.SetIndex(i)
if flag {
panic(fmt.Sprintf("command '%s': empty argument '%s' (index %d) appears after non-empty argument; all optional args must follow required ones", cmd.Name, arg.GetName(), i))
}
if arg.GetValue() == nil {
flag = true
}
}
return cmd
}
func (cmd *SCommand) AddFlags(flags ...ICommandFlagValue) *SCommand {
cmd.Flags = append(cmd.Flags, flags...)
return cmd
}
func (cmd *SCommand) AddSubCommand(subCommand ...*SCommand) *SCommand {
cmd.SubCommand = append(cmd.SubCommand, subCommand...)
return cmd
}
func (cmd *SCommand) GetArgsCount(onlyEmpty bool) int {
count := 0
for _, arg := range cmd.Args {
if !onlyEmpty && arg.GetValue() != nil {
continue
}
count++
}
return count
}
func (cmd *SCommand) RegisterHandler(handle CommandHandle) *SCommand {
cmd.Handle = handle
return cmd
}
func NewCommand(name string) *SCommand {
return &SCommand{
Name: name,
Description: "",
Summary: "",
Args: []ICommandArgValue{},
Flags: []ICommandFlagValue{},
SubCommand: []*SCommand{},
Handle: nil,
}
}