From baf8ae98deb3bae30567f621d5167694da2a1402 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tilo=20Pr=C3=BCtz?= Date: Fri, 22 Apr 2022 15:48:26 +0200 Subject: [PATCH] BoolFlag.ValueFromContext() as convenient accessor --- flag_bool.go | 5 +++++ flag_test.go | 11 +++++++++++ 2 files changed, 16 insertions(+) diff --git a/flag_bool.go b/flag_bool.go index b8e625a..bdca2b5 100644 --- a/flag_bool.go +++ b/flag_bool.go @@ -102,6 +102,11 @@ func (f *BoolFlag) Apply(set *flag.FlagSet) error { return nil } +// ValueFromContext returns the flag’s value in the given Context. +func (f *BoolFlag) ValueFromContext(ctx *Context) bool { + return ctx.Bool(f.Name) +} + // Bool looks up the value of a local BoolFlag, returns // false if not found func (c *Context) Bool(name string) bool { diff --git a/flag_test.go b/flag_test.go index 44c3500..53cb60b 100644 --- a/flag_test.go +++ b/flag_test.go @@ -51,6 +51,17 @@ func TestBoolFlagApply_SetsAllNames(t *testing.T) { expect(t, v, true) } +func TestBoolFlagValueFromContext(t *testing.T) { + set := flag.NewFlagSet("test", 0) + set.Bool("trueflag", true, "doc") + set.Bool("falseflag", false, "doc") + ctx := NewContext(nil, set, nil) + tf := &BoolFlag{Name: "trueflag"} + ff := &BoolFlag{Name: "falseflag"} + expect(t, tf.ValueFromContext(ctx), true) + expect(t, ff.ValueFromContext(ctx), false) +} + func TestFlagsFromEnv(t *testing.T) { newSetFloat64Slice := func(defaults ...float64) Float64Slice { s := NewFloat64Slice(defaults...)