/
orgtbl.go
82 lines (72 loc) · 1.97 KB
/
orgtbl.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
/***************************************************************
*
* Copyright (c) 2015, Menglong TAN <tanmenglong@gmail.com>
*
* This program is free software; you can redistribute it
* and/or modify it under the terms of the BSD licence
*
**************************************************************/
/**
*
*
* @file orgtbl.go
* @author Menglong TAN <tanmenglong@gmail.com>
* @date Sat Oct 10 16:35:28 2015
*
**/
package gotabulate
import (
"fmt"
"strings"
)
//===================================================================
// Public APIs
//===================================================================
type OrgtblFormatter struct{}
func NewOrgtblFormatter() *OrgtblFormatter {
return &OrgtblFormatter{}
}
func (this *OrgtblFormatter) Format(info *TableInfo) string {
str := ""
var header []string
if info.FirstRowHeader && len(info.Data) > 0 {
header = info.Data[0]
} else {
header = info.Headers
}
str += this.formatLine(header, info)
str += this.formatHeaderSep(info)
rowStart := 0
if info.FirstRowHeader {
rowStart = 1
}
for i := rowStart; i < len(info.Data); i++ {
str += this.formatLine(info.Data[i], info)
}
return str
}
//===================================================================
// Private
//===================================================================
func (this *OrgtblFormatter) formatLine(row []string, info *TableInfo) string {
str := ""
l := len(row)
str += fmt.Sprintf("| %s%s ", row[0], strings.Repeat(" ", info.CellWidth[0]-len(row[0])))
for i := 1; i < info.ColumnSize; i++ {
v := ""
if i < l {
v = row[i]
}
str += fmt.Sprintf("| %s%s ", strings.Repeat(" ", info.CellWidth[i]-len(v)), v)
}
str += "|\n"
return str
}
func (this *OrgtblFormatter) formatHeaderSep(info *TableInfo) string {
str := fmt.Sprintf("|%s", strings.Repeat("-", info.CellWidth[0]+2))
for i := 1; i < info.ColumnSize; i++ {
str += fmt.Sprintf("+%s", strings.Repeat("-", info.CellWidth[i]+2))
}
str += "|\n"
return str
}