forked from Yamashou/gqlgenc
/
config.go
289 lines (235 loc) · 7.51 KB
/
config.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
package config
import (
"context"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/animeshon/gqlgen/codegen/config"
"github.com/animeshon/gqlgenc/client"
"github.com/animeshon/gqlgenc/introspection"
"github.com/pkg/errors"
"github.com/vektah/gqlparser/v2"
"github.com/vektah/gqlparser/v2/ast"
"github.com/vektah/gqlparser/v2/validator"
"golang.org/x/xerrors"
"gopkg.in/yaml.v2"
)
// Config extends the gqlgen basic config
// and represents the config file
type Config struct {
SchemaFilename StringList `yaml:"schema,omitempty"`
Model config.PackageConfig `yaml:"model,omitempty"`
Client config.PackageConfig `yaml:"client,omitempty"`
Models config.TypeMap `yaml:"models,omitempty"`
Endpoint *EndPointConfig `yaml:"endpoint,omitempty"`
Generate *GenerateConfig `yaml:"generate,omitempty"`
Query []string `yaml:"query"`
// gqlgen config struct
GQLConfig *config.Config `yaml:"-"`
}
var cfgFilenames = []string{".gqlgenc.yml", "gqlgenc.yml", "gqlgenc.yaml"}
// StringList is a simple array of strings
type StringList []string
// Has checks if the strings array has a give value
func (a StringList) Has(file string) bool {
for _, existing := range a {
if existing == file {
return true
}
}
return false
}
// LoadConfigFromDefaultLocations looks for a config file in the current directory, and all parent directories
// walking up the tree. The closest config file will be returned.
func LoadConfigFromDefaultLocations() (*Config, error) {
cfgFile, err := findCfg()
if err != nil {
return nil, err
}
err = os.Chdir(filepath.Dir(cfgFile))
if err != nil {
return nil, errors.Wrap(err, "unable to enter config dir")
}
return LoadConfig(cfgFile)
}
// EndPointConfig are the allowed options for the 'endpoint' config
type EndPointConfig struct {
URL string `yaml:"url"`
Headers map[string]string `yaml:"headers,omitempty"`
}
// findCfg searches for the config file in this directory and all parents up the tree
// looking for the closest match
func findCfg() (string, error) {
dir, err := os.Getwd()
if err != nil {
return "", errors.Wrap(err, "unable to get working dir to findCfg")
}
cfg := findCfgInDir(dir)
for cfg == "" && dir != filepath.Dir(dir) {
dir = filepath.Dir(dir)
cfg = findCfgInDir(dir)
}
if cfg == "" {
return "", os.ErrNotExist
}
return cfg, nil
}
func findCfgInDir(dir string) string {
for _, cfgName := range cfgFilenames {
path := filepath.Join(dir, cfgName)
if _, err := os.Stat(path); err == nil {
return path
}
}
return ""
}
var path2regex = strings.NewReplacer(
`.`, `\.`,
`*`, `.+`,
`\`, `[\\/]`,
`/`, `[\\/]`,
)
// LoadConfig loads and parses the config gqlgenc config
func LoadConfig(filename string) (*Config, error) {
var cfg Config
b, err := ioutil.ReadFile(filename)
if err != nil {
return nil, xerrors.Errorf("unable to read config: %w", err)
}
confContent := []byte(os.ExpandEnv(string(b)))
if err := yaml.UnmarshalStrict(confContent, &cfg); err != nil {
return nil, xerrors.Errorf("unable to parse config: %w", err)
}
if cfg.SchemaFilename != nil && cfg.Endpoint != nil {
return nil, errors.New("'schema' and 'endpoint' both specified. Use schema to load from a local file, use endpoint to load from a remote server (using introspection)")
}
if cfg.SchemaFilename == nil && cfg.Endpoint == nil {
return nil, errors.New("neither 'schema' nor 'endpoint' specified. Use schema to load from a local file, use endpoint to load from a remote server (using introspection)")
}
// https://github.com/99designs/gqlgen/blob/3a31a752df764738b1f6e99408df3b169d514784/codegen/config/config.go#L120
for _, f := range cfg.SchemaFilename {
var matches []string
// for ** we want to override default globbing patterns and walk all
// subdirectories to match schema files.
if strings.Contains(f, "**") {
pathParts := strings.SplitN(f, "**", 2)
rest := strings.TrimPrefix(strings.TrimPrefix(pathParts[1], `\`), `/`)
// turn the rest of the glob into a regex, anchored only at the end because ** allows
// for any number of dirs in between and walk will let us match against the full path name
globRe := regexp.MustCompile(path2regex.Replace(rest) + `$`)
if err := filepath.Walk(pathParts[0], func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if globRe.MatchString(strings.TrimPrefix(path, pathParts[0])) {
matches = append(matches, path)
}
return nil
}); err != nil {
return nil, errors.Wrapf(err, "failed to walk schema at root %s", pathParts[0])
}
} else {
matches, err = filepath.Glob(f)
if err != nil {
return nil, errors.Wrapf(err, "failed to glob schema filename %s", f)
}
}
files := StringList{}
for _, m := range matches {
if !files.Has(m) {
files = append(files, m)
}
}
cfg.SchemaFilename = files
}
models := make(config.TypeMap)
if cfg.Models != nil {
models = cfg.Models
}
sources := []*ast.Source{}
for _, filename := range cfg.SchemaFilename {
filename = filepath.ToSlash(filename)
var err error
var schemaRaw []byte
schemaRaw, err = ioutil.ReadFile(filename)
if err != nil {
return nil, errors.Wrap(err, "unable to open schema")
}
sources = append(sources, &ast.Source{Name: filename, Input: string(schemaRaw)})
}
cfg.GQLConfig = &config.Config{
Model: cfg.Model,
Models: models,
// TODO: gqlgen must be set exec but client not used
Exec: config.PackageConfig{Filename: "generated.go"},
Directives: map[string]config.DirectiveConfig{},
Sources: sources,
}
if err := cfg.Client.Check(); err != nil {
return nil, xerrors.Errorf("config.exec: %w", err)
}
return &cfg, nil
}
// LoadSchema load and parses the schema from a local file or a remote server
func (c *Config) LoadSchema(ctx context.Context) error {
var schema *ast.Schema
if c.SchemaFilename != nil {
s, err := c.loadLocalSchema()
if err != nil {
return xerrors.Errorf("load local schema failed: %w", err)
}
schema = s
} else {
s, err := c.loadRemoteSchema(ctx)
if err != nil {
return xerrors.Errorf("load remote schema failed: %w", err)
}
schema = s
}
if schema.Query == nil {
schema.Query = &ast.Definition{
Kind: ast.Object,
Name: "Query",
}
schema.Types["Query"] = schema.Query
}
c.GQLConfig.Schema = schema
return nil
}
func (c *Config) loadRemoteSchema(ctx context.Context) (*ast.Schema, error) {
addHeader := func(req *http.Request) {
for key, value := range c.Endpoint.Headers {
req.Header.Set(key, value)
}
}
gqlclient := client.NewClient(http.DefaultClient, c.Endpoint.URL, addHeader)
var res introspection.Query
if err := gqlclient.Post(ctx, "Query", introspection.Introspection, &res, nil); err != nil {
return nil, xerrors.Errorf("introspection query failed: %w", err)
}
schema, err := validator.ValidateSchemaDocument(introspection.ParseIntrospectionQuery(c.Endpoint.URL, res))
if err != nil {
return nil, xerrors.Errorf("validation error: %w", err)
}
return schema, nil
}
func (c *Config) loadLocalSchema() (*ast.Schema, error) {
schema, err := gqlparser.LoadSchema(c.GQLConfig.Sources...)
if err != nil {
return nil, err
}
return schema, nil
}
type GenerateConfig struct {
Prefix *NamingConfig `yaml:"prefix,omitempty"`
Suffix *NamingConfig `yaml:"suffix,omitempty"`
// if true, used client v2 in generate code
ClientV2 bool `yaml:"clientV2,omitempty"`
}
type NamingConfig struct {
Query string `yaml:"query,omitempty"`
Mutation string `yaml:"mutation,omitempty"`
}