fix(engine): guard Files.Lines against empty file panic

Avoid panicking with index out of range when calling Lines on an empty file. Checking the length of the slice instead of checking for nil ensures empty files do not cause panic, and using strings.TrimSuffix makes newline trimming safer.

Signed-off-by: Sudhanshu <sudhanshuwriterblc@gmail.com>
pull/32280/head
Sudhanshu 1 week ago
parent af25d22902
commit 549313318b

@ -154,12 +154,10 @@ func (f files) AsSecrets() string {
// {{ range .Files.Lines "foo/bar.html" }}
// {{ . }}{{ end }}
func (f files) Lines(path string) []string {
if f == nil || f[path] == nil {
if f == nil || len(f[path]) == 0 {
return []string{}
}
s := string(f[path])
if s[len(s)-1] == '\n' {
s = s[:len(s)-1]
}
s = strings.TrimSuffix(s, "\n")
return strings.Split(s, "\n")
}

@ -30,6 +30,7 @@ var cases = []struct {
{"story/author.txt", "Joseph Conrad"},
{"multiline/test.txt", "bar\nfoo\n"},
{"multiline/test_with_blank_lines.txt", "bar\nfoo\n\n\n"},
{"multiline/empty.txt", ""},
}
func getTestFiles() files {
@ -94,8 +95,13 @@ func TestLines(t *testing.T) {
out := f.Lines("multiline/test.txt")
as.Len(out, 2)
as.Equal("bar", out[0])
outEmpty := f.Lines("multiline/empty.txt")
as.Len(outEmpty, 0)
outNonExistent := f.Lines("nonexistent.txt")
as.Len(outNonExistent, 0)
}
func TestBlankLines(t *testing.T) {

Loading…
Cancel
Save