From 8bd5fb2390f6b8a4f2cba2376302cce8a545d5e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tilo=20Pr=C3=BCtz?= Date: Fri, 22 Apr 2022 16:10:09 +0200 Subject: [PATCH] GenericFlag.ValueFromContext() as convenient accessor --- flag_generic.go | 5 +++++ flag_test.go | 8 ++++++++ 2 files changed, 13 insertions(+) diff --git a/flag_generic.go b/flag_generic.go index d159507..483c7d1 100644 --- a/flag_generic.go +++ b/flag_generic.go @@ -104,6 +104,11 @@ func (f GenericFlag) Apply(set *flag.FlagSet) error { return nil } +// ValueFromContext returns the flag’s value in the given Context. +func (f *GenericFlag) ValueFromContext(ctx *Context) interface{} { + return ctx.Generic(f.Name) +} + // Generic looks up the value of a local GenericFlag, returns // nil if not found func (c *Context) Generic(name string) interface{} { diff --git a/flag_test.go b/flag_test.go index ce9b5a3..7fa6673 100644 --- a/flag_test.go +++ b/flag_test.go @@ -1173,6 +1173,14 @@ func TestGenericFlagApply_SetsAllNames(t *testing.T) { expect(t, err, nil) } +func TestGenericFlagValueFromContext(t *testing.T) { + set := flag.NewFlagSet("test", 0) + set.Var(&Parser{"abc", "def"}, "myflag", "doc") + ctx := NewContext(nil, set, nil) + f := &GenericFlag{Name: "myflag"} + expect(t, f.ValueFromContext(ctx), &Parser{"abc", "def"}) +} + func TestParseMultiString(t *testing.T) { _ = (&App{ Flags: []Flag{