forked from shurcooL/githubv4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gen.go
258 lines (231 loc) 路 6.81 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
// +build ignore
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"go/format"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"sort"
"strconv"
"strings"
"text/template"
"github.com/shurcooL/graphql/ident"
)
func parseArgs(previewMode *bool) {
flag.BoolVar(previewMode, "p", false, "Allows generation of schema previews https://developer.github.com/v4/previews")
flag.Usage = func() {
fmt.Println("Usage: gen [options...]")
fmt.Println("Options:")
flag.PrintDefaults()
}
flag.Parse()
}
func main() {
previewMode := false
parseArgs(&previewMode)
const githubPublicSchema = "https://developer.github.com/v4/public_schema/schema.public.graphql"
publicSchema, err := getPublicSchema(githubPublicSchema)
if err != nil {
log.Fatalln(err)
}
mediaTypes := getMediaTypes(publicSchema)
err = run(previewMode, mediaTypes)
if err != nil {
log.Fatalln(err)
}
}
func getPublicSchema(fileUrl string) (string, error) {
resp, err := http.Get(fileUrl)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(body), nil
}
// getMediaTypes returns a list of header values that enable access to the GitHub API Preview Period features
// Check https://developer.github.com/changes/ for updates
func getMediaTypes(publicSchema string) []string {
re := regexp.MustCompile(`@preview\(toggledBy: \"(?P<media>[a-z-]+)-preview\"\)`)
matches := getRegexMatches(publicSchema, re)
mediaTypes := make([]string, 0)
for k := range matches {
mediaTypes = append(mediaTypes, k)
}
return mediaTypes
}
func getRegexMatches(publicSchema string, re *regexp.Regexp) map[string]bool {
groupNames := re.SubexpNames()
matches := make(map[string]bool)
for _, match := range re.FindAllStringSubmatch(publicSchema, -1) {
for groupIndex, group := range match {
name := groupNames[groupIndex]
if name == "" || matches[group] {
continue
}
matches[group] = true
}
}
return matches
}
func run(previewMode bool, mediaTypes []string) error {
githubToken, ok := os.LookupEnv("GITHUB_TOKEN")
if !ok {
return fmt.Errorf("GITHUB_TOKEN environment variable not set")
}
schema, err := loadSchema(githubToken, previewMode, mediaTypes)
if err != nil {
return err
}
for filename, t := range templates {
var buf bytes.Buffer
err := t.Execute(&buf, schema)
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())
}
fmt.Println("writing", filename)
err = ioutil.WriteFile(filename, out, 0644)
if err != nil {
return err
}
}
return nil
}
func loadSchema(githubToken string, previewMode bool, mediaTypes []string) (schema interface{}, err error) {
req, err := http.NewRequest("GET", "https://api.github.com/graphql", nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "bearer "+githubToken)
if previewMode {
for _, sp := range mediaTypes {
req.Header.Add("Accept", fmt.Sprintf("application/vnd.github.%s-preview+json", sp))
}
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
err = json.NewDecoder(resp.Body).Decode(&schema)
return schema, err
}
// Filename -> Template.
var templates = map[string]*template.Template{
"enum.go": t(`// Code generated by gen.go; DO NOT EDIT.
package githubv4
{{range .data.__schema.types | sortByName}}{{if and (eq .kind "ENUM") (not (internal .name))}}
{{template "enum" .}}
{{end}}{{end}}
{{- define "enum" -}}
// {{.name}} {{.description | clean | endSentence}}
type {{.name}} string
// {{.description | clean | fullSentence}}
const ({{range .enumValues}}
{{$.name}}{{.name | enumIdentifier}} {{$.name}} = {{.name | quote}} // {{.description | clean | fullSentence}}{{end}}
)
{{- end -}}
`),
"input.go": t(`// Code generated by gen.go; DO NOT EDIT.
package githubv4
// Input represents one of the Input structs:
//
// {{join (inputObjects .data.__schema.types) ", "}}.
type Input interface{}
{{range .data.__schema.types | sortByName}}{{if eq .kind "INPUT_OBJECT"}}
{{template "inputObject" .}}
{{end}}{{end}}
{{- define "inputObject" -}}
// {{.name}} {{.description | clean | endSentence}}
type {{.name}} struct {{"{"}}{{range .inputFields}}{{if eq .type.kind "NON_NULL"}}
// {{.description | clean | fullSentence}} (Required.)
{{.name | identifier}} {{.type | type}} ` + "`" + `json:"{{.name}}"` + "`" + `{{end}}{{end}}
{{range .inputFields}}{{if ne .type.kind "NON_NULL"}}
// {{.description | clean | fullSentence}} (Optional.)
{{.name | identifier}} {{.type | type}} ` + "`" + `json:"{{.name}},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)
}
}
return template.Must(template.New("").Funcs(template.FuncMap{
"internal": func(s string) bool { return strings.HasPrefix(s, "__") },
"quote": strconv.Quote,
"join": strings.Join,
"sortByName": func(types []interface{}) []interface{} {
sort.Slice(types, func(i, j int) bool {
ni := types[i].(map[string]interface{})["name"].(string)
nj := types[j].(map[string]interface{})["name"].(string)
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() },
"type": typeString,
"clean": func(s string) string { return strings.Join(strings.Fields(s), " ") },
"endSentence": func(s string) string {
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
},
}).Parse(text))
}