From 8c8db478f8d68c4c4c4d887495213ca4578f92c2 Mon Sep 17 00:00:00 2001 From: Joe Gregorio Date: Sat, 5 Dec 2020 21:39:34 -0500 Subject: [PATCH 1/2] Fix Context.Value. Before this change the added test would crash on a nil pointer dereference because the original code would only look in the local fileSet and not across all the fileSets. --- context.go | 5 ++++- context_test.go | 11 +++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/context.go b/context.go index 74ed51912e..65e0d1e4cb 100644 --- a/context.go +++ b/context.go @@ -108,7 +108,10 @@ func (c *Context) Lineage() []*Context { // Value returns the value of the flag corresponding to `name` func (c *Context) Value(name string) interface{} { - return c.flagSet.Lookup(name).Value.(flag.Getter).Get() + if fs := lookupFlagSet(name, c); fs != nil { + return fs.Lookup(name).Value.(flag.Getter).Get() + } + return nil } // Args returns the command line arguments associated with the context. diff --git a/context_test.go b/context_test.go index 61d6268452..335b071790 100644 --- a/context_test.go +++ b/context_test.go @@ -136,6 +136,17 @@ func TestContext_Bool(t *testing.T) { expect(t, c.Bool("top-flag"), true) } +func TestContext_Value(t *testing.T) { + set := flag.NewFlagSet("test", 0) + set.Int("myflag", 12, "doc") + parentSet := flag.NewFlagSet("test", 0) + parentSet.Int("top-flag", 13, "doc") + parentCtx := NewContext(nil, parentSet, nil) + c := NewContext(nil, set, parentCtx) + expect(t, c.Value("myflag"), 12) + expect(t, c.Value("top-flag"), 13) +} + func TestContext_Args(t *testing.T) { set := flag.NewFlagSet("test", 0) set.Bool("myflag", false, "doc") From 30e6347621df9bad1af0c91a2c7c1ba729680ec9 Mon Sep 17 00:00:00 2001 From: Joe Gregorio Date: Sat, 5 Dec 2020 21:59:56 -0500 Subject: [PATCH 2/2] Add test for the else path. --- context_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/context_test.go b/context_test.go index 335b071790..35feefedec 100644 --- a/context_test.go +++ b/context_test.go @@ -145,6 +145,7 @@ func TestContext_Value(t *testing.T) { c := NewContext(nil, set, parentCtx) expect(t, c.Value("myflag"), 12) expect(t, c.Value("top-flag"), 13) + expect(t, c.Value("unknown-flag"), nil) } func TestContext_Args(t *testing.T) {