-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
241 lines (201 loc) · 5.82 KB
/
app.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
package cli
import (
"fmt"
"log/slog"
"github.com/contentforward/structs"
)
var ErrCommandNotFound = fmt.Errorf("command not found")
var ErrNoCommands = fmt.Errorf("no commands registered")
var ErrNoArguments = fmt.Errorf("no arguments provided")
var ErrDisplaySubCommands = fmt.Errorf("print sub commands")
const helpCommand = "help"
type App interface {
Commands() []Command[any]
Add(name string, cmd Command[any]) Command[any]
Run(osArgs []string) error
}
type CLI struct {
settings Settings
globalOptions *GlobalOptions
commands []Command[any]
}
// Unknowns is a struct that holds unknown args and options
// it's a struct for the user to have the ability to
type Unknowns struct {
Args []string
Options map[string]any
}
type Settings struct {
}
type GlobalOptions struct {
Cwd string `arg:"cwd" short:"c" help:"Current working directory"`
Help bool `arg:"help" short:"h" help:"Show help"`
Verbosity int `arg:"v" help:"Verbosity level (0 - quiet, 1 - normal, 2 - verbose)"`
}
func NewApp(settings Settings, opts GlobalOptions) *CLI {
return &CLI{
settings: settings,
globalOptions: &opts,
commands: make([]Command[any], 0),
}
}
var _ App = (*CLI)(nil)
func (c *CLI) Commands() []Command[any] {
return c.commands
}
func (c *CLI) Add(name string, cmd Command[any]) Command[any] {
cmd.Name(name)
c.commands = append(c.commands, cmd)
return cmd
}
func (c *CLI) Run(osArgs []string) error {
if len(c.commands) < 1 {
return ErrNoCommands
}
if len(osArgs) < 1 {
err := c.runHelp(nil)
if err != nil {
return fmt.Errorf("")
}
return nil
}
globalOptions, err := c.getGlobalOptions(osArgs)
if err != nil {
return fmt.Errorf("failed to get command: %w", err)
}
err = mapStructToOptions(c.globalOptions, globalOptions)
if err != nil {
return fmt.Errorf("failed to update global options struct: %w", err)
}
// commandArgs holds the osArgs that are commands
// allArgs holds the osArgs that are not commands
command, commandArgs, allArgs, err := c.matchCommandByArgs(osArgs)
if err != nil {
slog.Error("failed to match command by args", "error", err)
err := c.runHelp(commandArgs)
if err != nil {
return fmt.Errorf("failed to run help: %w", err)
}
return nil
}
commandInputs := command.Options()
commandFields, err := structs.GetStructFields(commandInputs)
if err != nil {
return fmt.Errorf("failed to get struct fields: %w", err)
}
// cmdArgs are the args defined as numeric tags in the struct e.g. `arg:"0"`
// cmdUnknownArgs are the args that are not defined in the struct
// commandOptions are the options defined in the struct e.g. `arg:"cwd"`
// cmdUnknownOptions are the options that are not defined in the struct
cmdArgs, cmdUnknownArgs, commandOptions, cmdUnknownOptions := getCommandArgs(allArgs, commandFields)
unknowns := Unknowns{
Args: cmdUnknownArgs,
Options: cmdUnknownOptions,
}
// fill the options map with the args so that commands can use them
for i, arg := range cmdArgs {
commandOptions[fmt.Sprintf("%d", i)] = arg
}
// if --help is passed, show help
if c.globalOptions.Help {
err := c.runHelp(commandArgs)
if err != nil {
return fmt.Errorf("failed to run help: %w", err)
}
return nil
}
err = mapStructToOptions(commandInputs, commandOptions)
if err != nil {
return fmt.Errorf("failed to map command options: %w", err)
}
err = command.Run(*c.globalOptions, unknowns)
if err != nil {
return fmt.Errorf("failed to run command: %s: %w", command.Name(""), err)
}
return nil
}
func (c *CLI) runHelp(args []string) error {
// slog.Info("running help", "args", args)
for _, cmd := range c.commands {
if cmd.Name("") == helpCommand {
err := cmd.Run(*c.globalOptions, Unknowns{
Args: args,
Options: map[string]any{},
})
if err != nil {
return fmt.Errorf("failed to run help command: %w", err)
}
return nil
}
}
return fmt.Errorf("help command not found")
}
func (c *CLI) getGlobalOptions(osArgs []string) (map[string]any, error) {
globalFields, err := structs.GetStructFields(c.globalOptions)
if err != nil {
return nil, nil
}
// GlobalOptions struct does not accept arguments
// so we use unknownArgs as the processed arguments
_, _, globalOptions, _ := getCommandArgs(osArgs, globalFields)
return globalOptions, nil
}
func (c *CLI) matchCommandByArgs(args []string) (Command[any], []string, []string, error) {
var command Command[any]
var commandNameIndexes []int
for a := 0; a < len(args); a++ {
// previous arg is a command
// assert if this arg is a sub command
if command != nil {
subCommand := c.matchCommandByName(args[a], command.Commands())
if subCommand != nil {
command = subCommand
commandNameIndexes = append(commandNameIndexes, a)
continue
}
// no sub command found, but
// we have a command already so let's keep it and try further args
break
}
cmd := c.matchCommandByName(args[a], c.commands)
if cmd != nil {
command = cmd
commandNameIndexes = append(commandNameIndexes, a)
continue
}
}
if command == nil {
return nil, nil, nil, ErrCommandNotFound
}
// create a new slice that excludes the command args
// we don't need the command args anymore
allOtherArgs := make([]string, 0)
commandNameArgs := make([]string, 0)
for i := 0; i < len(args); i++ {
if exists(commandNameIndexes, i) {
commandNameArgs = append(commandNameArgs, args[i])
continue
}
allOtherArgs = append(allOtherArgs, args[i])
}
return command, commandNameArgs, allOtherArgs, nil
}
func exists(slice []int, val int) bool {
for _, v := range slice {
if v == val {
return true
}
}
return false
}
func (c *CLI) matchCommandByName(arg string, commands []Command[any]) Command[any] {
var command Command[any]
for i := 0; i < len(commands); i++ {
cmd := commands[i]
if cmd.Name("") == arg {
command = cmd
break
}
}
return command
}