Skip to content

Commit

Permalink
Merge pull request #624 from jwhonce/bz/1855983
Browse files Browse the repository at this point in the history
Strip extra trailing newlines in templates
  • Loading branch information
openshift-merge-robot authored Jun 16, 2021
2 parents 5d5d9b4 + 05a5685 commit 16f5a3c
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 4 deletions.
6 changes: 3 additions & 3 deletions pkg/report/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ func NewTemplate(name string) *Template {
func (t *Template) Parse(text string) (*Template, error) {
if strings.HasPrefix(text, "table ") {
t.isTable = true
text = "{{range .}}" + NormalizeFormat(text) + "{{end}}"
text = "{{range .}}" + NormalizeFormat(text) + "{{end -}}"
} else {
text = NormalizeFormat(text)
}
Expand All @@ -157,12 +157,12 @@ func (t *Template) IsTable() bool {
return t.isTable
}

var rangeRegex = regexp.MustCompile(`{{\s*range\s*\.\s*}}.*{{\s*end\s*}}`)
var rangeRegex = regexp.MustCompile(`{{\s*range\s*\.\s*}}.*{{\s*end\s*-?\s*}}`)

// EnforceRange ensures that the format string contains a range
func EnforceRange(format string) string {
if !rangeRegex.MatchString(format) {
return "{{range .}}" + format + "{{end}}"
return "{{range .}}" + format + "{{end -}}"
}
return format
}
Expand Down
37 changes: 36 additions & 1 deletion pkg/report/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,8 +158,43 @@ func TestTemplate_HasTable(t *testing.T) {
}

func TestTemplate_EnforceRange(t *testing.T) {
testRange := `{{range .}}foobar was here{{end}}`
testRange := `{{range .}}foobar was here{{end -}}`
assert.Equal(t, testRange, EnforceRange(testRange))
assert.Equal(t, testRange, EnforceRange("foobar was here"))
assert.NotEqual(t, testRange, EnforceRange("foobar"))

// Do not override a given range
testRange = `{{range .}}foobar was here{{end}}`
assert.Equal(t, testRange, EnforceRange(testRange))
}

func TestTemplate_Newlines(t *testing.T) {
input := []struct {
Field1 string
Field2 int
Field3 string
}{
{Field1: "One", Field2: 1, Field3: "First"},
{Field1: "Two", Field2: 2, Field3: "Second"},
{Field1: "Three", Field2: 3, Field3: "Third"},
}

hdrs := Headers(input[0], map[string]string{"Field1": "Ein", "Field2": "Zwei", "Field3": "Drei"})

// Ensure no blank lines in table
expected := "EIN\tZWEI\tDREI\nOne\t1\tFirst\nTwo\t2\tSecond\nThree\t3\tThird\n"

format := NormalizeFormat("{{.Field1}}\t{{.Field2}}\t{{.Field3}}")
format = EnforceRange(format)
tmpl, err := NewTemplate("TestTemplate").Parse(format)
assert.NoError(t, err)

var buf bytes.Buffer
err = tmpl.Execute(&buf, hdrs)
assert.NoError(t, err)

err = tmpl.Execute(&buf, input)
assert.NoError(t, err)

assert.Equal(t, expected, buf.String())
}

0 comments on commit 16f5a3c

Please sign in to comment.