-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
107 lines (89 loc) · 2.3 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
package main
import (
"encoding/csv"
"flag"
"fmt"
"io"
"log"
"os"
"strings"
"github.com/soh335/sliceflag"
)
func main() {
var path, printColumns, sort string
var limit int
var filters []string
var isFiltersOr bool
flag.StringVar(&path, "path", "", "set csv file path")
flag.StringVar(&path, "p", "", "set csv file path")
flag.IntVar(&limit, "limit", 0, "set max display rows num")
flag.IntVar(&limit, "l", 0, "set max display rows num")
flag.StringVar(&printColumns, "columns", "", "print specify columns")
flag.StringVar(&printColumns, "c", "", "print specify columns")
flag.StringVar(&sort, "sort", "", "sort by set value\nex) id desc/ hoge_id asc")
flag.StringVar(&sort, "s", "", "sort by set value\nex) id desc/ hoge_id asc")
sliceflag.StringVar(flag.CommandLine, &filters, "f", []string{}, "filter")
sliceflag.StringVar(flag.CommandLine, &filters, "filter", []string{}, "filter")
flag.BoolVar(&isFiltersOr, "or", false, "filter logical operator")
flag.Parse()
d, err := loadData(path)
if err != nil {
log.Fatal("error load data", err.Error())
}
columns, rows, err := convertData(d)
if err != nil {
log.Fatal("error convet data", err.Error())
}
viewer := newCsviwer(columns, rows, printColumns, filters, limit, isFiltersOr)
viewer.Print(parseSort(sort))
}
func loadData(path string) (io.Reader, error) {
if path != "" {
return os.Open(path)
}
stdin := os.Stdin
stats, err := os.Stdin.Stat()
if err != nil {
return nil, err
}
if stats.Size() > 0 {
return stdin, nil
}
return nil, fmt.Errorf("data is emptry")
}
func convertData(data io.Reader) ([]string, [][]string, error) {
c := csv.NewReader(data)
column, err := c.Read()
if err != nil {
return []string{}, [][]string{}, err
}
var rows [][]string
for {
row, err := c.Read()
if err == io.EOF {
break
}
if err != nil {
return []string{}, [][]string{}, err
}
rows = append(rows, row)
}
return column, rows, nil
}
func parseSort(sort string) *sortOption {
_sort := strings.ToUpper(sort)
if !strings.Contains(_sort, "ASC") && !strings.Contains(_sort, "DESC") {
return nil
}
_sorts := strings.Split(sort, " ")
if len(_sorts) != 2 {
return nil
}
for i, s := range _sorts {
_sorts[i] = strings.TrimSpace(s)
}
return &sortOption{
column: _sorts[0],
sortType: strings.ToUpper(_sorts[1]),
}
}