diff options
Diffstat (limited to 'context')
-rw-r--r-- | context/context.go | 21 | ||||
-rw-r--r-- | context/context_test.go | 22 |
2 files changed, 43 insertions, 0 deletions
diff --git a/context/context.go b/context/context.go index 9996f31faa5f..1a2e5c88cc09 100644 --- a/context/context.go +++ b/context/context.go @@ -12,6 +12,7 @@ package context import ( "fmt" "path" + "strings" "github.com/tazjin/kontemplate/util" ) @@ -158,3 +159,23 @@ func loadDefaultValues(rs *ResourceSet, c *Context) *map[string]interface{} { // errors here. return &rs.Values } + +// New variables can be defined or default values overridden with command line arguments when executing kontemplate. +func (ctx *Context) SetVariablesFromArguments(vars *[]string) error { + // Resource set files might not have defined any global variables, if so we have to + // create that a map before potentially writing variables into it + if ctx.Global == nil { + ctx.Global = make(map[string]interface{}, len(*vars)) + } + + for _, v := range *vars { + varParts := strings.Split(v, "=") + if len(varParts) != 2 { + return fmt.Errorf(`invalid explicit variable provided (%s), name and value should be divided with "="`, v) + } + + ctx.Global[varParts[0]] = varParts[1] + } + + return nil +} diff --git a/context/context_test.go b/context/context_test.go index 38b6a76e7aff..6dc27466a579 100644 --- a/context/context_test.go +++ b/context/context_test.go @@ -280,3 +280,25 @@ func TestExplicitSubresourcePathLoading(t *testing.T) { t.Fail() } } + +func TestSetVariablesFromArguments(t *testing.T) { + vars := []string{"version=some-service-version"} + ctx, _ := LoadContextFromFile("testdata/default-loading.yaml") + + if err := ctx.SetVariablesFromArguments(&vars); err != nil { + t.Error(err) + } + + if version := ctx.Global["version"]; version != "some-service-version" { + t.Errorf(`Expected variable "version" to have value "some-service-version" but was "%s"`, version) + } +} + +func TestSetInvalidVariablesFromArguments(t *testing.T) { + vars := []string{"version: some-service-version"} + ctx, _ := LoadContextFromFile("testdata/default-loading.yaml") + + if err := ctx.SetVariablesFromArguments(&vars); err == nil { + t.Error("Expected invalid variable to return an error") + } +} |