From b3707e666bc562cae76aad554bde6160644aa837 Mon Sep 17 00:00:00 2001 From: Joe Julian Date: Fri, 20 Jan 2023 11:24:13 -0800 Subject: [PATCH] strip trailing newline from Files.Lines Signed-off-by: Joe Julian --- pkg/engine/files.go | 9 ++++++--- pkg/engine/files_test.go | 15 ++++++++++++++- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/pkg/engine/files.go b/pkg/engine/files.go index f29b0ab7c..f2cfdb3f3 100644 --- a/pkg/engine/files.go +++ b/pkg/engine/files.go @@ -131,7 +131,7 @@ func (f files) AsConfig() string { // // data: // -// {{ .Files.Glob("secrets/*").AsSecrets() }} +// {{ .Files.Glob("secrets/*").AsSecrets() | indent 4 }} func (f files) AsSecrets() string { if f == nil { return "" @@ -157,6 +157,9 @@ func (f files) Lines(path string) []string { if f == nil || f[path] == nil { return []string{} } - - return strings.Split(string(f[path]), "\n") + s := string(f[path]) + if s[len(s)-1] == '\n' { + s = s[:len(s)-1] + } + return strings.Split(s, "\n") } diff --git a/pkg/engine/files_test.go b/pkg/engine/files_test.go index 4b37724f9..e53263c76 100644 --- a/pkg/engine/files_test.go +++ b/pkg/engine/files_test.go @@ -28,7 +28,8 @@ var cases = []struct { {"ship/stowaway.txt", "Legatt"}, {"story/name.txt", "The Secret Sharer"}, {"story/author.txt", "Joseph Conrad"}, - {"multiline/test.txt", "bar\nfoo"}, + {"multiline/test.txt", "bar\nfoo\n"}, + {"multiline/test_with_blank_lines.txt", "bar\nfoo\n\n\n"}, } func getTestFiles() files { @@ -96,3 +97,15 @@ func TestLines(t *testing.T) { as.Equal("bar", out[0]) } + +func TestBlankLines(t *testing.T) { + as := assert.New(t) + + f := getTestFiles() + + out := f.Lines("multiline/test_with_blank_lines.txt") + as.Len(out, 4) + + as.Equal("bar", out[0]) + as.Equal("", out[3]) +}