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-10-10 16:34:07 +02:00
|
|
|
func MarkdownTable(rows [][]string, cols []string, opt Options) string {
|
2022-04-15 09:42:07 +02:00
|
|
|
// Escape Markdown.
|
2022-10-10 16:34:07 +02:00
|
|
|
if opt.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-10-10 16:34:07 +02:00
|
|
|
Top: !opt.Valid,
|
|
|
|
Bottom: !opt.Valid,
|
2022-04-14 10:49:56 +02:00
|
|
|
}
|
|
|
|
|
2022-10-10 16:34:07 +02:00
|
|
|
// RenderFormat.
|
2022-04-14 10:49:56 +02:00
|
|
|
table := tablewriter.NewWriter(buf)
|
2022-04-14 12:18:05 +02:00
|
|
|
|
|
|
|
// Set Caption.
|
2022-10-10 16:34:07 +02:00
|
|
|
if opt.Caption != "" {
|
|
|
|
table.SetCaption(true, opt.Caption)
|
2022-04-14 12:18:05 +02:00
|
|
|
}
|
|
|
|
|
2022-10-10 16:34:07 +02:00
|
|
|
table.SetAutoWrapText(!opt.Valid && !opt.NoWrap)
|
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()
|
|
|
|
}
|