Skip to content

Commit 8cc7059

Browse files
mheapharshadixit12
andauthored
Skip template parsing for commented out lines (#351)
* Skip template parsing for commented out lines * fix: execute template only once * refactor: modify test input --------- Co-authored-by: Harsha Dixit <[email protected]>
1 parent 7f6ec07 commit 8cc7059

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

pkg/file/template.go

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,22 @@ func renderTemplate(content string, mockEnvVars bool) (string, error) {
9696
}
9797
t := template.New("state").Funcs(templateFuncs).Delims("${{", "}}")
9898

99-
t, err := t.Parse(content)
99+
// Parse content line by line, and ignore lines that start with #
100+
var allContent bytes.Buffer
101+
lines := strings.Split(content, "\n")
102+
for i := 0; i < len(lines); i++ {
103+
line := lines[i]
104+
if !strings.HasPrefix(strings.TrimSpace(line), "#") {
105+
allContent.WriteString(line + "\n")
106+
}
107+
}
108+
109+
result := allContent.String()
110+
if !strings.HasSuffix(content, "\n") {
111+
result = strings.TrimSuffix(result, "\n")
112+
}
113+
114+
t, err := t.Parse(result)
100115
if err != nil {
101116
return "", err
102117
}

pkg/file/template_test.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,3 +72,40 @@ func Test_renderTemplateCustomPrefix(t *testing.T) {
7272
os.Unsetenv("PREFIX_MY_VARIABLE")
7373
SetEnvVarPrefix(oldPrefix)
7474
}
75+
76+
func Test_renderTemplateIgnoresComments(t *testing.T) {
77+
content := `Hello, ${{ env "DECK_MY_VARIABLE" }}!
78+
# Also, ${{ env "DECK_NOT_SET_DOESNT_ERROR" }}!`
79+
80+
expectedOutput := `Hello, my_value!`
81+
mockEnvVars := false
82+
83+
os.Setenv("DECK_MY_VARIABLE", "my_value")
84+
85+
output, err := renderTemplate(content, mockEnvVars)
86+
if err != nil {
87+
t.Errorf("Unexpected error: %v", err)
88+
}
89+
90+
if output != expectedOutput {
91+
t.Errorf("Expected output %q, but got %q", expectedOutput, output)
92+
}
93+
os.Unsetenv("DECK_MY_VARIABLE")
94+
}
95+
96+
func Test_renderTemplateErrorWhenNotSet(t *testing.T) {
97+
content := `
98+
Hello, ${{ env "DECK_MY_VARIABLE" }}!
99+
Also, ${{ env "DECK_NOT_SET_ERRORS" }}!`
100+
101+
mockEnvVars := false
102+
103+
os.Setenv("DECK_MY_VARIABLE", "my_value")
104+
105+
_, err := renderTemplate(content, mockEnvVars)
106+
if err == nil {
107+
t.Errorf("expected error but did not receive one")
108+
}
109+
110+
os.Unsetenv("DECK_MY_VARIABLE")
111+
}

0 commit comments

Comments
 (0)