Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Context.Set no such flag #1497

Merged
merged 1 commit into from Sep 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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)
}
}