-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathanalyze.go
73 lines (66 loc) · 1.51 KB
/
analyze.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
package mdtsql
import (
"fmt"
"io"
"os"
"strconv"
"strings"
"github.com/olekukonko/tablewriter"
)
// Analyze parses the markdown file and returns the table information.
func Analyze(fileName string) ([]table, error) {
if fileName == "" {
return nil, fmt.Errorf("require markdown file")
}
if fileName == "-" {
fileName = "stdin"
}
if idx := strings.Index(fileName, "::"); idx != -1 {
fileName = fileName[:idx]
}
var reader io.Reader = os.Stdin
if fileName != "stdin" {
f, err := os.Open(fileName)
if err != nil {
return nil, err
}
defer f.Close()
reader = f
}
r := MDTReader{}
r.caption = Caption
if err := r.parse(reader); err != nil {
return nil, err
}
if len(r.tables) == 0 {
return nil, fmt.Errorf("no markdown table found")
}
tables := make([]table, 0, len(r.tables))
for i, node := range r.tables {
table, err := tableNode(r.source, node)
if err != nil {
return nil, err
}
if r.caption {
table.tableName = r.tableNames[i]
} else {
table.tableName = strconv.Itoa(i)
}
tables = append(tables, table)
}
return tables, nil
}
// Dump outputs the table information.
func Dump(w io.Writer, tables []table) {
for _, table := range tables {
fmt.Fprintf(w, "Table Name: [%s]\n", table.tableName)
typeTable := tablewriter.NewWriter(w)
typeTable.SetAutoFormatHeaders(false)
typeTable.SetHeader([]string{"column name", "type"})
for n, name := range table.names {
typeTable.Append([]string{name, table.types[n]})
}
typeTable.Render()
fmt.Fprintf(w, "\n")
}
}