-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
129 lines (108 loc) · 2.13 KB
/
main.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
117
118
119
120
121
122
123
124
125
126
127
128
129
package main
import (
"encoding/csv"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"strings"
"github.com/jedib0t/go-pretty/table"
ptable "github.com/jedib0t/go-pretty/table"
"github.com/jedib0t/go-pretty/text"
)
func main() {
var filepath *string
if len(os.Args) == 2 {
filepath = &os.Args[1]
} else {
filepath = flag.String("f", "", "filename")
}
flag.Parse()
table, err := read(*filepath)
if err != nil {
return
}
fmt.Println(table.Render())
}
func read(path string) (ptable.Writer, error) {
var r *csv.Reader
if path != "" {
file, OSErr := os.Open(path)
if OSErr != nil {
fmt.Println(OSErr)
return nil, OSErr
}
r = csv.NewReader(file)
} else {
stdin := readFromStdin()
input := strings.NewReader(stdin)
r = csv.NewReader(input)
}
r = configureCSVReader(r)
r.FieldsPerRecord = -1
r.TrimLeadingSpace = true
table := createTable()
for {
csvRow, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
log.Fatal(err)
continue
}
tableRow := make([]interface{}, len(csvRow))
for i := range tableRow {
tableRow[i] = csvRow[i]
}
table.AppendRow(tableRow)
}
return table, nil
}
func readFromStdin() string {
if !StdInHasData() {
fmt.Println("No data piped.")
return ""
}
bytes, err := ioutil.ReadAll(os.Stdin)
if err != nil {
fmt.Println("Failed to read stdin")
os.Exit(1)
}
return string(bytes)
}
func createTable() ptable.Writer {
t := table.NewWriter()
t.SetStyle(table.StyleLight)
t.Style().Format = table.FormatOptions{
Footer: text.FormatLower,
Header: text.FormatLower,
}
t.Style().Options.DrawBorder = true
t.Style().Options.SeparateColumns = true
t.Style().Options.SeparateFooter = true
t.Style().Options.SeparateHeader = true
return t
}
func configureCSVReader(r *csv.Reader) *csv.Reader {
// Enable variable number of columns per entry
r.FieldsPerRecord = -1
r.TrimLeadingSpace = true
return r
}
func StdInHasData() bool {
file := os.Stdin
fi, err := file.Stat()
if err != nil {
fmt.Println("file.Stat()", err)
return false
}
size := fi.Size()
if size <= 1 {
fmt.Println("Stdin is empty")
return false
}
return true
}