From bf18c00347867c9f8be0e872a82b4e1baed24d45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tilo=20Pr=C3=BCtz?= Date: Fri, 22 Apr 2022 16:12:11 +0200 Subject: [PATCH] IntFlag.ValueFromContext() as convenient accessor --- flag_int.go | 5 +++++ flag_test.go | 8 ++++++++ 2 files changed, 13 insertions(+) diff --git a/flag_int.go b/flag_int.go index 62c0848..642a68b 100644 --- a/flag_int.go +++ b/flag_int.go @@ -102,6 +102,11 @@ func (f *IntFlag) Apply(set *flag.FlagSet) error { return nil } +// ValueFromContext returns the flag’s value in the given Context. +func (f *IntFlag) ValueFromContext(ctx *Context) int { + return ctx.Int(f.Name) +} + // Int looks up the value of a local IntFlag, returns // 0 if not found func (c *Context) Int(name string) int { diff --git a/flag_test.go b/flag_test.go index 7fa6673..86d281e 100644 --- a/flag_test.go +++ b/flag_test.go @@ -663,6 +663,14 @@ func TestIntFlagApply_SetsAllNames(t *testing.T) { expect(t, v, 5) } +func TestIntFlagValueFromContext(t *testing.T) { + set := flag.NewFlagSet("test", 0) + set.Int("myflag", 42, "doc") + ctx := NewContext(nil, set, nil) + f := &IntFlag{Name: "myflag"} + expect(t, f.ValueFromContext(ctx), 42) +} + var int64FlagTests = []struct { name string expected string