Skip to content

Commit

Permalink
up: update the gOpts reset func logic, update some tests
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Sep 29, 2022
1 parent 7a3fd89 commit 01d0e0c
Show file tree
Hide file tree
Showing 9 changed files with 118 additions and 65 deletions.
12 changes: 7 additions & 5 deletions app.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,15 +103,18 @@ func NewApp(fns ...func(app *App)) *App {
Desc: "This is my console application",
}

// set a default version
app.Version = "1.0.0"
app.fs = gflag.New("appOpts").WithConfigFn(func(opt *gflag.FlagsConfig) {
app.fs = gflag.New("appOpts").WithConfigFn(func(opt *gflag.Config) {
opt.WithoutType = true
opt.Alignment = gflag.AlignLeft
})

// init base
Logf(VerbCrazy, "create a new cli application, and create base ")

// set a default version
app.Version = "1.0.0"
app.Context = gCtx

// init base
app.base = newBase()
app.opts = newGlobalOpts()

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

// init some info
app.InitCtx()
app.initHelpVars()
app.bindAppOpts()

Expand Down
2 changes: 1 addition & 1 deletion app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ func TestApp_Run_command_withArguments(t *testing.T) {

err = app.Exec("not-exists", []string{})
is.Err(err)
is.Eq("exec unknown command: 'not-exists'", err.Error())
is.Eq(`exec unknown command "not-exists"`, err.Error())
// other
// app.AddError(fmt.Errorf("test error"))
}
Expand Down
33 changes: 25 additions & 8 deletions base.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func (ctx *Context) Value(key any) any {
}

// InitCtx some common info
func (ctx *Context) InitCtx() {
func (ctx *Context) InitCtx() *Context {
binFile := os.Args[0]
workDir, _ := os.Getwd()

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

// PID get pid
Expand Down Expand Up @@ -135,6 +135,11 @@ func (ctx *Context) GetVal(key string) interface{} {
return ctx.Get(key)
}

// ResetData from ctx
func (ctx *Context) ResetData() {
ctx.Data = make(maputil.Data)
}

/*************************************************************
* command Base
*************************************************************/
Expand All @@ -145,10 +150,10 @@ type base struct {
*Hooks
*Context
color.SimplePrinter
// HelpVars help template vars.
// HelpVars help message replace vars.
helper.HelpVars
// TODO
helpData map[string]any
// TODO tplVars for render help template text.
tplVars map[string]any

// Logo ASCII logo setting
Logo *Logo
Expand Down Expand Up @@ -195,8 +200,8 @@ func newBase() base {
// cmdAliases: make(maputil.Aliases),
cmdAliases: structs.NewAliases(aliasNameCheck),
// ExitOnEnd: false,
helpData: make(map[string]any),
Context: NewCtx(),
tplVars: make(map[string]any),
Context: NewCtx(),
}
}

Expand All @@ -210,6 +215,13 @@ func (b *base) initHelpVars() {
})
}

// ResetData from ctx
func (b *base) ResetData() {
if b.Context != nil {
b.Context.ResetData()
}
}

// GetCommand get a command by name
func (b *base) GetCommand(name string) *Command {
return b.commands[name]
Expand Down Expand Up @@ -330,7 +342,7 @@ func (b *base) FindByPath(path string) *Command {
return b.Match(splitPath2names(path))
}

// MatchByPath command by path. eg. "top:sub" or "top sub"
// MatchByPath command by path. eg: "top:sub" or "top sub"
func (b *base) MatchByPath(path string) *Command {
return b.Match(splitPath2names(path))
}
Expand Down Expand Up @@ -381,3 +393,8 @@ func (b *base) CmdAliases() *structs.Aliases {
func (b *base) AliasesMapping() map[string]string {
return b.cmdAliases.Mapping()
}

// AddTplVar to instance.
func (b *base) AddTplVar(key string, val any) {
b.tplVars[key] = val
}
7 changes: 4 additions & 3 deletions base_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,8 @@ func TestApp_On_CmdNotFound(t *testing.T) {

func TestApp_On_CmdNotFound_redirect(t *testing.T) {
buf.Reset()
simpleCmd.ClearData()
simpleCmd.Init()
simpleCmd.ResetData()
assert.Eq(t, nil, simpleCmd.GetVal("simple"))

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

err := ctx.App.Exec("simple", nil)
err := ctx.App.Exec(simpleCmd.Name, nil)
assert.NoErr(t, err)
buf.WriteString("value:" + simpleCmd.StrValue("simple"))
buf.WriteString("value:" + simpleCmd.Data.Str("simple"))
return true
})

Expand Down
36 changes: 22 additions & 14 deletions cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,10 @@ type Command struct {
// path names of the command. 'parent current'
pathNames []string

// command is inject to the App
app *App
root bool // is root command

// Parent parent command
parent *Command

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

// command is inject to the App
app *App
root bool // is root command
// mark is disabled. if true will skip register to cli-app.
// mark is disabled. if true will skip register to app.
disabled bool
// command is standalone running.
standalone bool
// global option binding on standalone.
// global option binding on standalone. deny error on repeat run.
goptBounded bool
}

Expand All @@ -121,16 +122,16 @@ type Command struct {
// // OR with an config func
// cmd := NewCommand("my-cmd", "description", func(c *Command) { ... })
// app.Add(cmd) // OR cmd.AttachTo(app)
func NewCommand(name, desc string, fn ...func(c *Command)) *Command {
func NewCommand(name, desc string, setFn ...func(c *Command)) *Command {
c := &Command{
Name: name,
Desc: desc,
// Flags: *NewFlags(name, desc),
}

// has config func
if len(fn) > 0 {
c.Config = fn[0]
if len(setFn) > 0 {
c.Config = setFn[0]
}

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

// initialize works for the command
//
// - ctx
// - sub-cmd
func (c *Command) initialize() {
if c.initialized {
Expand Down Expand Up @@ -287,17 +289,22 @@ func (c *Command) initialize() {
c.Fire(events.OnCmdInit, nil)
}

// init core
// init base, ctx
func (c *Command) initCommandBase(cName string) {
Logf(VerbCrazy, "init command c.base for the command: %s", cName)

if c.Hooks == nil {
c.Hooks = &Hooks{}
}

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

c.initHelpVars()

binWithPath := c.binName + " " + c.Path()
c.AddVars(map[string]string{
"cmd": cName,
// binName with command name
Expand Down Expand Up @@ -385,10 +392,10 @@ func (c *Command) Run(args []string) (err error) {

// binding global options
if !c.goptBounded {
c.goptBounded = true
Debugf("global options will binding to c.Flags on standalone mode")
Debugf("cmd: %s - binding global options on standalone mode", c.Name)
// bindingCommonGOpts(&c.Flags)
gOpts.bindingFlags(&c.Flags)
c.goptBounded = true
}

// dispatch and parse flags and execute command
Expand All @@ -404,8 +411,8 @@ func (c *Command) innerDispatch(args []string) (err error) {
// parse command flags
args, err = c.parseOptions(args)
if err != nil {
// ignore flag.ErrHelp error
if err == flag.ErrHelp {
Debugf("cmd: %s - parse opts return flag.ErrHelp, render command help", c.Name)
c.ShowHelp()
return nil
}
Expand All @@ -418,6 +425,7 @@ func (c *Command) innerDispatch(args []string) (err error) {
// remaining args
if c.standalone {
if gOpts.ShowHelp {
Debugf("cmd: %s - gOpts.ShowHelp is True, render command help", c.Name)
c.ShowHelp()
return
}
Expand Down Expand Up @@ -568,7 +576,7 @@ func (c *Command) SetParent(parent *Command) {
c.parent = parent
}

// Module name of the grouped command
// ParentName name of the parent command
func (c *Command) ParentName() string {
if c.parent != nil {
return c.parent.Name
Expand Down
43 changes: 31 additions & 12 deletions cmd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ var r = &gcli.Command{
},
Func: func(c *gcli.Command, args []string) error {
bf.WriteString("command path: " + c.Path())
dump.Println(c.Path(), args)
// dump.Println(c.Path(), args)
return nil
},
}
Expand Down Expand Up @@ -270,7 +270,7 @@ func TestCommand_Run_moreLevelSub(t *testing.T) {
var int0 int
var str0 string

var c0 = gcli.NewCommand("test", "desc test", func(c *gcli.Command) {
var c0 = gcli.NewCommand("test", "desc for test command", func(c *gcli.Command) {
c.IntOpt(&int0, "int", "", 0, "int desc")
c.StrOpt(&str0, "str", "", "", "str desc")
c.AddArg("arg0", "arg0 desc")
Expand All @@ -279,15 +279,21 @@ var c0 = gcli.NewCommand("test", "desc test", func(c *gcli.Command) {
bf.WriteString("name=" + c.Name)
c.Set("name", c.Name)
c.Set("args", args)
dump.P(c.ID(), "command Func is exec")
// dump.P(c.ID(), "command Func is exec")
return nil
}
})

func resetCmd(c *gcli.Command) {
c.ResetData()
gcli.ResetGOpts()
}

func TestCommand_Run_emptyArgs(t *testing.T) {
bf.Reset()
is := assert.New(t)

resetCmd(c0)
gcli.SetVerbose(gcli.VerbCrazy)
defer gcli.ResetVerbose()

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

func TestCommand_Run_parseHelp(t *testing.T) {
bf.Reset()
func TestCommand_Run_XshowHelp1(t *testing.T) {
is := assert.New(t)

bf.Reset()
resetCmd(c0)
gcli.Config(func(opts *gcli.GlobalOpts) {
opts.SetDisable()
})
err := c0.Run([]string{"-h"})
is.NoErr(err)
}

func TestCommand_Run_showHelp2(t *testing.T) {
is := assert.New(t)

bf.Reset()
resetCmd(c0)

// no color
color.Disable()
color.SetOutput(bf)
defer color.ResetOptions()

err = c0.Run([]string{"--help"})
err := c0.Run([]string{"--help"})
is.NoErr(err)
str := bf.String()
is.Contains(str, "Int desc")
is.Contains(str, "--str string")
is.Contains(str, "Str desc")
is.Contains(str, "Display the help information")
is.Contains(str, "arg0 Arg0 desc")
is.Contains(str, "arg1 Arg1 desc")
is.StrContains(str, "Arg0 desc")
is.StrContains(str, "Arg1 desc")
}

func TestCommand_Run_parseOptions(t *testing.T) {
func TestCommand_Run_XparseOptions(t *testing.T) {
bf.Reset()
is := assert.New(t)

gcli.ResetGOpts()
resetCmd(c0)
gcli.SetDebugMode()
defer gcli.ResetVerbose()

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

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

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

0 comments on commit 01d0e0c

Please sign in to comment.