Skip to content

Commit

Permalink
Merge pull request #1497 from Torwang1/main
Browse files Browse the repository at this point in the history
fix: Context.Set no such flag
  • Loading branch information
dearchap committed Sep 21, 2022
2 parents 880a802 + 3005438 commit 9f465af
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 9f465af

Please sign in to comment.