Skip to content

Commit

Permalink
Extract varsParser function
Browse files Browse the repository at this point in the history
  • Loading branch information
chuhlomin committed May 27, 2022
1 parent 2abb239 commit d69319d
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 8 deletions.
18 changes: 10 additions & 8 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,7 @@ func main() {
func run() error {
var c config
parsers := map[reflect.Type]env.ParserFunc{
reflect.TypeOf(vars{}): func(v string) (interface{}, error) {
m := map[string]interface{}{}
err := yaml.Unmarshal([]byte(v), &m)
if err != nil {
return nil, fmt.Errorf("unable to parse Vars: %v", err)
}
return m, nil
},
reflect.TypeOf(vars{}): varsParser,
}
if err := env.ParseWithFuncs(&c, parsers); err != nil {
return err
Expand All @@ -62,6 +55,15 @@ func run() error {
return nil
}

func varsParser(v string) (interface{}, error) {
m := map[string]interface{}{}
err := yaml.Unmarshal([]byte(v), &m)
if err != nil {
return nil, fmt.Errorf("unable to parse Vars: %v", err)
}
return m, nil
}

func renderTemplate(templateFilePath string, vars vars) (string, error) {
b, err := ioutil.ReadFile(templateFilePath)
if err != nil {
Expand Down
75 changes: 75 additions & 0 deletions main_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"encoding/json"
"errors"
"testing"
)
Expand All @@ -25,6 +26,80 @@ func TestEscape(t *testing.T) {
}
}

func TestVarsParser(t *testing.T) {
tests := []struct {
in string
expectedJSON string
err error
}{
{
`
key: value`,
`{"key":"value"}`,
nil,
},
{
`
key: |
value`,
`{"key":"value"}`,
nil,
},
{
`
key: |
line 1
line 2`,
`{"key":"line 1\nline 2"}`,
nil,
},
{
`
key: |
line 1: val1
line 2: val2
line 3: val3`,
``,
errors.New("unable to parse Vars: yaml: line 5: mapping values are not allowed in this context"),
},
{
`
key: "line 1: val1
line 2: val2
line 3: val3"`,
`{"key":"line 1: val1 line 2: val2 line 3: val3"}`,
nil,
},
{
`{"key": "val1"}`,
`{"key":"val1"}`,
nil,
},
}

for _, tt := range tests {
actual, err := varsParser(tt.in)
if tt.err != nil {
if err == nil {
t.Errorf("varsParser(%q) was incorrect, got: nil, want: %q.", tt.in, tt.err)
}
if err.Error() != tt.err.Error() {
t.Errorf("varsParser(%q) was incorrect, got: %q, want: %q.", tt.in, err, tt.err)
}
continue
}

actualJSONBytes, err := json.Marshal(actual)
if err != nil {
t.Errorf("varsParser (%q) failed to marshal actual %v", tt.in, actual)
}

if string(actualJSONBytes) != tt.expectedJSON {
t.Errorf("varsParser(%q) was incorrect, got: %q, want: %q.", tt.in, string(actualJSONBytes), tt.expectedJSON)
}
}
}

func TestRenderTemplate(t *testing.T) {
tests := []struct {
templateFilePath string
Expand Down

0 comments on commit d69319d

Please sign in to comment.