Strip extra trailing newlines in templates
When wrapping table format in range, string extra new lines from table ends. Fixes https://bugzilla.redhat.com/show_bug.cgi?id=1855983 Signed-off-by: Jhon Honce <jhonce@redhat.com>
This commit is contained in:
parent
f25c9f3b3c
commit
5123c30844
|
|
@ -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)
|
||||
}
|
||||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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())
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue