From 9cb9c85c6cbe9af5b5393d881e2282c3dbd3317b Mon Sep 17 00:00:00 2001 From: Sam Lown Date: Tue, 5 Sep 2023 15:05:00 +0000 Subject: [PATCH] here.Doc will remove trailing empty lines --- build/schemas/cal/date-time.json | 2 +- pkg/here/here.go | 12 ++++++++++++ pkg/here/here_test.go | 8 ++++---- 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/build/schemas/cal/date-time.json b/build/schemas/cal/date-time.json index a5ea82fd..08483501 100644 --- a/build/schemas/cal/date-time.json +++ b/build/schemas/cal/date-time.json @@ -7,7 +7,7 @@ "type": "string", "format": "date-time", "title": "Date Time", - "description": "Civil date time in simplified ISO format with no time zone\ninformation, for example: 2021-05-26T13:45:00\n" + "description": "Civil date time in simplified ISO format with no time zone\ninformation, for example: 2021-05-26T13:45:00" } }, "$comment": "Generated with GOBL v0.55.0" diff --git a/pkg/here/here.go b/pkg/here/here.go index 0561183a..99e3cc12 100644 --- a/pkg/here/here.go +++ b/pkg/here/here.go @@ -51,6 +51,7 @@ func Doc(raw string) string { minIndentSize := getMinIndent(lines, skipFirstLine) lines = removeIndentation(lines, minIndentSize, skipFirstLine) + lines = removeEmptyTailLines(lines) return strings.Join(lines, "\n") } @@ -104,6 +105,17 @@ func removeIndentation(lines []string, n int, skipFirstLine bool) []string { return lines } +// removeEmptyTailLines removes empty lines from the end of the lines array. +func removeEmptyTailLines(lines []string) []string { + for i := len(lines) - 1; i >= 0; i-- { + if lines[i] != "" { + break + } + lines = lines[:i] + } + return lines +} + // Docf returns unindented and formatted string as here-document. // Formatting is done as for fmt.Printf(). func Docf(raw string, args ...interface{}) string { diff --git a/pkg/here/here_test.go b/pkg/here/here_test.go index 42291bd8..138112f1 100644 --- a/pkg/here/here_test.go +++ b/pkg/here/here_test.go @@ -22,7 +22,7 @@ var tests = []testCase{ Foo Bar `, - "Foo\nBar\n"}, + "Foo\nBar"}, {`Foo Bar`, "Foo\nBar"}, @@ -30,7 +30,7 @@ var tests = []testCase{ Bar `, - "Foo\n\t\nBar\n"}, // Second line contains two tabs. + "Foo\n\t\nBar"}, // Second line contains two tabs. {` Foo Bar @@ -42,7 +42,7 @@ var tests = []testCase{ ` Foo Bar - `, "Foo\nBar\n"}, + `, "Foo\nBar"}, {"\n\u3000zenkaku space", "\x80\x80zenkaku space"}, } @@ -71,7 +71,7 @@ func TestDocf(t *testing.T) { ` i := 42 s := "Hello" - expect := "int: 42\nstring: Hello\n" + expect := "int: 42\nstring: Hello" result := here.Docf(tc, i, s) if result != expect {