/
parse.go
113 lines (103 loc) · 2.04 KB
/
parse.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
package bqt
import (
"encoding/csv"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
)
type Replacement struct {
TableFullName string
ReplaceSql string
TableShortName string
}
/*
returns a Test structure given a filepath
*/
func ParseTest(path string) (Test, error) {
jsonFile, err := os.Open(path)
if err != nil {
return Test{}, err
}
bytes, err := ioutil.ReadAll(jsonFile)
if err != nil {
return Test{}, err
}
test := Test{}
if err := json.Unmarshal(bytes, &test); err != nil {
return Test{}, err
}
sqlQuery, err := ReadContents(test.File)
test.FileContent = sqlQuery
test.SourceFile = path
if err != nil {
return Test{}, err
}
return test, nil
}
/*
Given a folder returns a list of Test structs
*/
func ParseFolder(path string) ([]Test, error) {
files, err := ioutil.ReadDir(path)
tests := []Test{}
if err != nil {
return []Test{}, err
}
for _, f := range files {
if strings.HasSuffix(strings.ToLower(f.Name()), ".json") {
fullPath := filepath.Join(path, f.Name())
test, err := ParseTest(fullPath)
if err != nil {
return []Test{}, err
}
fmt.Println(fmt.Sprintf("Detected test: %v", fullPath))
tests = append(tests, test)
}
}
return tests, nil
}
/*
Utility Function, converts a CSV file into a List of dictionaries.
Each row is converted into a dictionary where the keys are columns.
*/
func CSVToMap(reader io.Reader) []map[string]string {
r := csv.NewReader(reader)
rows := []map[string]string{}
var header []string
for {
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
log.Fatal(err)
}
if header == nil {
header = record
} else {
dict := map[string]string{}
for i := range header {
dict[header[i]] = record[i]
}
rows = append(rows, dict)
}
}
return rows
}
func SaveSQL(path string, sql string) error {
err := os.MkdirAll(filepath.Dir(path), os.ModePerm)
if err != nil {
return err
}
data := []byte(sql)
err = ioutil.WriteFile(path, data, 0644)
if err != nil {
return err
}
return nil
}