From de4859ae06c4531442c0748a9a68a83fcc05a06a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miloslav=20Trma=C4=8D?= Date: Thu, 23 Feb 2023 00:30:27 +0100 Subject: [PATCH] Fix the combination of "table " and \n in report formats MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Completely skipping the NormalizeFormat part also skipped the removal of the "table " directive. Signed-off-by: Miloslav Trmač --- pkg/report/formatter.go | 14 ++++++++++++-- pkg/report/formatter_test.go | 1 + 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/pkg/report/formatter.go b/pkg/report/formatter.go index 2774ff056..aa8ed6b36 100644 --- a/pkg/report/formatter.go +++ b/pkg/report/formatter.go @@ -49,6 +49,15 @@ type Formatter struct { writer io.Writer // Destination for formatted output } +// stringsCutPrefix is equivalent to Go 1.20’s strings.CutPrefix. +// Replace this function with a direct call to the standard library after we update to Go 1.20. +func stringsCutPrefix(s, prefix string) (string, bool) { + if !strings.HasPrefix(s, prefix) { + return s, false + } + return s[len(prefix):], true +} + // Parse parses golang template returning a formatter // // - OriginPodman implies text is a template from podman code. Output will @@ -64,11 +73,12 @@ func (f *Formatter) Parse(origin Origin, text string) (*Formatter, error) { // To be backwards compatible with the previous behavior we try to replace and // parse the template. If it fails use the original text and parse again. var normText string + textWithoutTable, hasTable := stringsCutPrefix(text, "table ") switch { - case strings.HasPrefix(text, "table "): + case hasTable: f.RenderTable = true normText = "{{range .}}" + NormalizeFormat(text) + "{{end -}}" - text = "{{range .}}" + text + "{{end -}}" + text = "{{range .}}" + textWithoutTable + "{{end -}}" case OriginUser == origin: normText = EnforceRange(NormalizeFormat(text)) text = EnforceRange(text) diff --git a/pkg/report/formatter_test.go b/pkg/report/formatter_test.go index d84935c3e..4c989a561 100644 --- a/pkg/report/formatter_test.go +++ b/pkg/report/formatter_test.go @@ -84,6 +84,7 @@ func TestFormatter_ParseTable(t *testing.T) { {&bytes.Buffer{}, OriginUser, `{{range .}}{{.ID}}{{end -}}`, "c061a0839ef10fc2e110571eb6fab5aa8f4b5cbfd3e66aa35e9b2a"}, // regression test for https://bugzilla.redhat.com/show_bug.cgi?id=2059658 and https://github.com/containers/podman/issues/13446 {&bytes.Buffer{}, OriginUser, `{{range .}}{{printf "\n"}}{{end -}}`, "\n\n\n"}, + {&tabwriter.Writer{}, OriginUser, `table {{printf "\n"}}`, "\n\n\n\n"}, } for loop, tc := range testCase {