From 660184dd92d1f13f1156dfceb1f22df327dfbd3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tilo=20Pr=C3=BCtz?= Date: Fri, 22 Apr 2022 16:59:19 +0200 Subject: [PATCH] PathFlag.ValueFromContext() as convenient accessor --- flag_path.go | 5 +++++ flag_test.go | 8 ++++++++ 2 files changed, 13 insertions(+) diff --git a/flag_path.go b/flag_path.go index 4010e84..40c9009 100644 --- a/flag_path.go +++ b/flag_path.go @@ -96,6 +96,11 @@ func (f *PathFlag) Apply(set *flag.FlagSet) error { return nil } +// ValueFromContext returns the flag’s value in the given Context. +func (f *PathFlag) ValueFromContext(ctx *Context) string { + return ctx.Path(f.Name) +} + // Path looks up the value of a local PathFlag, returns // "" if not found func (c *Context) Path(name string) string { diff --git a/flag_test.go b/flag_test.go index e80231d..1ff56f8 100644 --- a/flag_test.go +++ b/flag_test.go @@ -501,6 +501,14 @@ func TestPathFlagApply_SetsAllNames(t *testing.T) { expect(t, v, "/path/to/file/PATH") } +func TestPathFlagValueFromContext(t *testing.T) { + set := flag.NewFlagSet("test", 0) + set.String("myflag", "/my/path", "doc") + ctx := NewContext(nil, set, nil) + f := &PathFlag{Name: "myflag"} + expect(t, f.ValueFromContext(ctx), "/my/path") +} + var envHintFlagTests = []struct { name string env string