-
Notifications
You must be signed in to change notification settings - Fork 0
/
generator.go
106 lines (95 loc) · 2.11 KB
/
generator.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
package sequelie
import (
"bytes"
"errors"
"github.com/dave/jennifer/jen"
"golang.org/x/text/cases"
"golang.org/x/text/language"
"os"
"strings"
"sync"
)
var titleCaser = cases.Title(language.AmericanEnglish, cases.NoLower)
var importSequelie = []byte("import \"sequelie\"")
func renderQuery(key string, q *Query) string {
separatorIndex := strings.Index(key, ".")
if separatorIndex == -1 {
panic("cannot find the separator for the key")
}
token := key[separatorIndex+1:]
token = strings.ReplaceAll(token, "_", " ")
token = titleCaser.String(token)
token = strings.ReplaceAll(token, " ", "")
return jen.Var().
Id(token+"Query").
Op("=").
Qual("sequelie", "Query").
Call(jen.Lit(q.String())).
GoString()
}
func getPackage(key string) string {
separatorIndex := strings.Index(key, ".")
if separatorIndex == -1 {
panic("cannot find the separator for the key")
}
return strings.ToLower(key[:separatorIndex])
}
func flatten() map[string][][]byte {
var t = make(map[string][][]byte)
for k, v := range store {
pkg := getPackage(k)
t[pkg] = append(t[pkg], []byte(renderQuery(k, v)))
}
return t
}
func render(pkg string, declarations [][]byte) []byte {
t := [][]byte{
[]byte("package " + pkg),
{},
importSequelie,
{},
}
t = append(t, declarations...)
return bytes.Join(t, newLineBytes)
}
func Generate() error {
t := flatten()
var waitGroup sync.WaitGroup
var errs []error
for pkg, declarations := range t {
pkg := pkg
declarations := declarations
waitGroup.Add(1)
go func() {
defer waitGroup.Done()
rendered := render(pkg, declarations)
err := os.MkdirAll(".sequelie/"+pkg, os.ModePerm)
if err != nil {
errs = append(errs, err)
return
}
f, err := os.Create(".sequelie/" + pkg + "/queries.go")
if err != nil {
errs = append(errs, err)
return
}
defer func(f *os.File) {
err := f.Close()
if err != nil {
errs = append(errs, err)
return
}
}(f)
_, err = f.Write(rendered)
if err != nil {
errs = append(errs, err)
return
}
}()
}
waitGroup.Wait()
if len(errs) > 0 {
return errors.Join(errs...)
}
return nil
}