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
|
//go:build ignore
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"go/format"
"io"
"log"
"net/http"
"os"
"sort"
"strconv"
"strings"
"text/template"
"github.com/shurcooL/graphql/ident"
)
func main() {
flag.Parse()
err := run()
if err != nil {
log.Fatalln(err)
}
}
func run() error {
githubToken, ok := os.LookupEnv("GITHUB_TOKEN")
if !ok {
return fmt.Errorf("GITHUB_TOKEN environment variable not set")
}
schema, err := loadSchema(githubToken)
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 = os.WriteFile(filename, out, 0644)
if err != nil {
return err
}
}
return nil
}
func loadSchema(githubToken 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)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("non-200 OK status code: %v body: %q", resp.Status, body)
}
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}}
{{enumIdentifier $.name .name}} {{$.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(enum, value string) string {
var brandNames = map[string]string{ // Augments the list in ident.
"LINKEDIN": "LinkedIn",
"YOUTUBE": "YouTube",
}
switch brand, isBrand := brandNames[value]; {
case enum == "SponsorsCountryOrRegionCode":
// These enum values are country/region codes like "CA" or "US"
// rather than words, so don't try to convert them to mixed caps.
return enum + value
case value == "SCIM":
// An initialism or acronym that ident doesn't know about.
// Use it as is to preserve its consistent case (https://go.dev/s/style#initialisms).
return enum + value
case isBrand:
// Brand name that ident doesn't know about.
return enum + brand
default:
return enum + ident.ParseScreamingSnakeCase(value).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))
}
|