2022-04-14 10:49:56 +02:00
|
|
|
package report
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2022-04-15 09:42:07 +02:00
|
|
|
"strings"
|
2022-04-14 10:49:56 +02:00
|
|
|
|
|
|
|
"github.com/olekukonko/tablewriter"
|
|
|
|
)
|
|
|
|
|
2022-04-17 12:30:33 +02:00
|
|
|
// MarkdownTable returns a text-formatted table with caption, optionally as valid Markdown,
|
2022-04-14 10:49:56 +02:00
|
|
|
// so the output can be pasted into the docs.
|
2022-04-17 12:30:33 +02:00
|
|
|
func MarkdownTable(rows [][]string, cols []string, caption string, valid bool) string {
|
2022-04-15 09:42:07 +02:00
|
|
|
// Escape Markdown.
|
2022-04-17 12:30:33 +02:00
|
|
|
if valid {
|
2022-04-15 09:42:07 +02:00
|
|
|
for i := range rows {
|
|
|
|
for j := range rows[i] {
|
|
|
|
if strings.ContainsRune(rows[i][j], '|') {
|
|
|
|
rows[i][j] = strings.ReplaceAll(rows[i][j], "|", "\\|")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-14 10:49:56 +02:00
|
|
|
buf := &bytes.Buffer{}
|
|
|
|
|
2022-04-14 12:18:05 +02:00
|
|
|
// Set Borders.
|
2022-04-14 10:49:56 +02:00
|
|
|
borders := tablewriter.Border{
|
|
|
|
Left: true,
|
|
|
|
Right: true,
|
2022-04-17 12:30:33 +02:00
|
|
|
Top: !valid,
|
|
|
|
Bottom: !valid,
|
2022-04-14 10:49:56 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Render.
|
|
|
|
table := tablewriter.NewWriter(buf)
|
2022-04-14 12:18:05 +02:00
|
|
|
|
|
|
|
// Set Caption.
|
|
|
|
if caption != "" {
|
|
|
|
table.SetCaption(true, caption)
|
|
|
|
}
|
|
|
|
|
2022-04-17 12:30:33 +02:00
|
|
|
table.SetAutoWrapText(!valid)
|
2022-04-14 10:49:56 +02:00
|
|
|
table.SetAutoFormatHeaders(false)
|
|
|
|
table.SetHeader(cols)
|
|
|
|
table.SetBorders(borders)
|
|
|
|
table.SetCenterSeparator("|")
|
|
|
|
table.AppendBulk(rows)
|
|
|
|
table.Render()
|
|
|
|
|
|
|
|
return buf.String()
|
|
|
|
}
|