added support for mandatory variables to cli/compose

Signed-off-by: Arash Deshmeh <adeshmeh@ca.ibm.com>
This commit is contained in:
Arash Deshmeh 2018-02-21 06:29:08 -05:00
parent 2813fae8f9
commit 99ecf57c6c
2 changed files with 81 additions and 1 deletions

View File

@ -7,7 +7,7 @@ import (
) )
var delimiter = "\\$" var delimiter = "\\$"
var substitution = "[_a-z][_a-z0-9]*(?::?-[^}]+)?" var substitution = "[_a-z][_a-z0-9]*(?::?[-?][^}]+)?"
var patternString = fmt.Sprintf( var patternString = fmt.Sprintf(
"%s(?i:(?P<escaped>%s)|(?P<named>%s)|{(?P<braced>%s)}|(?P<invalid>))", "%s(?i:(?P<escaped>%s)|(?P<named>%s)|{(?P<braced>%s)}|(?P<invalid>))",
@ -69,6 +69,26 @@ func Substitute(template string, mapping Mapping) (string, error) {
return value return value
} }
if strings.Contains(substitution, ":?") {
name, errorMessage := partition(substitution, ":?")
value, ok := mapping(name)
if !ok || value == "" {
err = &InvalidTemplateError{Template: errorMessage}
return ""
}
return value
}
if strings.Contains(substitution, "?") {
name, errorMessage := partition(substitution, "?")
value, ok := mapping(name)
if !ok {
err = &InvalidTemplateError{Template: errorMessage}
return ""
}
return value
}
// No default (fall back to empty string) // No default (fall back to empty string)
value, ok := mapping(substitution) value, ok := mapping(substitution)
if !ok { if !ok {

View File

@ -81,3 +81,63 @@ func TestNonAlphanumericDefault(t *testing.T) {
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, "ok /non:-alphanumeric", result) assert.Equal(t, "ok /non:-alphanumeric", result)
} }
func TestMandatoryVariableErrors(t *testing.T) {
testCases := []struct {
template string
expectedError string
}{
{
template: "not ok ${UNSET_VAR:?Mandatory Variable Unset}",
expectedError: "Mandatory Variable Unset",
},
{
template: "not ok ${BAR:?Mandatory Variable Empty}",
expectedError: "Mandatory Variable Empty",
},
{
template: "not ok ${UNSET_VAR:?}",
expectedError: "",
},
{
template: "not ok ${UNSET_VAR?Mandatory Variable Unset",
expectedError: "Mandatory Variable Unset",
},
{
template: "not ok ${UNSET_VAR?}",
expectedError: "",
},
}
for _, tc := range testCases {
_, err := Substitute(tc.template, defaultMapping)
assert.Error(t, err)
assert.IsType(t, &InvalidTemplateError{tc.expectedError}, err)
}
}
func TestDefaultsForMandatoryVariables(t *testing.T) {
testCases := []struct {
template string
expected string
}{
{
template: "ok ${FOO:?err}",
expected: "ok first",
},
{
template: "ok ${FOO?err}",
expected: "ok first",
},
{
template: "ok ${BAR?err}",
expected: "ok ",
},
}
for _, tc := range testCases {
result, err := Substitute(tc.template, defaultMapping)
assert.Nil(t, err)
assert.Equal(t, tc.expected, result)
}
}