From 4791c0212273904aae620175a1ca07aee2ac4bcf Mon Sep 17 00:00:00 2001 From: Brian Picciano Date: Sun, 23 Jun 2019 12:55:11 -0600 Subject: [PATCH] mcfg: implement ParamDefaultOrRequired --- mcfg/mcfg_test.go | 20 ++++++++++++++++++++ mcfg/param.go | 12 ++++++++++++ 2 files changed, 32 insertions(+) diff --git a/mcfg/mcfg_test.go b/mcfg/mcfg_test.go index bbc7470..940ff6a 100644 --- a/mcfg/mcfg_test.go +++ b/mcfg/mcfg_test.go @@ -47,3 +47,23 @@ func TestPopulate(t *T) { assert.Equal(t, 3, *c) } } + +func TestParamDefaultOrRequired(t *T) { + { + cmp := new(mcmp.Component) + Int(cmp, "a", ParamDefaultOrRequired(0)) + params := CollectParams(cmp) + assert.Equal(t, "a", params[0].Name) + assert.Equal(t, true, params[0].Required) + assert.Equal(t, new(int), params[0].Into) + } + { + cmp := new(mcmp.Component) + Int(cmp, "a", ParamDefaultOrRequired(1)) + i := 1 + params := CollectParams(cmp) + assert.Equal(t, "a", params[0].Name) + assert.Equal(t, false, params[0].Required) + assert.Equal(t, &i, params[0].Into) + } +} diff --git a/mcfg/param.go b/mcfg/param.go index 26a405b..b5dd6a3 100644 --- a/mcfg/param.go +++ b/mcfg/param.go @@ -83,6 +83,18 @@ func ParamDefault(value interface{}) ParamOption { } } +// ParamDefaultOrRequired returns a ParamOption whose behavior depends on the +// given value. If the given value is the zero value for its type, then this returns +// ParamRequired(), otherwise this returns ParamDefault(value). +func ParamDefaultOrRequired(value interface{}) ParamOption { + v := reflect.ValueOf(value) + zero := reflect.Zero(v.Type()) + if v.Interface() == zero.Interface() { + return ParamRequired() + } + return ParamDefault(value) +} + // ParamUsage returns a ParamOption which sets the usage string on the Param. // This is used in some Sources, like SourceCLI, when displaying information // about available parameters.