Skip to content

Commit

Permalink
fix: Context.Set no such flag
Browse files Browse the repository at this point in the history
  • Loading branch information
torwang committed Sep 20, 2022
1 parent 880a802 commit 3005438
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
8 changes: 5 additions & 3 deletions context.go
Expand Up @@ -3,6 +3,7 @@ package cli
import (
"context"
"flag"
"fmt"
"strings"
)

Expand Down Expand Up @@ -46,10 +47,11 @@ func (cCtx *Context) NumFlags() int {

// Set sets a context flag to a value.
func (cCtx *Context) Set(name, value string) error {
if cCtx.flagSet.Lookup(name) == nil {
cCtx.onInvalidFlag(name)
if fs := cCtx.lookupFlagSet(name); fs != nil {
return fs.Set(name, value)
}
return cCtx.flagSet.Set(name, value)

return fmt.Errorf("no such flag -%s", name)
}

// IsSet determines if the flag was actually set
Expand Down
16 changes: 16 additions & 0 deletions context_test.go
Expand Up @@ -643,3 +643,19 @@ func TestCheckRequiredFlags(t *testing.T) {
})
}
}

func TestContext_ParentContext_Set(t *testing.T) {
parentSet := flag.NewFlagSet("parent", flag.ContinueOnError)
parentSet.String("Name", "", "")

context := NewContext(
nil,
flag.NewFlagSet("child", flag.ContinueOnError),
NewContext(nil, parentSet, nil),
)

err := context.Set("Name", "aaa")
if err != nil {
t.Errorf("expect nil. set parent context flag return err: %s", err)
}
}

0 comments on commit 3005438

Please sign in to comment.