forked from OpsLevel/opslevel-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgen.go
307 lines (276 loc) · 7.98 KB
/
gen.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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
//go:build ignore
// +build ignore
package main
import (
"bytes"
"flag"
"fmt"
"go/format"
"log"
"os"
"sort"
"strconv"
"strings"
"text/template"
"unicode"
"github.com/Masterminds/sprig/v3"
"github.com/hasura/go-graphql-client/ident"
"github.com/opslevel/opslevel-go/v2023"
)
const (
enumFile string = "enum.go"
inputObjectFile string = "input.go"
)
type GraphQLSchema struct {
Types []GraphQLTypes `graphql:"types" json:"types"`
}
type IntrospectiveType struct {
Name string `graphql:"name" json:"name"`
Kind string `graphql:"kind" json:"kind"`
OfType struct {
OfTypeName string `graphql:"name" json:"name"`
} `graphql:"ofType" json:"ofType"`
}
type GraphQLInputValue struct {
Name string `graphql:"name" json:"name"`
DefaultValue string `graphql:"defaultValue" json:"defaultValue"`
Description string `graphql:"description" json:"description"`
Type IntrospectiveType `graphql:"type" json:"type"`
}
type GraphQLField struct {
Args []GraphQLInputValue `graphql:"args" json:"args"`
Description string `graphql:"description" json:"description"`
IsDeprecated bool `graphql:"isDeprecated" json:"isDeprecated"`
Name string `graphql:"name" json:"name"`
}
type GraphQLTypes struct {
Name string `graphql:"name" json:"name"`
Kind string `graphql:"kind" json:"kind"`
Description string `graphql:"description" json:"description"`
PossibleTypes []GraphQLPossibleType `graphql:"possibleTypes"`
EnumValues []GraphQLEnumValues `graphql:"enumValues" json:"enumValues"`
Fields []GraphQLField `graphql:"fields" json:"fields"`
InputFields []GraphQLInputValue `graphql:"inputFields" json:"inputFields"`
}
type GraphQLEnumValues struct {
Name string `graphql:"name" json:"name"`
Description string `graphql:"description" json:"description"`
}
type GraphQLPossibleType struct {
Name string
Kind string
OfType GraphQLOfType
}
type GraphQLOfType struct {
Name string
Kind string
}
func GetSchema(client *opslevel.Client) (*GraphQLSchema, error) {
var q struct {
Schema GraphQLSchema `graphql:"__schema"`
}
if err := client.Query(&q, nil); err != nil {
return nil, err
}
return &q.Schema, nil
}
func main() {
flag.Parse()
err := run()
if err != nil {
log.Fatalln(err)
}
}
func getRootSchema() (*GraphQLSchema, error) {
token, ok := os.LookupEnv("OPSLEVEL_API_TOKEN")
if !ok {
return nil, fmt.Errorf("OPSLEVEL_API_TOKEN environment variable not set")
}
client := opslevel.NewGQLClient(opslevel.SetAPIToken(token), opslevel.SetAPIVisibility("public"))
schema, err := GetSchema(client)
if err != nil {
return nil, err
}
return schema, nil
}
func run() error {
schema, err := getRootSchema()
if err != nil {
return err
}
enumSchema := GraphQLSchema{}
inputObjectSchema := GraphQLSchema{}
interfaceSchema := GraphQLSchema{}
objectSchema := GraphQLSchema{}
scalarSchema := GraphQLSchema{}
unionSchema := GraphQLSchema{}
for _, t := range schema.Types {
switch t.Kind {
case "ENUM":
enumSchema.Types = append(enumSchema.Types, t)
case "SCALAR":
scalarSchema.Types = append(scalarSchema.Types, t)
case "INTERFACE":
interfaceSchema.Types = append(interfaceSchema.Types, t)
case "INPUT_OBJECT":
inputObjectSchema.Types = append(inputObjectSchema.Types, t)
case "OBJECT":
objectSchema.Types = append(objectSchema.Types, t)
case "UNION":
unionSchema.Types = append(unionSchema.Types, t)
default:
panic("Unknown GraphQL type: " + t.Kind)
}
}
var buf bytes.Buffer
var subSchema GraphQLSchema
for filename, t := range templates {
switch filename {
case enumFile:
subSchema = enumSchema
case inputObjectFile:
subSchema = inputObjectSchema
default:
panic("Unknown file: " + filename)
}
err := t.Execute(&buf, subSchema)
if err != nil {
return err
}
out, err := format.Source(buf.Bytes())
if err != nil {
log.Println(err)
out = []byte("// gofmt error: " + err.Error() + "\n\n" + buf.String())
}
buf.Reset()
fmt.Println("writing", filename)
err = os.WriteFile(filename, out, 0o644)
if err != nil {
return err
}
}
return nil
}
// Filename -> Template.
var templates = map[string]*template.Template{
enumFile: t(`// Code generated by gen.go; DO NOT EDIT.
package opslevel
{{range .Types | sortByName}}{{if and (eq .Kind "ENUM") (not (internal .Name))}}
{{template "enum" .}}
{{end}}{{end}}
{{- define "enum" -}}
// {{.Name}} {{.Description | clean | endSentence}}
type {{.Name}} string
const ({{range .EnumValues}}
{{$.Name}}{{.Name | enumIdentifier}} {{$.Name}} = {{.Name | quote}} // {{.Description | clean | fullSentence}}{{end}}
)
// All {{$.Name}} as []string
var All{{$.Name}} = []string {
{{range .EnumValues}}string({{$.Name}}{{.Name | enumIdentifier}}),
{{end}}
}
{{- end -}}
`),
inputObjectFile: t(`// Code generated by gen.go; DO NOT EDIT.
package opslevel
{{range .Types | sortByName}}{{if and (eq .Kind "INPUT_OBJECT") (not (internal .Name))}}
{{template "input_object" .}}
{{end}}{{end}}
{{- define "input_object" -}}
// {{.Name}} {{.Description | clean | endSentence}}
type {{.Name}} struct { {{range .InputFields }}
// {{.Description | clean | fullSentence}} {{if eq .Type.Kind "NON_NULL"}}(Required.){{else}}(Optional.){{end}}
{{.Name | title}} {{.Type.OfType.OfTypeName | lowerStringType}} ` + "`" + `json:"{{.Name | lowerFirst }}{{if ne .Type.Kind "NON_NULL"}},omitempty{{end}}"` +
"`" + `{{end}}
}
{{- end -}}
`),
}
func t(text string) *template.Template {
// typeString returns a string representation of GraphQL type t.
var typeString func(t map[string]interface{}) string
typeString = func(t map[string]interface{}) string {
switch t["kind"] {
case "NON_NULL":
s := typeString(t["ofType"].(map[string]interface{}))
if !strings.HasPrefix(s, "*") {
panic(fmt.Errorf("nullable type %q doesn't begin with '*'", s))
}
return s[1:] // Strip star from nullable type to make it non-null.
case "LIST":
return "*[]" + typeString(t["ofType"].(map[string]interface{}))
default:
return "*" + t["name"].(string)
}
}
genTemplate := template.New("")
genTemplate.Funcs(templFuncMap)
genTemplate.Funcs(sprig.TxtFuncMap())
genTemplate.Funcs(template.FuncMap{"type": typeString})
return template.Must(genTemplate.Parse(text))
}
var templFuncMap = template.FuncMap{
"internal": func(s string) bool { return strings.HasPrefix(s, "__") },
"quote": strconv.Quote,
"join": strings.Join,
"lowerStringType": func(value string) string {
if value == "String" || value == "" {
return "string"
}
return value
},
"lowerFirst": func(value string) string {
for i, v := range value {
return string(unicode.ToLower(v)) + value[i+1:]
}
return value
},
"sortByName": func(types []GraphQLTypes) []GraphQLTypes {
sort.Slice(types, func(i, j int) bool {
ni := types[i].Name
nj := types[j].Name
return ni < nj
})
return types
},
"inputObjects": func(types []interface{}) []string {
var names []string
for _, t := range types {
t := t.(map[string]interface{})
if t["kind"].(string) != "INPUT_OBJECT" {
continue
}
names = append(names, t["name"].(string))
}
sort.Strings(names)
return names
},
"identifier": func(name string) string { return ident.ParseLowerCamelCase(name).ToMixedCaps() },
"enumIdentifier": func(name string) string { return ident.ParseScreamingSnakeCase(name).ToMixedCaps() },
"clean": func(s string) string { return strings.Join(strings.Fields(s), " ") },
"endSentence": func(s string) string {
if len(s) == 0 {
// Do nothing.
return ""
}
s = strings.ToLower(s[0:1]) + s[1:]
switch {
default:
s = "represents " + s
case strings.HasPrefix(s, "autogenerated "):
s = "is an " + s
case strings.HasPrefix(s, "specifies "):
// Do nothing.
}
if !strings.HasSuffix(s, ".") {
s += "."
}
return s
},
"fullSentence": func(s string) string {
if !strings.HasSuffix(s, ".") {
s += "."
}
return s
},
}