/
format.go
112 lines (91 loc) · 2.1 KB
/
format.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package show
import (
"io"
"os"
"strings"
"github.com/PuerkitoBio/goquery"
"github.com/olekukonko/tablewriter"
"github.com/Chyroc/phpmyadmin-cli/internal/common"
)
var out io.Writer = os.Stdout
func TestSetOut(w io.Writer) {
out = w
}
func parseFromHTML(html string) ([]string, [][]string, error) {
doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
if err != nil {
return nil, nil, err
}
var header []string
var datas [][]string
var columnLine = -1
var rowLine = -1
doc.Find("table").Each(func(i int, selection *goquery.Selection) {
if selection.HasClass("print_ignore") {
selection.Remove()
}
})
// header
doc.Find("tr").Each(func(j int, tr *goquery.Selection) {
if columnLine == -1 {
if strings.Contains(tr.Find("td").Text(), "Edit Copy") {
columnLine = 3
}
}
if rowLine == -1 {
if len(header) == 1 && (header[0] == "Database" || strings.HasPrefix(header[0], "Tables_in_")) {
rowLine = 0
}
}
tr.Find("th").Each(func(_ int, th *goquery.Selection) {
if th.Find("span").HasClass("tblcomment") {
th.Find("span").Remove()
}
thText := th.Text()
if thText != "" {
header = append(header, strings.TrimSpace(thText))
}
})
})
// datas
doc.Find("tr").Each(func(j int, tr *goquery.Selection) {
if j <= rowLine {
return
}
var data []string
tr.Find("td").Each(func(i int, td *goquery.Selection) {
if i <= columnLine {
return
}
data = append(data, td.Text())
})
if len(data) != 0 && (len(header) == 0 || (len(header) > 0 && len(header) == len(data))) {
datas = append(datas, data)
}
})
return header, datas, nil
}
// FromHTML Parse table from HTML
func ParseFromHTML(html string) error {
header, datas, err := parseFromHTML(html)
if err != nil {
return err
}
for _, v := range header {
common.Debug3("header [%s]\n", v)
}
for _, vv := range datas {
for _, v := range vv {
common.Debug3("datas [%s]\n", v)
}
}
t := tablewriter.NewWriter(out)
t.SetHeader(header)
t.SetAutoFormatHeaders(false)
t.SetAutoWrapText(false)
for _, v := range datas {
t.Append(v)
}
t.Render()
return nil
}