Skip to content

Commit 9f465af

Browse files
authored
Merge pull request #1497 from Torwang1/main
fix: Context.Set no such flag
2 parents 880a802 + 3005438 commit 9f465af

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

context.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package cli
33
import (
44
"context"
55
"flag"
6+
"fmt"
67
"strings"
78
)
89

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

4748
// Set sets a context flag to a value.
4849
func (cCtx *Context) Set(name, value string) error {
49-
if cCtx.flagSet.Lookup(name) == nil {
50-
cCtx.onInvalidFlag(name)
50+
if fs := cCtx.lookupFlagSet(name); fs != nil {
51+
return fs.Set(name, value)
5152
}
52-
return cCtx.flagSet.Set(name, value)
53+
54+
return fmt.Errorf("no such flag -%s", name)
5355
}
5456

5557
// IsSet determines if the flag was actually set

context_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -643,3 +643,19 @@ func TestCheckRequiredFlags(t *testing.T) {
643643
})
644644
}
645645
}
646+
647+
func TestContext_ParentContext_Set(t *testing.T) {
648+
parentSet := flag.NewFlagSet("parent", flag.ContinueOnError)
649+
parentSet.String("Name", "", "")
650+
651+
context := NewContext(
652+
nil,
653+
flag.NewFlagSet("child", flag.ContinueOnError),
654+
NewContext(nil, parentSet, nil),
655+
)
656+
657+
err := context.Set("Name", "aaa")
658+
if err != nil {
659+
t.Errorf("expect nil. set parent context flag return err: %s", err)
660+
}
661+
}

0 commit comments

Comments
 (0)