BoolFlag.ValueFromContext() as convenient accessor

This commit is contained in:
Tilo Prütz 2022-04-22 15:48:26 +02:00
parent 3b6436c36d
commit baf8ae98de
2 changed files with 16 additions and 0 deletions

View File

@ -102,6 +102,11 @@ func (f *BoolFlag) Apply(set *flag.FlagSet) error {
return nil
}
// ValueFromContext returns the flags 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 {

View File

@ -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...)