-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtabulate.go
116 lines (101 loc) · 2.47 KB
/
tabulate.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
113
114
115
116
/***************************************************************
*
* Copyright (c) 2015, Menglong TAN <[email protected]>
*
* This program is free software; you can redistribute it
* and/or modify it under the terms of the BSD licence
*
**************************************************************/
/**
*
*
* @file tabulate.go
* @author Menglong TAN <[email protected]>
* @date Thu Oct 8 23:58:11 2015
*
**/
package gotabulate
import (
"fmt"
"strings"
)
//===================================================================
// Public APIs
//===================================================================
type TableInfo struct {
Headers []string
FirstRowHeader bool
Data [][]string
ColumnSize int
CellWidth []int
}
type Tabulator struct {
Headers []string
FirstRowHeader bool
Format string
}
const (
defaultFormat = "simple"
)
var formatters = map[string]Formatter{
"simple": NewSimpleFormatter(),
"orgtbl": NewOrgtblFormatter(),
"pipe": NewPipeFormatter(),
"plain": NewPlainFormatter(),
"psql": NewPsqlFormatter(),
"grid": NewGridFormatter(),
}
func NewTabulator() *Tabulator {
return &Tabulator{
FirstRowHeader: true,
Format: defaultFormat,
}
}
func (this *Tabulator) SetHeader(header []string) {
this.Headers = header
this.FirstRowHeader = false
}
func (this *Tabulator) SetFirstRowHeader(use bool) {
this.FirstRowHeader = use
}
func (this *Tabulator) SetFormat(format string) {
this.Format = format
}
func (this *Tabulator) Tabulate(data [][]string) string {
info := &TableInfo{
Headers: this.Headers,
FirstRowHeader: this.FirstRowHeader,
Data: data,
ColumnSize: 0,
CellWidth: []int{},
}
if !this.FirstRowHeader {
info.Update(info.Headers)
}
for _, row := range info.Data {
info.Update(row)
}
if formatter, ok := formatters[strings.ToLower(this.Format)]; ok {
return formatter.Format(info)
} else {
panic(fmt.Errorf("unsupported format: %s", this.Format))
}
}
//===================================================================
// Private
//===================================================================
func (this *TableInfo) Update(row []string) {
rowLen := len(row)
if rowLen > this.ColumnSize {
for i := 0; i < rowLen-this.ColumnSize; i++ {
this.CellWidth = append(this.CellWidth, 0)
}
this.ColumnSize = rowLen
}
for i := 0; i < rowLen; i++ {
l := len(row[i])
if l > this.CellWidth[i] {
this.CellWidth[i] = l
}
}
}