Skip to content

Commit 01d0e0c

Browse files
committed
up: update the gOpts reset func logic, update some tests
1 parent 7a3fd89 commit 01d0e0c

9 files changed

+118
-65
lines changed

app.go

+7-5
Original file line numberDiff line numberDiff line change
@@ -103,15 +103,18 @@ func NewApp(fns ...func(app *App)) *App {
103103
Desc: "This is my console application",
104104
}
105105

106-
// set a default version
107-
app.Version = "1.0.0"
108-
app.fs = gflag.New("appOpts").WithConfigFn(func(opt *gflag.FlagsConfig) {
106+
app.fs = gflag.New("appOpts").WithConfigFn(func(opt *gflag.Config) {
109107
opt.WithoutType = true
110108
opt.Alignment = gflag.AlignLeft
111109
})
112110

113-
// init base
114111
Logf(VerbCrazy, "create a new cli application, and create base ")
112+
113+
// set a default version
114+
app.Version = "1.0.0"
115+
app.Context = gCtx
116+
117+
// init base
115118
app.base = newBase()
116119
app.opts = newGlobalOpts()
117120

@@ -153,7 +156,6 @@ func (app *App) initialize() {
153156
app.Fire(events.OnAppInitBefore, nil)
154157

155158
// init some info
156-
app.InitCtx()
157159
app.initHelpVars()
158160
app.bindAppOpts()
159161

app_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,7 @@ func TestApp_Run_command_withArguments(t *testing.T) {
234234

235235
err = app.Exec("not-exists", []string{})
236236
is.Err(err)
237-
is.Eq("exec unknown command: 'not-exists'", err.Error())
237+
is.Eq(`exec unknown command "not-exists"`, err.Error())
238238
// other
239239
// app.AddError(fmt.Errorf("test error"))
240240
}

base.go

+25-8
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ func (ctx *Context) Value(key any) any {
5353
}
5454

5555
// InitCtx some common info
56-
func (ctx *Context) InitCtx() {
56+
func (ctx *Context) InitCtx() *Context {
5757
binFile := os.Args[0]
5858
workDir, _ := os.Getwd()
5959

@@ -70,7 +70,7 @@ func (ctx *Context) InitCtx() {
7070
ctx.binFile = binFile
7171
ctx.binName = filepath.Base(binFile)
7272
ctx.argLine = strings.Join(os.Args[1:], " ")
73-
// return ctx
73+
return ctx
7474
}
7575

7676
// PID get pid
@@ -135,6 +135,11 @@ func (ctx *Context) GetVal(key string) interface{} {
135135
return ctx.Get(key)
136136
}
137137

138+
// ResetData from ctx
139+
func (ctx *Context) ResetData() {
140+
ctx.Data = make(maputil.Data)
141+
}
142+
138143
/*************************************************************
139144
* command Base
140145
*************************************************************/
@@ -145,10 +150,10 @@ type base struct {
145150
*Hooks
146151
*Context
147152
color.SimplePrinter
148-
// HelpVars help template vars.
153+
// HelpVars help message replace vars.
149154
helper.HelpVars
150-
// TODO
151-
helpData map[string]any
155+
// TODO tplVars for render help template text.
156+
tplVars map[string]any
152157

153158
// Logo ASCII logo setting
154159
Logo *Logo
@@ -195,8 +200,8 @@ func newBase() base {
195200
// cmdAliases: make(maputil.Aliases),
196201
cmdAliases: structs.NewAliases(aliasNameCheck),
197202
// ExitOnEnd: false,
198-
helpData: make(map[string]any),
199-
Context: NewCtx(),
203+
tplVars: make(map[string]any),
204+
Context: NewCtx(),
200205
}
201206
}
202207

@@ -210,6 +215,13 @@ func (b *base) initHelpVars() {
210215
})
211216
}
212217

218+
// ResetData from ctx
219+
func (b *base) ResetData() {
220+
if b.Context != nil {
221+
b.Context.ResetData()
222+
}
223+
}
224+
213225
// GetCommand get a command by name
214226
func (b *base) GetCommand(name string) *Command {
215227
return b.commands[name]
@@ -330,7 +342,7 @@ func (b *base) FindByPath(path string) *Command {
330342
return b.Match(splitPath2names(path))
331343
}
332344

333-
// MatchByPath command by path. eg. "top:sub" or "top sub"
345+
// MatchByPath command by path. eg: "top:sub" or "top sub"
334346
func (b *base) MatchByPath(path string) *Command {
335347
return b.Match(splitPath2names(path))
336348
}
@@ -381,3 +393,8 @@ func (b *base) CmdAliases() *structs.Aliases {
381393
func (b *base) AliasesMapping() map[string]string {
382394
return b.cmdAliases.Mapping()
383395
}
396+
397+
// AddTplVar to instance.
398+
func (b *base) AddTplVar(key string, val any) {
399+
b.tplVars[key] = val
400+
}

base_test.go

+4-3
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,8 @@ func TestApp_On_CmdNotFound(t *testing.T) {
114114

115115
func TestApp_On_CmdNotFound_redirect(t *testing.T) {
116116
buf.Reset()
117-
simpleCmd.ClearData()
117+
simpleCmd.Init()
118+
simpleCmd.ResetData()
118119
assert.Eq(t, nil, simpleCmd.GetVal("simple"))
119120

120121
cli := newNotExitApp()
@@ -126,9 +127,9 @@ func TestApp_On_CmdNotFound_redirect(t *testing.T) {
126127
buf.WriteString(" - command:" + ctx.Str("name"))
127128
buf.WriteString("; redirect:simple - ")
128129

129-
err := ctx.App.Exec("simple", nil)
130+
err := ctx.App.Exec(simpleCmd.Name, nil)
130131
assert.NoErr(t, err)
131-
buf.WriteString("value:" + simpleCmd.StrValue("simple"))
132+
buf.WriteString("value:" + simpleCmd.Data.Str("simple"))
132133
return true
133134
})
134135

cmd.go

+22-14
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,10 @@ type Command struct {
8282
// path names of the command. 'parent current'
8383
pathNames []string
8484

85+
// command is inject to the App
86+
app *App
87+
root bool // is root command
88+
8589
// Parent parent command
8690
parent *Command
8791

@@ -102,14 +106,11 @@ type Command struct {
102106
// HelpRender custom render cmd help message
103107
HelpRender func(c *Command)
104108

105-
// command is inject to the App
106-
app *App
107-
root bool // is root command
108-
// mark is disabled. if true will skip register to cli-app.
109+
// mark is disabled. if true will skip register to app.
109110
disabled bool
110111
// command is standalone running.
111112
standalone bool
112-
// global option binding on standalone.
113+
// global option binding on standalone. deny error on repeat run.
113114
goptBounded bool
114115
}
115116

@@ -121,16 +122,16 @@ type Command struct {
121122
// // OR with an config func
122123
// cmd := NewCommand("my-cmd", "description", func(c *Command) { ... })
123124
// app.Add(cmd) // OR cmd.AttachTo(app)
124-
func NewCommand(name, desc string, fn ...func(c *Command)) *Command {
125+
func NewCommand(name, desc string, setFn ...func(c *Command)) *Command {
125126
c := &Command{
126127
Name: name,
127128
Desc: desc,
128129
// Flags: *NewFlags(name, desc),
129130
}
130131

131132
// has config func
132-
if len(fn) > 0 {
133-
c.Config = fn[0]
133+
if len(setFn) > 0 {
134+
c.Config = setFn[0]
134135
}
135136

136137
// set name
@@ -240,6 +241,7 @@ func (c *Command) MatchByPath(path string) *Command {
240241

241242
// initialize works for the command
242243
//
244+
// - ctx
243245
// - sub-cmd
244246
func (c *Command) initialize() {
245247
if c.initialized {
@@ -287,17 +289,22 @@ func (c *Command) initialize() {
287289
c.Fire(events.OnCmdInit, nil)
288290
}
289291

290-
// init core
292+
// init base, ctx
291293
func (c *Command) initCommandBase(cName string) {
292294
Logf(VerbCrazy, "init command c.base for the command: %s", cName)
293295

294296
if c.Hooks == nil {
295297
c.Hooks = &Hooks{}
296298
}
297299

298-
binWithPath := c.binName + " " + c.Path()
300+
if c.Context == nil {
301+
Logf(VerbDebug, "cmd: %s - use the gCtx as command context", cName)
302+
c.Context = gCtx
303+
}
299304

300305
c.initHelpVars()
306+
307+
binWithPath := c.binName + " " + c.Path()
301308
c.AddVars(map[string]string{
302309
"cmd": cName,
303310
// binName with command name
@@ -385,10 +392,10 @@ func (c *Command) Run(args []string) (err error) {
385392

386393
// binding global options
387394
if !c.goptBounded {
388-
c.goptBounded = true
389-
Debugf("global options will binding to c.Flags on standalone mode")
395+
Debugf("cmd: %s - binding global options on standalone mode", c.Name)
390396
// bindingCommonGOpts(&c.Flags)
391397
gOpts.bindingFlags(&c.Flags)
398+
c.goptBounded = true
392399
}
393400

394401
// dispatch and parse flags and execute command
@@ -404,8 +411,8 @@ func (c *Command) innerDispatch(args []string) (err error) {
404411
// parse command flags
405412
args, err = c.parseOptions(args)
406413
if err != nil {
407-
// ignore flag.ErrHelp error
408414
if err == flag.ErrHelp {
415+
Debugf("cmd: %s - parse opts return flag.ErrHelp, render command help", c.Name)
409416
c.ShowHelp()
410417
return nil
411418
}
@@ -418,6 +425,7 @@ func (c *Command) innerDispatch(args []string) (err error) {
418425
// remaining args
419426
if c.standalone {
420427
if gOpts.ShowHelp {
428+
Debugf("cmd: %s - gOpts.ShowHelp is True, render command help", c.Name)
421429
c.ShowHelp()
422430
return
423431
}
@@ -568,7 +576,7 @@ func (c *Command) SetParent(parent *Command) {
568576
c.parent = parent
569577
}
570578

571-
// Module name of the grouped command
579+
// ParentName name of the parent command
572580
func (c *Command) ParentName() string {
573581
if c.parent != nil {
574582
return c.parent.Name

cmd_test.go

+31-12
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ var r = &gcli.Command{
194194
},
195195
Func: func(c *gcli.Command, args []string) error {
196196
bf.WriteString("command path: " + c.Path())
197-
dump.Println(c.Path(), args)
197+
// dump.Println(c.Path(), args)
198198
return nil
199199
},
200200
}
@@ -270,7 +270,7 @@ func TestCommand_Run_moreLevelSub(t *testing.T) {
270270
var int0 int
271271
var str0 string
272272

273-
var c0 = gcli.NewCommand("test", "desc test", func(c *gcli.Command) {
273+
var c0 = gcli.NewCommand("test", "desc for test command", func(c *gcli.Command) {
274274
c.IntOpt(&int0, "int", "", 0, "int desc")
275275
c.StrOpt(&str0, "str", "", "", "str desc")
276276
c.AddArg("arg0", "arg0 desc")
@@ -279,15 +279,21 @@ var c0 = gcli.NewCommand("test", "desc test", func(c *gcli.Command) {
279279
bf.WriteString("name=" + c.Name)
280280
c.Set("name", c.Name)
281281
c.Set("args", args)
282-
dump.P(c.ID(), "command Func is exec")
282+
// dump.P(c.ID(), "command Func is exec")
283283
return nil
284284
}
285285
})
286286

287+
func resetCmd(c *gcli.Command) {
288+
c.ResetData()
289+
gcli.ResetGOpts()
290+
}
291+
287292
func TestCommand_Run_emptyArgs(t *testing.T) {
288293
bf.Reset()
289294
is := assert.New(t)
290295

296+
resetCmd(c0)
291297
gcli.SetVerbose(gcli.VerbCrazy)
292298
defer gcli.ResetVerbose()
293299

@@ -302,40 +308,54 @@ func TestCommand_Run_emptyArgs(t *testing.T) {
302308
is.Eq("arg0", c0.Arg("arg0").Name)
303309
}
304310

305-
func TestCommand_Run_parseHelp(t *testing.T) {
306-
bf.Reset()
311+
func TestCommand_Run_XshowHelp1(t *testing.T) {
307312
is := assert.New(t)
308313

314+
bf.Reset()
315+
resetCmd(c0)
316+
gcli.Config(func(opts *gcli.GlobalOpts) {
317+
opts.SetDisable()
318+
})
309319
err := c0.Run([]string{"-h"})
310320
is.NoErr(err)
321+
}
322+
323+
func TestCommand_Run_showHelp2(t *testing.T) {
324+
is := assert.New(t)
325+
326+
bf.Reset()
327+
resetCmd(c0)
311328

312329
// no color
313330
color.Disable()
314331
color.SetOutput(bf)
315332
defer color.ResetOptions()
316333

317-
err = c0.Run([]string{"--help"})
334+
err := c0.Run([]string{"--help"})
335+
is.NoErr(err)
318336
str := bf.String()
319337
is.Contains(str, "Int desc")
320338
is.Contains(str, "--str string")
321339
is.Contains(str, "Str desc")
322340
is.Contains(str, "Display the help information")
323-
is.Contains(str, "arg0 Arg0 desc")
324-
is.Contains(str, "arg1 Arg1 desc")
341+
is.StrContains(str, "Arg0 desc")
342+
is.StrContains(str, "Arg1 desc")
325343
}
326344

327-
func TestCommand_Run_parseOptions(t *testing.T) {
345+
func TestCommand_Run_XparseOptions(t *testing.T) {
328346
bf.Reset()
329347
is := assert.New(t)
330348

331-
gcli.ResetGOpts()
349+
resetCmd(c0)
332350
gcli.SetDebugMode()
333351
defer gcli.ResetVerbose()
334352

335353
is.Eq("test", c0.Name)
336354

355+
dump.P(gcli.GOpts())
337356
err := c0.Run([]string{"--int", "10", "--str=abc", "txt"})
338357

358+
dump.P(gcli.GOpts(), c0.Context)
339359
is.NoErr(err)
340360
is.Eq("test", c0.Get("name"))
341361
is.Eq([]string{"txt"}, c0.Get("args"))
@@ -355,8 +375,7 @@ func TestCommand_Run_parseOptions(t *testing.T) {
355375
c.IntOpt(&int0, "int", "", 0, "desc")
356376
c.IntOpt(&co.maxSteps, "max-step", "", 0, "setting the max step value")
357377
c.AddArg("arg0", "arg0 desc")
358-
})
359-
c1.SetFunc(func(c *gcli.Command, args []string) error {
378+
}).WithFunc(func(c *gcli.Command, args []string) error {
360379
is.Eq("[txt]", fmt.Sprint(args))
361380
return nil
362381
})

0 commit comments

Comments
 (0)