Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions runner/md_output.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,13 @@ func formatMarkdownValue(v reflect.Value) string {
}

func escapeMarkdown(s string) string {
// Escape backslashes as well as pipes so a literal "\|" keeps its backslash,
// and flatten every line ending so one result stays on one table row.
replacer := strings.NewReplacer(
"\\", "\\\\",
"|", "\\|",
"\r\n", " ",
"\r", " ",
"\n", " ",
)
return strings.TrimSpace(replacer.Replace(s))
Expand Down
64 changes: 64 additions & 0 deletions runner/md_output_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package runner

import (
"strings"
"testing"

"github.com/stretchr/testify/require"
)

func TestEscapeMarkdown(t *testing.T) {
tests := []struct {
name string
in string
want string
}{
{name: "plain", in: "httpx", want: "httpx"},
{name: "pipe", in: "a|b", want: `a\|b`},
{name: "backslash", in: `C:\temp`, want: `C:\\temp`},
{name: "backslash before pipe", in: `left\|right`, want: `left\\\|right`},
{name: "lf", in: "left\nright", want: "left right"},
{name: "crlf", in: "left\r\nright", want: "left right"},
{name: "cr", in: "left\rright", want: "left right"},
{name: "trailing line ending", in: "value\r\n", want: "value"},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
require.Equal(t, tt.want, escapeMarkdown(tt.in))
})
}
}

func TestMarkdownRowKeepsOneRowPerResult(t *testing.T) {
r := Result{
Title: `left\|right`,
Generator: "left\rright",
WebServer: "left\r\nright",
StatusCode: 200,
}

header := r.MarkdownHeader()
row := r.MarkdownRow(nil)

require.True(t, strings.HasSuffix(row, "\n"))
require.Equal(t, 1, strings.Count(row, "\n"), "result must stay on one table row")
require.NotContains(t, row, "\r")
require.Contains(t, row, `| left\\\|right |`)
require.Contains(t, row, "| left right |")

headerLine := strings.SplitN(header, "\n", 2)[0]
require.Equal(t, countMarkdownCells(headerLine), countMarkdownCells(strings.TrimSuffix(row, "\n")))
}

// countMarkdownCells counts the cells of a table row the way GitHub Flavored
// Markdown splits it: a pipe preceded by a backslash belongs to the cell.
func countMarkdownCells(line string) int {
cells := 0
for i := 1; i < len(line); i++ {
if line[i] == '|' && line[i-1] != '\\' {
cells++
}
}
return cells
}
Loading