From 549313318ba0c8dd0599e42f912d642852b629bf Mon Sep 17 00:00:00 2001 From: Sudhanshu Date: Thu, 2 Jul 2026 09:34:11 +0530 Subject: [PATCH] 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 --- pkg/engine/files.go | 6 ++---- pkg/engine/files_test.go | 8 +++++++- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/pkg/engine/files.go b/pkg/engine/files.go index 7834cac2c..7e437a67e 100644 --- a/pkg/engine/files.go +++ b/pkg/engine/files.go @@ -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") } diff --git a/pkg/engine/files_test.go b/pkg/engine/files_test.go index f07f6afeb..99314acfb 100644 --- a/pkg/engine/files_test.go +++ b/pkg/engine/files_test.go @@ -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) {