-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
255 lines (226 loc) · 5.78 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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
package main
import (
"log"
"os"
"github.com/urfave/cli"
"bufio"
"encoding/csv"
"io/ioutil"
"encoding/json"
"github.com/satori/go.uuid"
_ "io"
"io"
"fmt"
"strings"
)
var jsonFile ConfigFile
func main() {
app := cli.NewApp()
app.Name = "Csv-Manager"
app.Usage = "Get info from a csv and modify its headers"
app.Version="0.1.0"
var filePath string
var configPath string
app.Flags = []cli.Flag {
cli.StringFlag{
Name: "filepath, f",
Value: "",
Usage: "the CSV file path",
Destination: &filePath,
},
cli.StringFlag{
Name: "configp, c",
Value: "",
Usage: "the config file path",
Destination: &configPath,
},
}
app.Commands = []cli.Command{
{
Name: "headers",
Aliases: []string{"d"},
Usage: "Modify headers for a file",
Action: func(c *cli.Context) error {
if configPath != "" {
if filePath != ""{
ModifyHeaders(filePath)
} else {
log.Println("`filepath, f` flag has to be provided")
}
} else {
log.Println("`configp, c` flag has to be provided")
}
return nil
},
},
{
Name: "info",
Aliases: []string{"i"},
Usage: "info about the file",
Action: func(c *cli.Context) error {
//loadConfig(configPath)
//log.Println(jsonFile)
if filePath != ""{
log.Println("Getting the info for your csv... (it could take a few seconds)")
//Create the CsvModifier instance
csvModifier := CsvModifier{filePath, uuid.NewV4().String() + ".csv", nil}
//only modify the 1st line
headers := readHeaders(csvModifier.CsvToModifyPath)
headersInOne := "| "
for i:=0; i<len(headers); i++ {
headersInOne+=headers[i]+" | "
}
log.Printf("Headers: %s", headersInOne)
linesTotal := countCsvLines(csvModifier.CsvToModifyPath)
log.Printf("Total rows: %d", linesTotal)
} else {
log.Println("`filepath, f` flag has to be provided")
}
return nil
},
},
}
//sort.Sort(cli.Command(app.Commands))
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
/**
Modify the headers of the csv and returns a new csv with the headers changed
*/
func ModifyHeaders(filepath string) {
loadConfig("config.json")
//log.Println(jsonFile)
log.Println("Modifying the headers for your csv!")
//Create the CsvModifier instance
csvModifier := CsvModifier{filepath, uuid.NewV4().String() + ".csv", nil}
//only modify the 1st line
fileFrom, _ := os.Open(csvModifier.CsvToModifyPath)
linesTotal := countCsvLines(csvModifier.CsvToModifyPath)
linesProcessed := 0
log.Printf("Total lines: %d", linesTotal)
//defer
reader := csv.NewReader(bufio.NewReader(fileFrom))
line, _ := reader.Read()
newLine := csvModifier.changeNames(line)
//log.Println(line)
fileNew := csvModifier.createFile()
w := csv.NewWriter(fileNew)
w.Write(newLine)
linesProcessed++
w.Flush()
if err := w.Error(); err != nil {
log.Fatal(err)
}
//write the rest of the lines
for {
//w1 := csv.NewWriter(fileNew)
record, err2 := reader.Read()
if err2 == io.EOF {
break
}
if err2 != nil {
log.Fatal(err2)
}
//log.Println(record)
errW := w.Write(record)
if errW != nil {
log.Fatal(errW)
}
w.Flush()
linesProcessed++
fmt.Println(calculatePercentProcessed(linesProcessed, linesTotal))
}
fileFrom.Close()
fileNew.Close()
log.Printf("%d lines processed", linesProcessed)
}
/**
Calculate the percentage of the lines being processed
*/
func calculatePercentProcessed(processed int, total int) int{
return int(processed*100/total)
}
/**
This function counts and returns the amount of rows in a csv file
@params filepath -> the path of the file to be used by the function
*/
func countCsvLines(filepath string) int{
file, _ := os.Open(filepath)
fileScanner := bufio.NewScanner(file)
lineCount := 0
for fileScanner.Scan() {
lineCount++
}
file.Close()
return lineCount
}
func readHeaders(filepath string) []string{
fileFrom, _ := os.Open(filepath)
reader := csv.NewReader(bufio.NewReader(fileFrom))
line, _ := reader.Read()
return line
}
func loadConfig(path string) {
raw, err := ioutil.ReadFile(path)
if err != nil {
log.Fatalf("%s", err)
}
json.Unmarshal(raw, &jsonFile)
}
type ConfigFile struct {
OldNewNames map[string]string `json:"old_new_names"`
NameChanger string `json:"name_changer_instance"`
}
type CsvModifier struct {
CsvToModifyPath string
ResultCsvPath string
File *os.File
}
/**
Create a new file with a random name uuid
*/
func (cr *CsvModifier) createFile() (*os.File) {
filename := cr.ResultCsvPath
file, err := os.Create(filename)
if err != nil {
log.Fatalf("Error creating file %s.csv", filename)
} else {
log.Printf("%s file has been created", filename)
}
return file
}
/**
Changes values for a row, in this case it will be used to changed the headers based on the config file
*/
func (cr *CsvModifier) changeNames(vals []string) ([]string) {
changerName := jsonFile.NameChanger
changerInstance := FactoryNameChanger[changerName]
instanceOFChanger := changerInstance()
return instanceOFChanger.ModifyList(vals)
}
/**
Implement this interface those who need to get a different behavior for the headers values
*/
//////////////////////////////////////// ICHANGER INTERFACE ---------------------------------------
type fn func()IChanger
var FactoryNameChanger = map[string]fn{
"Upper": func() IChanger{return UpperChanger{}},
}
type IChanger interface{
ModifyList([]string)[]string
}
/**
This struct is going to convert the headers to upperCase from the values they already have
*/
type UpperChanger struct{
}
//This lines guaranties that UpperChanger is going to implement IChanger interface
var _ IChanger = (*UpperChanger)(nil)
func (uc UpperChanger) ModifyList(elList []string) []string {
for i, e:= range elList {
elList[i] = strings.ToUpper(e)
}
return elList
}