-
Notifications
You must be signed in to change notification settings - Fork 11
/
tablib_tabular.go
72 lines (66 loc) · 2.12 KB
/
tablib_tabular.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package tablib
import (
"github.com/bndr/gotabulate"
"regexp"
"strings"
"unicode/utf8"
)
var (
// TabularGrid is the value to be passed to gotabulate to render the table
// as ASCII table with grid format
TabularGrid = "grid"
// TabularSimple is the value to be passed to gotabulate to render the table
// as ASCII table with simple format
TabularSimple = "simple"
// TabularCondensed is the value to be passed to gotabulate to render the table
// as ASCII table with condensed format
TabularCondensed = "condensed"
// TabularMarkdown is the value to be passed to gotabulate to render the table
// as ASCII table with Markdown format
TabularMarkdown = "markdown"
)
// Markdown returns a Markdown table Exportable representation of the Dataset.
func (d *Dataset) Markdown() *Exportable {
return d.Tabular(TabularMarkdown)
}
// Tabular returns a tabular Exportable representation of the Dataset.
// format is either grid, simple, condensed or markdown.
func (d *Dataset) Tabular(format string) *Exportable {
back := d.Records()
t := gotabulate.Create(back)
if format == TabularCondensed || format == TabularMarkdown {
rendered := regexp.MustCompile("\n\n\\s").ReplaceAllString(t.Render("simple"), "\n ")
if format == TabularMarkdown {
firstLine := regexp.MustCompile("-\\s+-").ReplaceAllString(strings.Split(rendered, "\n")[0], "- | -")
// now just locate the position of pipe characterds, and set them
positions := make([]int, 0, d.cols-1)
x := 0
for _, c := range firstLine {
if c == '|' {
positions = append(positions, x)
}
x += utf8.RuneLen(c)
}
b := newBuffer()
lines := strings.Split(rendered, "\n")
for _, line := range lines[1 : len(lines)-2] {
ipos := 0
b.WriteString("| ")
for _, pos := range positions {
if ipos < len(line) && pos < len(line) {
b.WriteString(line[ipos:pos])
b.WriteString(" | ")
ipos = pos + 1
}
}
if ipos < len(line) {
b.WriteString(line[ipos:])
}
b.WriteString(" | \n")
}
return newExportable(b)
}
return newExportableFromString(rendered)
}
return newExportableFromString(t.Render(format))
}