forked from olachat/gola
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
114 lines (95 loc) · 2.31 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
package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"go/format"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/olachat/gola/dolttpl"
"github.com/olachat/gola/mysqldriver"
"github.com/olachat/gola/structs"
"github.com/volatiletech/sqlboiler/v4/drivers"
"github.com/spf13/viper"
)
func main() {
viper.SetConfigName("gola")
wd, err := os.Getwd()
if err != nil {
wd = "."
}
configPaths := []string{wd}
for _, p := range configPaths {
viper.AddConfigPath(p)
}
viper.ReadInConfig()
viper.AutomaticEnv()
driverName := "mysql"
var config drivers.Config = viper.GetStringMap(driverName)
m := &mysqldriver.MySQLDriver{}
db, err := m.Assemble(config)
if err != nil {
panic(err)
}
output := config.DefaultString("output", "temp")
gentype := config.DefaultString("gentype", "orm")
if !strings.HasPrefix(output, "/") {
output = wd + string(filepath.Separator) + output
}
if !strings.HasSuffix(output, string(filepath.Separator)) {
output = output + string(filepath.Separator)
}
for _, t := range db.Tables {
println(t.Name)
switch gentype {
case "orm":
ioutil.WriteFile(output+t.Name+".go", genORM(db, t), 0644)
}
}
}
func genTPL(db *drivers.DBInfo, t drivers.Table, tplName string) []byte {
buf := bytes.NewBufferString("")
err := dolttpl.GetTpl(tplName).Execute(buf, structs.NewTableStruct(db, t, VERSION))
if err != nil {
panic(err)
}
return buf.Bytes()
}
func genORM(db *drivers.DBInfo, t drivers.Table) []byte {
return formatBuffer(genTPL(db, t, "00_struct.gogo"))
}
var (
rgxSyntaxError = regexp.MustCompile(`(\d+):\d+: `)
)
func formatBuffer(buf []byte) []byte {
output, err := format.Source(buf)
if err == nil {
return output
}
matches := rgxSyntaxError.FindStringSubmatch(err.Error())
if matches == nil {
panic(errors.New("failed to format template: " + err.Error()))
}
lineNum, _ := strconv.Atoi(matches[1])
scanner := bufio.NewScanner(bytes.NewReader(buf))
errBuf := &bytes.Buffer{}
line := 1
for ; scanner.Scan(); line++ {
if delta := line - lineNum; delta < -5 || delta > 5 {
continue
}
if line == lineNum {
errBuf.WriteString(">>>> ")
} else {
fmt.Fprintf(errBuf, "% 4d ", line)
}
errBuf.Write(scanner.Bytes())
errBuf.WriteByte('\n')
}
panic(fmt.Errorf("failed to format template\n\n%s", errBuf.Bytes()))
}