-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
110 lines (88 loc) · 2.29 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
package main
import (
"bytes"
"embed"
"io/fs"
"os"
"strings"
"gopkg.in/yaml.v3"
)
//go:embed graphql
var schemas embed.FS
//go:embed model
var models embed.FS
var graphqlExtension = ".graphql"
type gqlgenConfig struct {
Schema []string `yaml:"schema"`
Model *struct {
Package string `yaml:"package"`
Filename string `yaml:"filename"`
}
AutoBind []string `yaml:"autobind"`
}
func main() {
config := readConfigFile()
generateSchema(config)
generateModel(config)
}
func generateSchema(config gqlgenConfig) {
dir, _ := schemas.ReadDir("graphql")
schemaDir := getSchemaDir(config)
for _, f := range dir {
filename := strings.Replace(f.Name(), ".graphql", graphqlExtension, 1)
contents, _ := fs.ReadFile(schemas, "graphql/"+filename)
os.WriteFile(schemaDir+"gorm-gqlgen-relay-"+filename, contents, fs.ModePerm)
}
}
func getSchemaDir(config gqlgenConfig) string {
for _, path := range config.Schema {
if strings.Contains(path, "*.graphql") {
return strings.Replace(path, "*.graphql", "", 1)
}
if strings.Contains(path, "*.graphqls") {
graphqlExtension = ".graphqls"
return strings.Replace(path, "*.graphqls", "", 1)
}
}
panic("No schema directory found (schema: *.graphql or *.graphqls)")
}
func readConfigFile() gqlgenConfig {
contents, err := os.ReadFile("./gqlgen.yml")
if err == nil {
return parseConfigFile(contents)
}
contents, err = os.ReadFile("./gqlgen.yaml")
if err != nil {
panic(err)
}
return parseConfigFile(contents)
}
func parseConfigFile(contents []byte) (config gqlgenConfig) {
if err := yaml.Unmarshal(contents, &config); err != nil {
panic(err)
}
if config.AutoBind == nil || len(config.AutoBind) == 0 {
panic("No autobind files found")
}
return
}
func generateModel(config gqlgenConfig) {
dir, _ := models.ReadDir("model")
modelDir := getModelDir(config)
for _, f := range dir {
contents, _ := fs.ReadFile(models, "model/"+f.Name())
os.WriteFile(
modelDir+"/gorm-gqlgen-relay-"+f.Name(),
bytes.Replace(contents, []byte("package model"), []byte("package "+config.Model.Package), 1),
fs.ModePerm,
)
}
}
func getModelDir(config gqlgenConfig) string {
if config.Model == nil {
return "./graph/model/"
}
split := strings.Split(config.Model.Filename, "/")
split = split[:len(split)-1]
return strings.Join(split, "/")
}