/
stack.go
115 lines (102 loc) · 2.65 KB
/
stack.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
package cmd
import (
"errors"
"flag"
"io"
)
type StackSubcommand struct {
groupName string
groupsString string
useFilenames bool
}
func (sub *StackSubcommand) Name() string {
return "stack"
}
func (sub *StackSubcommand) Aliases() []string {
return []string{}
}
func (sub *StackSubcommand) Description() string {
return "Stack multiple CSVs into one CSV."
}
func (sub *StackSubcommand) SetFlags(fs *flag.FlagSet) {
fs.StringVar(&sub.groupName, "group-name", "", "Name of the column for grouping")
fs.StringVar(&sub.groupsString, "groups", "", "Group to display for each file")
fs.BoolVar(&sub.useFilenames, "filenames", false, "Use the filename for groups")
}
func (sub *StackSubcommand) Run(args []string) {
filenames := args
hasSpecifiedGroups := sub.groupsString != ""
if hasSpecifiedGroups && sub.useFilenames {
ExitWithError(errors.New("Cannot specify both --filename and --groups"))
}
shouldAppendGroup := hasSpecifiedGroups || sub.useFilenames
var groups []string
if hasSpecifiedGroups {
groups = GetArrayFromCsvString(sub.groupsString)
} else if sub.useFilenames {
groups = filenames
}
if shouldAppendGroup && len(filenames) != len(groups) {
ExitWithError(errors.New("Number of files and groups are not equal"))
}
var groupColumnName string
if sub.groupName != "" {
groupColumnName = sub.groupName
} else if sub.useFilenames {
groupColumnName = "File"
} else if shouldAppendGroup {
groupColumnName = "Group"
} else {
groupColumnName = ""
}
inputCsvs := GetInputCsvsOrPanic(filenames, -1)
StackFiles(inputCsvs, groupColumnName, groups)
}
func StackFiles(inputCsvs []*InputCsv, groupName string, groups []string) {
shouldAppendGroup := groupName != ""
outputCsv := NewOutputCsvFromInputCsvs(inputCsvs)
// Check that the headers match
headers := make([][]string, len(inputCsvs))
for i, inputCsv := range inputCsvs {
header, err := inputCsv.Read()
if err != nil {
ExitWithError(err)
}
headers[i] = header
}
firstHeader := headers[0]
for i, header := range headers {
if i == 0 {
continue
}
if len(firstHeader) != len(header) {
ExitWithError(errors.New("Headers do not match"))
}
for j, elem := range firstHeader {
if elem != header[j] {
ExitWithError(errors.New("Headers do not match"))
}
}
}
if shouldAppendGroup {
firstHeader = append(firstHeader, groupName)
}
outputCsv.Write(firstHeader)
// Go through the files
for i, inputCsv := range inputCsvs {
for {
row, err := inputCsv.Read()
if err != nil {
if err == io.EOF {
break
} else {
ExitWithError(err)
}
}
if shouldAppendGroup {
row = append(row, groups[i])
}
outputCsv.Write(row)
}
}
}