Skip to content

Commit

Permalink
json array handling
Browse files Browse the repository at this point in the history
Signed-off-by: Gerd Oberlechner <[email protected]>
  • Loading branch information
geoberle committed Dec 19, 2024
1 parent 985e87d commit a3a5728
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 17 deletions.
12 changes: 2 additions & 10 deletions tooling/templatize/cmd/generate/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,11 @@ import (
"io/fs"
"os"
"path/filepath"
"text/template"

"github.com/Masterminds/sprig/v3"
"github.com/spf13/cobra"

options "github.com/Azure/ARO-HCP/tooling/templatize/cmd"
"github.com/Azure/ARO-HCP/tooling/templatize/pkg/config"
)

func DefaultGenerationOptions() *RawGenerationOptions {
Expand Down Expand Up @@ -113,16 +112,9 @@ func (o *ValidatedGenerationOptions) Complete() (*GenerationOptions, error) {
}

func (opts *GenerationOptions) ExecuteTemplate() error {
tmpl := template.New(opts.InputFile).Funcs(sprig.FuncMap())
content, err := fs.ReadFile(opts.InputFS, opts.InputFile)
if err != nil {
return err
}

tmpl, err = tmpl.Parse(string(content))
if err != nil {
return err
}

return tmpl.Option("missingkey=error").ExecuteTemplate(opts.OutputFile, opts.InputFile, opts.RolloutOptions.Config)
return config.PreprocessContentIntoWriter(content, opts.RolloutOptions.Config, opts.OutputFile)
}
37 changes: 30 additions & 7 deletions tooling/templatize/pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package config

import (
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
Expand Down Expand Up @@ -260,15 +262,36 @@ func PreprocessFile(templateFilePath string, vars map[string]any) ([]byte, error

// PreprocessContent processes a gotemplate from memory
func PreprocessContent(content []byte, vars map[string]any) ([]byte, error) {
tmpl := template.New("file")
tmpl, err := tmpl.Parse(string(content))
var tmplBytes bytes.Buffer
if err := PreprocessContentIntoWriter(content, vars, &tmplBytes); err != nil {
return nil, err
}
return tmplBytes.Bytes(), nil
}

func PreprocessContentIntoWriter(content []byte, vars map[string]any, writer io.Writer) error {
funcMap := template.FuncMap{
"json": jsonEncoder,
}
tmpl, err := template.New("file").Funcs(funcMap).Parse(string(content))
if err != nil {
return nil, fmt.Errorf("failed to parse template: %w", err)
return fmt.Errorf("failed to parse template: %w", err)
}

var tmplBytes bytes.Buffer
if err := tmpl.Option("missingkey=error").Execute(&tmplBytes, vars); err != nil {
return nil, fmt.Errorf("failed to execute template: %w", err)
if err := tmpl.Option("missingkey=error").Execute(writer, vars); err != nil {
return fmt.Errorf("failed to execute template: %w", err)
}
return tmplBytes.Bytes(), nil
return nil
}

func jsonEncoder(value interface{}) (string, error) {
valueType := reflect.TypeOf(value)
if valueType.Kind() == reflect.String {
return value.(string), nil
}
jsonBytes, err := json.Marshal(value)
if err != nil {
return "", err
}
return string(jsonBytes), nil
}
46 changes: 46 additions & 0 deletions tooling/templatize/pkg/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"os"
"testing"

"github.com/google/go-cmp/cmp"
"github.com/stretchr/testify/assert"

"github.com/Azure/ARO-HCP/tooling/templatize/internal/testutil"
Expand Down Expand Up @@ -308,3 +309,48 @@ func TestPreprocessContentMissingKey(t *testing.T) {
})
}
}

func TestPreprocessContentJson(t *testing.T) {
templateContent := "{{ .variable | json }}"

testCases := []struct {
name string
value any
expectedResult string
}{
{
name: "string value",
value: "foo",
expectedResult: "foo",
},
{
name: "array value",
value: []string{"foo", "bar"},
expectedResult: "[\"foo\",\"bar\"]",
},
{
name: "int value",
value: 42,
expectedResult: "42",
},
{
name: "bool value",
value: true,
expectedResult: "true",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
processed, err := PreprocessContent(
[]byte(templateContent),
map[string]any{
"variable": tc.value,
},
)
assert.Nil(t, err)
if diff := cmp.Diff(string(processed), string(tc.expectedResult)); diff != "" {
t.Errorf("got diff between expected and actual result\ndiff:\n%s\n\nIf this is expected, re-run the test with `UPDATE=true go test ./...` to update the fixtures.", diff)
}
})
}
}
8 changes: 8 additions & 0 deletions tooling/templatize/pkg/ev2/mapping_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,14 @@ func TestPlaceholderGenerators(t *testing.T) {
expectedFlattened: "__foo.bar__",
expectedReplace: "any('__foo.bar__')",
},
{
name: "bicep array param",
generator: NewBicepParamPlaceholders(),
key: []string{"foo", "bar"},
valueType: reflect.TypeOf([]any{}),
expectedFlattened: "__foo.bar__",
expectedReplace: "any('__foo.bar__')",
},
}

for _, tc := range tests {
Expand Down

0 comments on commit a3a5728

Please sign in to comment.