Execute paths without the .tmpl extension as templates (#654)

## Changes
The `.tmpl` extension is only meant as a qualifier for whether the file
content is executed as a template. All file paths in the `template`
directory should be treated as valid go text templates.

Before only paths with the `.tmpl` extensions would be resolved as
templates, after this change, all file paths are interpreted as
templates.

## Tests
Unit test. The newly added unit tests also asserts that the file path is
correct, even when the `.tmpl` extension is missing.
This commit is contained in:
shreyas-goenka 2023-08-11 15:48:32 +02:00 committed by GitHub
parent 8656c4a1fa
commit 6ea70c82a9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 32 additions and 8 deletions

View File

@ -124,19 +124,29 @@ func (r *renderer) computeFile(relPathTemplate string) (file, error) {
}
perm := info.Mode().Perm()
// Execute relative path template to get destination path for the file
relPath, err := r.executeTemplate(relPathTemplate)
if err != nil {
return nil, err
}
// If file name does not specify the `.tmpl` extension, then it is copied
// over as is, without treating it as a template
if !strings.HasSuffix(relPathTemplate, templateExtension) {
return &copyFile{
dstPath: &destinationPath{
root: r.instanceRoot,
relPath: relPathTemplate,
relPath: relPath,
},
perm: perm,
ctx: r.ctx,
srcPath: relPathTemplate,
srcFiler: r.templateFiler,
}, nil
} else {
// Trim the .tmpl suffix from file name, if specified in the template
// path
relPath = strings.TrimSuffix(relPath, templateExtension)
}
// read template file's content
@ -160,13 +170,6 @@ func (r *renderer) computeFile(relPathTemplate string) (file, error) {
return nil, fmt.Errorf("failed to compute file content for %s. %w", relPathTemplate, err)
}
// Execute relative path template to get materialized path for the file
relPathTemplate = strings.TrimSuffix(relPathTemplate, templateExtension)
relPath, err := r.executeTemplate(relPathTemplate)
if err != nil {
return nil, err
}
return &inMemoryFile{
dstPath: &destinationPath{
root: r.instanceRoot,

View File

@ -459,3 +459,17 @@ func TestRendererFileTreeRendering(t *testing.T) {
assert.DirExists(t, filepath.Join(tmpDir, "my_directory"))
assert.FileExists(t, filepath.Join(tmpDir, "my_directory", "my_file"))
}
func TestRendererSubTemplateInPath(t *testing.T) {
ctx := context.Background()
tmpDir := t.TempDir()
r, err := newRenderer(ctx, nil, "./testdata/template-in-path/template", "./testdata/template-in-path/library", tmpDir)
require.NoError(t, err)
err = r.walk()
require.NoError(t, err)
assert.Equal(t, filepath.Join(tmpDir, "my_directory", "my_file"), r.files[0].DstPath().absPath())
assert.Equal(t, "my_directory/my_file", r.files[0].DstPath().relPath)
}

View File

@ -0,0 +1,7 @@
{{define "dir_name" -}}
my_directory
{{- end}}
{{define "file_name" -}}
my_file
{{- end}}