-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathapplication.go
429 lines (389 loc) · 7.97 KB
/
application.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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
package xcli
import (
"errors"
"fmt"
"github.com/mix-go/xcli/argv"
"github.com/mix-go/xcli/flag"
"os"
"strings"
)
var (
// App
iApp *application
)
func init() {
iApp = New("app", "0.0.0")
}
// New
func New(name, version string) *application {
app := &application{
Name: name,
Version: version,
}
app.BasePath = argv.Program().Dir
return app
}
// App
func App() *application {
return iApp
}
// SetName
func SetName(name string) *application {
return iApp.SetName(name)
}
// SetVersion
func SetVersion(version string) *application {
return iApp.SetVersion(version)
}
// SetDebug
func SetDebug(debug bool) *application {
return iApp.SetDebug(debug)
}
// Use
func Use(h ...HandlerFunc) *application {
return iApp.Use(h...)
}
// AddCommand
func AddCommand(cmds ...*Command) *application {
iApp.AddCommand(cmds...)
return iApp
}
// Run
func Run() {
iApp.Run()
}
// application
type application struct {
// 应用名称
Name string
// 应用版本
Version string
// 应用调试
Debug bool
// 基础路径
BasePath string
// 是否单命令
singleton bool
// 默认命令
defaultCommand string
// 命令集合
commands []*Command
// handlers
handlers []HandlerFunc
}
// HandlerFunc
type HandlerFunc func(next func())
// SetName
func (t *application) SetName(name string) *application {
t.Name = name
return t
}
// SetVersion
func (t *application) SetVersion(version string) *application {
t.Version = version
return t
}
// SetDebug
func (t *application) SetDebug(debug bool) *application {
t.Debug = debug
return t
}
// Use
func (t *application) Use(h ...HandlerFunc) *application {
t.handlers = append(t.handlers, h...)
return t
}
// AddCommand
func (t *application) AddCommand(cmds ...*Command) *application {
t.commands = append(t.commands, cmds...)
// init
for _, c := range t.commands {
if c.Singleton {
t.singleton = true
}
if c.Default {
t.defaultCommand = c.Name
}
}
if t.singleton {
argv.Parse(true)
flag.Parse()
}
return t
}
// Run 执行
func (t *application) Run() {
defer func() {
if err := recover(); err != nil {
switch err.(type) {
case *NotFoundError, *UnsupportedError:
fmt.Println(err)
return
default:
panic(err)
}
}
}()
if len(t.commands) == 0 {
panic(errors.New("command cannot be empty"))
}
command := argv.Command()
if command == "" {
if flag.Match("h", "help").Bool(false) {
t.globalHelp()
return
}
if flag.Match("v", "version").Bool(false) {
t.version()
return
}
options := flag.Options().Map()
if len(options) == 0 {
if t.defaultCommand != "" && len(os.Args) == 1 {
os.Args = append(os.Args, t.defaultCommand)
argv.Parse()
flag.Parse()
t.Run()
} else {
t.globalHelp()
}
return
}
if t.singleton {
t.call()
return
}
f := ""
for k := range options {
f = k
break
}
p := argv.Program().Path
panic(NewNotFoundError(fmt.Errorf("flag provided but not defined: '%s', see '%s --help'.", f, p)))
} else if flag.Match("help").Bool(false) {
t.commandHelp()
return
}
t.call()
}
func (t *application) getCommand(n string) *Command {
var cmd *Command
if t.singleton {
// 单命令
for _, c := range t.commands {
if c.Singleton {
cmd = c
break
}
}
} else {
for _, c := range t.commands {
if c.Name == n {
cmd = c
break
}
}
}
return cmd
}
// 执行命令
func (t *application) call() {
// 命令行选项效验
t.validateOptions()
// 提取命令
command := argv.Command()
cmd := t.getCommand(command)
if cmd == nil {
panic(NewNotFoundError(fmt.Errorf("'%s' is not command, see '%s --help'.", command, argv.Program().Path)))
}
if cmd.RunF == nil && cmd.RunI == nil {
panic(fmt.Errorf("'%s' command RunF & RunI field is empty", cmd.Name))
}
// 执行命令
exec := func() {
rf := cmd.RunF
if rf != nil {
rf()
return
}
ri := cmd.RunI
if ri != nil {
ri.Main()
return
}
}
if len(t.handlers)+len(cmd.handlers) > 0 {
tmp := append(t.handlers, cmd.handlers...)
for i, j := 0, len(tmp)-1; i < j; i, j = i+1, j-1 {
tmp[i], tmp[j] = tmp[j], tmp[i]
}
var next func()
for k, f := range tmp {
if k == 0 {
n := exec
c := f
next = func() {
c(n)
}
if len(tmp) == 1 {
c(n)
}
} else if len(tmp)-1 == k {
f(next)
} else {
n := next
c := f
next = func() {
c(n)
}
}
}
} else {
exec()
}
}
// 命令行选项效验
func (t *application) validateOptions() {
command := argv.Command()
cmd := t.getCommand(command)
if cmd == nil {
return
}
options := cmd.Options
if len(options) == 0 {
return
}
var flags []string
for _, o := range options {
for _, v := range o.Names {
if len(v) == 1 {
flags = append(flags, fmt.Sprintf("-%s", v))
} else {
flags = append(flags, fmt.Sprintf("--%s", v))
}
}
}
inArray := func(value string, values []string) bool {
for _, v := range values {
if v == value {
return true
}
}
return false
}
for f := range flag.Options().Map() {
if !inArray(f, flags) {
p := argv.Program().Path
c := argv.Command()
if c != "" {
c = fmt.Sprintf(" %s", c)
}
panic(NewNotFoundError(fmt.Errorf("flag provided but not defined: '%s', see '%s%s --help'.", f, p, c)))
}
}
}
// 全局帮助
func (t *application) globalHelp() {
command := argv.Command()
cmd := t.getCommand(command)
if command != "" && cmd == nil {
panic(NewNotFoundError(fmt.Errorf("'%s' is not command, see '%s --help'.", command, argv.Program().Path)))
}
if cmd != nil && cmd.Long != "" {
fmt.Println(cmd.Long)
fmt.Println("")
}
program := argv.Program().Path
if !t.singleton {
fmt.Println(fmt.Sprintf("Usage: %s [GLOBAL OPTIONS] COMMAND [ARG...]", program))
} else {
if cmd != nil && cmd.UsageFormat != "" {
fmt.Println(fmt.Sprintf(cmd.UsageFormat, program))
} else {
fmt.Println(fmt.Sprintf("Usage: %s [ARG...]", program))
}
}
if !t.singleton {
t.printCommands()
} else {
t.printCommandOptions()
}
t.printGlobalOptions()
fmt.Println("")
fg := ""
if !t.singleton {
fg = " COMMAND"
}
fmt.Println(fmt.Sprintf("Run '%s%s --help' for more information on a command.", program, fg))
fmt.Println("")
fmt.Println("Developed with Mix Go framework. (openmix.org/mix-go)")
}
// 命令帮助
func (t *application) commandHelp() {
command := argv.Command()
cmd := t.getCommand(command)
if cmd == nil {
panic(NewNotFoundError(fmt.Errorf("'%s' is not command, see '%s --help'.", command, argv.Program().Path)))
}
if cmd.Long != "" {
fmt.Println(cmd.Long)
fmt.Println("")
}
program := argv.Program().Path
if cmd.UsageFormat != "" {
fmt.Println(fmt.Sprintf(cmd.UsageFormat, program, command))
} else {
fmt.Println(fmt.Sprintf("Usage: %s %s [ARG...]", program, command))
}
t.printCommandOptions()
fmt.Println("")
fmt.Println("Developed with Mix Go framework. (openmix.org/mix-go)")
}
// 打印全局选项
func (t *application) printGlobalOptions() {
tabs := "\t"
fmt.Println("")
fmt.Println("Global Options:")
fmt.Println(fmt.Sprintf(" -h, --help%sPrint usage", tabs))
fmt.Println(fmt.Sprintf(" -v, --version%sPrint version information", tabs))
}
// 打印命令
func (t *application) printCommands() {
fmt.Println("")
fmt.Println("Commands:")
for _, v := range t.commands {
command := v.Name
short := v.Short
fmt.Println(fmt.Sprintf(" %s\t%s", command, short))
}
}
// 打印命令选项
func (t *application) printCommandOptions() {
command := argv.Command()
cmd := t.getCommand(command)
if cmd == nil {
return
}
options := cmd.Options
if len(options) == 0 {
return
}
fmt.Println("")
fmt.Println("Command Options:")
for _, o := range options {
var flags []string
for _, v := range o.Names {
if len(v) == 1 {
flags = append(flags, fmt.Sprintf("-%s", v))
} else {
flags = append(flags, fmt.Sprintf("--%s", v))
}
}
fg := strings.Join(flags, ", ")
fmt.Println(fmt.Sprintf(" %s\t%s", fg, o.Usage))
}
}
// 版本号
func (t *application) version() {
fmt.Println(fmt.Sprintf("%s %s", t.Name, t.Version))
}