DurationFlag.ValueFromContext() as convenient accessor

This commit is contained in:
Tilo Prütz 2022-04-22 15:50:13 +02:00
parent baf8ae98de
commit 9eae255aac
2 changed files with 13 additions and 0 deletions

View File

@ -101,6 +101,11 @@ func (f *DurationFlag) Apply(set *flag.FlagSet) error {
return nil
}
// ValueFromContext returns the flags value in the given Context.
func (f *DurationFlag) ValueFromContext(ctx *Context) time.Duration {
return ctx.Duration(f.Name)
}
// Duration looks up the value of a local DurationFlag, returns
// 0 if not found
func (c *Context) Duration(name string) time.Duration {

View File

@ -826,6 +826,14 @@ func TestDurationFlagApply_SetsAllNames(t *testing.T) {
expect(t, v, time.Hour*30)
}
func TestDurationFlagValueFromContext(t *testing.T) {
set := flag.NewFlagSet("test", 0)
set.Duration("myflag", 42*time.Second, "doc")
ctx := NewContext(nil, set, nil)
f := &DurationFlag{Name: "myflag"}
expect(t, f.ValueFromContext(ctx), 42*time.Second)
}
var intSliceFlagTests = []struct {
name string
aliases []string