StringFlag.ValueFromContext() as convenient accessor

This commit is contained in:
Tilo Prütz 2022-04-22 17:02:18 +02:00
parent 660184dd92
commit ce4d9279c4
2 changed files with 13 additions and 0 deletions

View File

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

View File

@ -450,6 +450,14 @@ func TestStringFlagApply_SetsAllNames(t *testing.T) {
expect(t, v, "YUUUU") expect(t, v, "YUUUU")
} }
func TestStringFlagValueFromContext(t *testing.T) {
set := flag.NewFlagSet("test", 0)
set.String("myflag", "foobar", "doc")
ctx := NewContext(nil, set, nil)
f := &StringFlag{Name: "myflag"}
expect(t, f.ValueFromContext(ctx), "foobar")
}
var pathFlagTests = []struct { var pathFlagTests = []struct {
name string name string
aliases []string aliases []string