From ce4d9279c42ef762256900e52a58f8cc3ad48b08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tilo=20Pr=C3=BCtz?= Date: Fri, 22 Apr 2022 17:02:18 +0200 Subject: [PATCH] StringFlag.ValueFromContext() as convenient accessor --- flag_string.go | 5 +++++ flag_test.go | 8 ++++++++ 2 files changed, 13 insertions(+) diff --git a/flag_string.go b/flag_string.go index cd3c7df..7464a28 100644 --- a/flag_string.go +++ b/flag_string.go @@ -97,6 +97,11 @@ func (f *StringFlag) Apply(set *flag.FlagSet) error { return nil } +// ValueFromContext returns the flag’s value in the given Context. +func (f *StringFlag) ValueFromContext(ctx *Context) string { + return ctx.String(f.Name) +} + // String looks up the value of a local StringFlag, returns // "" if not found func (c *Context) String(name string) string { diff --git a/flag_test.go b/flag_test.go index 1ff56f8..aa9fbec 100644 --- a/flag_test.go +++ b/flag_test.go @@ -450,6 +450,14 @@ func TestStringFlagApply_SetsAllNames(t *testing.T) { expect(t, v, "YUUUU") } +func TestStringFlagValueFromContext(t *testing.T) { + set := flag.NewFlagSet("test", 0) + set.String("myflag", "foobar", "doc") + ctx := NewContext(nil, set, nil) + f := &StringFlag{Name: "myflag"} + expect(t, f.ValueFromContext(ctx), "foobar") +} + var pathFlagTests = []struct { name string aliases []string