aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/github.com/99designs/gqlgen/codegen/config
diff options
context:
space:
mode:
authorMichael Muré <batolettre@gmail.com>2020-02-05 22:03:19 +0100
committerMichael Muré <batolettre@gmail.com>2020-02-05 22:33:03 +0100
commit1d4bb7ceb0cef79d68df0bacc913b01e40e6ddd6 (patch)
treee088b0fa43058afde1db71541d8fcb4b94905d6e /vendor/github.com/99designs/gqlgen/codegen/config
parentf093be96e98284580d61664adecd0a2ff8b354e4 (diff)
downloadgit-bug-1d4bb7ceb0cef79d68df0bacc913b01e40e6ddd6.tar.gz
migrate to go modules
Diffstat (limited to 'vendor/github.com/99designs/gqlgen/codegen/config')
-rw-r--r--vendor/github.com/99designs/gqlgen/codegen/config/binder.go448
-rw-r--r--vendor/github.com/99designs/gqlgen/codegen/config/config.go490
2 files changed, 0 insertions, 938 deletions
diff --git a/vendor/github.com/99designs/gqlgen/codegen/config/binder.go b/vendor/github.com/99designs/gqlgen/codegen/config/binder.go
deleted file mode 100644
index 72956de4..00000000
--- a/vendor/github.com/99designs/gqlgen/codegen/config/binder.go
+++ /dev/null
@@ -1,448 +0,0 @@
-package config
-
-import (
- "fmt"
- "go/token"
- "go/types"
-
- "github.com/99designs/gqlgen/codegen/templates"
- "github.com/99designs/gqlgen/internal/code"
- "github.com/pkg/errors"
- "github.com/vektah/gqlparser/ast"
- "golang.org/x/tools/go/packages"
-)
-
-// Binder connects graphql types to golang types using static analysis
-type Binder struct {
- pkgs map[string]*packages.Package
- schema *ast.Schema
- cfg *Config
- References []*TypeReference
-}
-
-func (c *Config) NewBinder(s *ast.Schema) (*Binder, error) {
- pkgs, err := packages.Load(&packages.Config{Mode: packages.LoadTypes | packages.LoadSyntax}, c.Models.ReferencedPackages()...)
- if err != nil {
- return nil, err
- }
-
- mp := map[string]*packages.Package{}
- for _, p := range pkgs {
- populatePkg(mp, p)
- for _, e := range p.Errors {
- if e.Kind == packages.ListError {
- return nil, p.Errors[0]
- }
- }
- }
-
- return &Binder{
- pkgs: mp,
- schema: s,
- cfg: c,
- }, nil
-}
-
-func populatePkg(mp map[string]*packages.Package, p *packages.Package) {
- imp := code.NormalizeVendor(p.PkgPath)
- if _, ok := mp[imp]; ok {
- return
- }
- mp[imp] = p
- for _, p := range p.Imports {
- populatePkg(mp, p)
- }
-}
-
-func (b *Binder) TypePosition(typ types.Type) token.Position {
- named, isNamed := typ.(*types.Named)
- if !isNamed {
- return token.Position{
- Filename: "unknown",
- }
- }
-
- return b.ObjectPosition(named.Obj())
-}
-
-func (b *Binder) ObjectPosition(typ types.Object) token.Position {
- if typ == nil {
- return token.Position{
- Filename: "unknown",
- }
- }
- pkg := b.getPkg(typ.Pkg().Path())
- return pkg.Fset.Position(typ.Pos())
-}
-
-func (b *Binder) FindType(pkgName string, typeName string) (types.Type, error) {
- obj, err := b.FindObject(pkgName, typeName)
- if err != nil {
- return nil, err
- }
-
- if fun, isFunc := obj.(*types.Func); isFunc {
- return fun.Type().(*types.Signature).Params().At(0).Type(), nil
- }
- return obj.Type(), nil
-}
-
-func (b *Binder) getPkg(find string) *packages.Package {
- imp := code.NormalizeVendor(find)
- if p, ok := b.pkgs[imp]; ok {
- return p
- }
- return nil
-}
-
-var MapType = types.NewMap(types.Typ[types.String], types.NewInterfaceType(nil, nil).Complete())
-var InterfaceType = types.NewInterfaceType(nil, nil)
-
-func (b *Binder) DefaultUserObject(name string) (types.Type, error) {
- models := b.cfg.Models[name].Model
- if len(models) == 0 {
- return nil, fmt.Errorf(name + " not found in typemap")
- }
-
- if models[0] == "map[string]interface{}" {
- return MapType, nil
- }
-
- if models[0] == "interface{}" {
- return InterfaceType, nil
- }
-
- pkgName, typeName := code.PkgAndType(models[0])
- if pkgName == "" {
- return nil, fmt.Errorf("missing package name for %s", name)
- }
-
- obj, err := b.FindObject(pkgName, typeName)
- if err != nil {
- return nil, err
- }
-
- return obj.Type(), nil
-}
-
-func (b *Binder) FindObject(pkgName string, typeName string) (types.Object, error) {
- if pkgName == "" {
- return nil, fmt.Errorf("package cannot be nil")
- }
- fullName := typeName
- if pkgName != "" {
- fullName = pkgName + "." + typeName
- }
-
- pkg := b.getPkg(pkgName)
- if pkg == nil {
- return nil, errors.Errorf("required package was not loaded: %s", fullName)
- }
-
- // function based marshalers take precedence
- for astNode, def := range pkg.TypesInfo.Defs {
- // only look at defs in the top scope
- if def == nil || def.Parent() == nil || def.Parent() != pkg.Types.Scope() {
- continue
- }
-
- if astNode.Name == "Marshal"+typeName {
- return def, nil
- }
- }
-
- // then look for types directly
- for astNode, def := range pkg.TypesInfo.Defs {
- // only look at defs in the top scope
- if def == nil || def.Parent() == nil || def.Parent() != pkg.Types.Scope() {
- continue
- }
-
- if astNode.Name == typeName {
- return def, nil
- }
- }
-
- return nil, errors.Errorf("unable to find type %s\n", fullName)
-}
-
-func (b *Binder) PointerTo(ref *TypeReference) *TypeReference {
- newRef := &TypeReference{
- GO: types.NewPointer(ref.GO),
- GQL: ref.GQL,
- CastType: ref.CastType,
- Definition: ref.Definition,
- Unmarshaler: ref.Unmarshaler,
- Marshaler: ref.Marshaler,
- IsMarshaler: ref.IsMarshaler,
- }
-
- b.References = append(b.References, newRef)
- return newRef
-}
-
-// TypeReference is used by args and field types. The Definition can refer to both input and output types.
-type TypeReference struct {
- Definition *ast.Definition
- GQL *ast.Type
- GO types.Type
- CastType types.Type // Before calling marshalling functions cast from/to this base type
- Marshaler *types.Func // When using external marshalling functions this will point to the Marshal function
- Unmarshaler *types.Func // When using external marshalling functions this will point to the Unmarshal function
- IsMarshaler bool // Does the type implement graphql.Marshaler and graphql.Unmarshaler
-}
-
-func (ref *TypeReference) Elem() *TypeReference {
- if p, isPtr := ref.GO.(*types.Pointer); isPtr {
- return &TypeReference{
- GO: p.Elem(),
- GQL: ref.GQL,
- CastType: ref.CastType,
- Definition: ref.Definition,
- Unmarshaler: ref.Unmarshaler,
- Marshaler: ref.Marshaler,
- IsMarshaler: ref.IsMarshaler,
- }
- }
-
- if ref.IsSlice() {
- return &TypeReference{
- GO: ref.GO.(*types.Slice).Elem(),
- GQL: ref.GQL.Elem,
- CastType: ref.CastType,
- Definition: ref.Definition,
- Unmarshaler: ref.Unmarshaler,
- Marshaler: ref.Marshaler,
- IsMarshaler: ref.IsMarshaler,
- }
- }
- return nil
-}
-
-func (t *TypeReference) IsPtr() bool {
- _, isPtr := t.GO.(*types.Pointer)
- return isPtr
-}
-
-func (t *TypeReference) IsNilable() bool {
- _, isPtr := t.GO.(*types.Pointer)
- _, isMap := t.GO.(*types.Map)
- _, isInterface := t.GO.(*types.Interface)
- return isPtr || isMap || isInterface
-}
-
-func (t *TypeReference) IsSlice() bool {
- _, isSlice := t.GO.(*types.Slice)
- return t.GQL.Elem != nil && isSlice
-}
-
-func (t *TypeReference) IsNamed() bool {
- _, isSlice := t.GO.(*types.Named)
- return isSlice
-}
-
-func (t *TypeReference) IsStruct() bool {
- _, isStruct := t.GO.Underlying().(*types.Struct)
- return isStruct
-}
-
-func (t *TypeReference) IsScalar() bool {
- return t.Definition.Kind == ast.Scalar
-}
-
-func (t *TypeReference) UniquenessKey() string {
- var nullability = "O"
- if t.GQL.NonNull {
- nullability = "N"
- }
-
- return nullability + t.Definition.Name + "2" + templates.TypeIdentifier(t.GO)
-}
-
-func (t *TypeReference) MarshalFunc() string {
- if t.Definition == nil {
- panic(errors.New("Definition missing for " + t.GQL.Name()))
- }
-
- if t.Definition.Kind == ast.InputObject {
- return ""
- }
-
- return "marshal" + t.UniquenessKey()
-}
-
-func (t *TypeReference) UnmarshalFunc() string {
- if t.Definition == nil {
- panic(errors.New("Definition missing for " + t.GQL.Name()))
- }
-
- if !t.Definition.IsInputType() {
- return ""
- }
-
- return "unmarshal" + t.UniquenessKey()
-}
-
-func (b *Binder) PushRef(ret *TypeReference) {
- b.References = append(b.References, ret)
-}
-
-func isMap(t types.Type) bool {
- if t == nil {
- return true
- }
- _, ok := t.(*types.Map)
- return ok
-}
-
-func isIntf(t types.Type) bool {
- if t == nil {
- return true
- }
- _, ok := t.(*types.Interface)
- return ok
-}
-
-func (b *Binder) TypeReference(schemaType *ast.Type, bindTarget types.Type) (ret *TypeReference, err error) {
- var pkgName, typeName string
- def := b.schema.Types[schemaType.Name()]
- defer func() {
- if err == nil && ret != nil {
- b.PushRef(ret)
- }
- }()
-
- if len(b.cfg.Models[schemaType.Name()].Model) == 0 {
- return nil, fmt.Errorf("%s was not found", schemaType.Name())
- }
-
- for _, model := range b.cfg.Models[schemaType.Name()].Model {
- if model == "map[string]interface{}" {
- if !isMap(bindTarget) {
- continue
- }
- return &TypeReference{
- Definition: def,
- GQL: schemaType,
- GO: MapType,
- }, nil
- }
-
- if model == "interface{}" {
- if !isIntf(bindTarget) {
- continue
- }
- return &TypeReference{
- Definition: def,
- GQL: schemaType,
- GO: InterfaceType,
- }, nil
- }
-
- pkgName, typeName = code.PkgAndType(model)
- if pkgName == "" {
- return nil, fmt.Errorf("missing package name for %s", schemaType.Name())
- }
-
- ref := &TypeReference{
- Definition: def,
- GQL: schemaType,
- }
-
- obj, err := b.FindObject(pkgName, typeName)
- if err != nil {
- return nil, err
- }
-
- if fun, isFunc := obj.(*types.Func); isFunc {
- ref.GO = fun.Type().(*types.Signature).Params().At(0).Type()
- ref.Marshaler = fun
- ref.Unmarshaler = types.NewFunc(0, fun.Pkg(), "Unmarshal"+typeName, nil)
- } else if hasMethod(obj.Type(), "MarshalGQL") && hasMethod(obj.Type(), "UnmarshalGQL") {
- ref.GO = obj.Type()
- ref.IsMarshaler = true
- } else if underlying := basicUnderlying(obj.Type()); def.IsLeafType() && underlying != nil && underlying.Kind() == types.String {
- // Special case for named types wrapping strings. Used by default enum implementations.
-
- ref.GO = obj.Type()
- ref.CastType = underlying
-
- underlyingRef, err := b.TypeReference(&ast.Type{NamedType: "String"}, nil)
- if err != nil {
- return nil, err
- }
-
- ref.Marshaler = underlyingRef.Marshaler
- ref.Unmarshaler = underlyingRef.Unmarshaler
- } else {
- ref.GO = obj.Type()
- }
-
- ref.GO = b.CopyModifiersFromAst(schemaType, ref.GO)
-
- if bindTarget != nil {
- if err = code.CompatibleTypes(ref.GO, bindTarget); err != nil {
- continue
- }
- ref.GO = bindTarget
- }
-
- return ref, nil
- }
-
- return nil, fmt.Errorf("%s has type compatible with %s", schemaType.Name(), bindTarget.String())
-}
-
-func (b *Binder) CopyModifiersFromAst(t *ast.Type, base types.Type) types.Type {
- if t.Elem != nil {
- child := b.CopyModifiersFromAst(t.Elem, base)
- if _, isStruct := child.Underlying().(*types.Struct); isStruct {
- child = types.NewPointer(child)
- }
- return types.NewSlice(child)
- }
-
- var isInterface bool
- if named, ok := base.(*types.Named); ok {
- _, isInterface = named.Underlying().(*types.Interface)
- }
-
- if !isInterface && !t.NonNull {
- return types.NewPointer(base)
- }
-
- return base
-}
-
-func hasMethod(it types.Type, name string) bool {
- if ptr, isPtr := it.(*types.Pointer); isPtr {
- it = ptr.Elem()
- }
- namedType, ok := it.(*types.Named)
- if !ok {
- return false
- }
-
- for i := 0; i < namedType.NumMethods(); i++ {
- if namedType.Method(i).Name() == name {
- return true
- }
- }
- return false
-}
-
-func basicUnderlying(it types.Type) *types.Basic {
- if ptr, isPtr := it.(*types.Pointer); isPtr {
- it = ptr.Elem()
- }
- namedType, ok := it.(*types.Named)
- if !ok {
- return nil
- }
-
- if basic, ok := namedType.Underlying().(*types.Basic); ok {
- return basic
- }
-
- return nil
-}
diff --git a/vendor/github.com/99designs/gqlgen/codegen/config/config.go b/vendor/github.com/99designs/gqlgen/codegen/config/config.go
deleted file mode 100644
index 8e8992e3..00000000
--- a/vendor/github.com/99designs/gqlgen/codegen/config/config.go
+++ /dev/null
@@ -1,490 +0,0 @@
-package config
-
-import (
- "fmt"
- "go/types"
- "io/ioutil"
- "os"
- "path/filepath"
- "regexp"
- "sort"
- "strings"
-
- "golang.org/x/tools/go/packages"
-
- "github.com/99designs/gqlgen/internal/code"
- "github.com/pkg/errors"
- "github.com/vektah/gqlparser"
- "github.com/vektah/gqlparser/ast"
- "gopkg.in/yaml.v2"
-)
-
-type Config struct {
- SchemaFilename StringList `yaml:"schema,omitempty"`
- Exec PackageConfig `yaml:"exec"`
- Model PackageConfig `yaml:"model"`
- Resolver PackageConfig `yaml:"resolver,omitempty"`
- AutoBind []string `yaml:"autobind"`
- Models TypeMap `yaml:"models,omitempty"`
- StructTag string `yaml:"struct_tag,omitempty"`
- Directives map[string]DirectiveConfig `yaml:"directives,omitempty"`
-}
-
-var cfgFilenames = []string{".gqlgen.yml", "gqlgen.yml", "gqlgen.yaml"}
-
-// DefaultConfig creates a copy of the default config
-func DefaultConfig() *Config {
- return &Config{
- SchemaFilename: StringList{"schema.graphql"},
- Model: PackageConfig{Filename: "models_gen.go"},
- Exec: PackageConfig{Filename: "generated.go"},
- Directives: map[string]DirectiveConfig{},
- }
-}
-
-// 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)
-}
-
-var path2regex = strings.NewReplacer(
- `.`, `\.`,
- `*`, `.+`,
- `\`, `[\\/]`,
- `/`, `[\\/]`,
-)
-
-// LoadConfig reads the gqlgen.yml config file
-func LoadConfig(filename string) (*Config, error) {
- config := DefaultConfig()
-
- b, err := ioutil.ReadFile(filename)
- if err != nil {
- return nil, errors.Wrap(err, "unable to read config")
- }
-
- if err := yaml.UnmarshalStrict(b, config); err != nil {
- return nil, errors.Wrap(err, "unable to parse config")
- }
-
- defaultDirectives := map[string]DirectiveConfig{
- "skip": {SkipRuntime: true},
- "include": {SkipRuntime: true},
- "deprecated": {SkipRuntime: true},
- }
-
- for key, value := range defaultDirectives {
- if _, defined := config.Directives[key]; !defined {
- config.Directives[key] = value
- }
- }
-
- preGlobbing := config.SchemaFilename
- config.SchemaFilename = StringList{}
- for _, f := range preGlobbing {
- 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)
- }
- }
-
- for _, m := range matches {
- if config.SchemaFilename.Has(m) {
- continue
- }
- config.SchemaFilename = append(config.SchemaFilename, m)
- }
- }
-
- return config, nil
-}
-
-type PackageConfig struct {
- Filename string `yaml:"filename,omitempty"`
- Package string `yaml:"package,omitempty"`
- Type string `yaml:"type,omitempty"`
-}
-
-type TypeMapEntry struct {
- Model StringList `yaml:"model"`
- Fields map[string]TypeMapField `yaml:"fields,omitempty"`
-}
-
-type TypeMapField struct {
- Resolver bool `yaml:"resolver"`
- FieldName string `yaml:"fieldName"`
-}
-
-type StringList []string
-
-func (a *StringList) UnmarshalYAML(unmarshal func(interface{}) error) error {
- var single string
- err := unmarshal(&single)
- if err == nil {
- *a = []string{single}
- return nil
- }
-
- var multi []string
- err = unmarshal(&multi)
- if err != nil {
- return err
- }
-
- *a = multi
- return nil
-}
-
-func (a StringList) Has(file string) bool {
- for _, existing := range a {
- if existing == file {
- return true
- }
- }
- return false
-}
-
-func (c *PackageConfig) normalize() error {
- if c.Filename == "" {
- return errors.New("Filename is required")
- }
- c.Filename = abs(c.Filename)
- // If Package is not set, first attempt to load the package at the output dir. If that fails
- // fallback to just the base dir name of the output filename.
- if c.Package == "" {
- c.Package = code.NameForDir(c.Dir())
- }
-
- return nil
-}
-
-func (c *PackageConfig) ImportPath() string {
- return code.ImportPathForDir(c.Dir())
-}
-
-func (c *PackageConfig) Dir() string {
- return filepath.Dir(c.Filename)
-}
-
-func (c *PackageConfig) Check() error {
- if strings.ContainsAny(c.Package, "./\\") {
- return fmt.Errorf("package should be the output package name only, do not include the output filename")
- }
- if c.Filename != "" && !strings.HasSuffix(c.Filename, ".go") {
- return fmt.Errorf("filename should be path to a go source file")
- }
-
- return c.normalize()
-}
-
-func (c *PackageConfig) Pkg() *types.Package {
- return types.NewPackage(c.ImportPath(), c.Dir())
-}
-
-func (c *PackageConfig) IsDefined() bool {
- return c.Filename != ""
-}
-
-func (c *Config) Check() error {
- if err := c.Models.Check(); err != nil {
- return errors.Wrap(err, "config.models")
- }
- if err := c.Exec.Check(); err != nil {
- return errors.Wrap(err, "config.exec")
- }
- if err := c.Model.Check(); err != nil {
- return errors.Wrap(err, "config.model")
- }
- if c.Resolver.IsDefined() {
- if err := c.Resolver.Check(); err != nil {
- return errors.Wrap(err, "config.resolver")
- }
- }
-
- // check packages names against conflict, if present in the same dir
- // and check filenames for uniqueness
- packageConfigList := []PackageConfig{
- c.Model,
- c.Exec,
- c.Resolver,
- }
- filesMap := make(map[string]bool)
- pkgConfigsByDir := make(map[string]PackageConfig)
- for _, current := range packageConfigList {
- _, fileFound := filesMap[current.Filename]
- if fileFound {
- return fmt.Errorf("filename %s defined more than once", current.Filename)
- }
- filesMap[current.Filename] = true
- previous, inSameDir := pkgConfigsByDir[current.Dir()]
- if inSameDir && current.Package != previous.Package {
- return fmt.Errorf("filenames %s and %s are in the same directory but have different package definitions", stripPath(current.Filename), stripPath(previous.Filename))
- }
- pkgConfigsByDir[current.Dir()] = current
- }
-
- return c.normalize()
-}
-
-func stripPath(path string) string {
- return filepath.Base(path)
-}
-
-type TypeMap map[string]TypeMapEntry
-
-func (tm TypeMap) Exists(typeName string) bool {
- _, ok := tm[typeName]
- return ok
-}
-
-func (tm TypeMap) UserDefined(typeName string) bool {
- m, ok := tm[typeName]
- return ok && len(m.Model) > 0
-}
-
-func (tm TypeMap) Check() error {
- for typeName, entry := range tm {
- for _, model := range entry.Model {
- if strings.LastIndex(model, ".") < strings.LastIndex(model, "/") {
- return fmt.Errorf("model %s: invalid type specifier \"%s\" - you need to specify a struct to map to", typeName, entry.Model)
- }
- }
- }
- return nil
-}
-
-func (tm TypeMap) ReferencedPackages() []string {
- var pkgs []string
-
- for _, typ := range tm {
- for _, model := range typ.Model {
- if model == "map[string]interface{}" || model == "interface{}" {
- continue
- }
- pkg, _ := code.PkgAndType(model)
- if pkg == "" || inStrSlice(pkgs, pkg) {
- continue
- }
- pkgs = append(pkgs, code.QualifyPackagePath(pkg))
- }
- }
-
- sort.Slice(pkgs, func(i, j int) bool {
- return pkgs[i] > pkgs[j]
- })
- return pkgs
-}
-
-func (tm TypeMap) Add(name string, goType string) {
- modelCfg := tm[name]
- modelCfg.Model = append(modelCfg.Model, goType)
- tm[name] = modelCfg
-}
-
-type DirectiveConfig struct {
- SkipRuntime bool `yaml:"skip_runtime"`
-}
-
-func inStrSlice(haystack []string, needle string) bool {
- for _, v := range haystack {
- if needle == v {
- return true
- }
- }
-
- return false
-}
-
-// 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 ""
-}
-
-func (c *Config) normalize() error {
- if err := c.Model.normalize(); err != nil {
- return errors.Wrap(err, "model")
- }
-
- if err := c.Exec.normalize(); err != nil {
- return errors.Wrap(err, "exec")
- }
-
- if c.Resolver.IsDefined() {
- if err := c.Resolver.normalize(); err != nil {
- return errors.Wrap(err, "resolver")
- }
- }
-
- if c.Models == nil {
- c.Models = TypeMap{}
- }
-
- return nil
-}
-
-func (c *Config) Autobind(s *ast.Schema) error {
- if len(c.AutoBind) == 0 {
- return nil
- }
- ps, err := packages.Load(&packages.Config{Mode: packages.LoadTypes}, c.AutoBind...)
- if err != nil {
- return err
- }
-
- for _, t := range s.Types {
- if c.Models.UserDefined(t.Name) {
- continue
- }
-
- for _, p := range ps {
- if t := p.Types.Scope().Lookup(t.Name); t != nil {
- c.Models.Add(t.Name(), t.Pkg().Path()+"."+t.Name())
- break
- }
- }
- }
-
- return nil
-}
-
-func (c *Config) InjectBuiltins(s *ast.Schema) {
- builtins := TypeMap{
- "__Directive": {Model: StringList{"github.com/99designs/gqlgen/graphql/introspection.Directive"}},
- "__DirectiveLocation": {Model: StringList{"github.com/99designs/gqlgen/graphql.String"}},
- "__Type": {Model: StringList{"github.com/99designs/gqlgen/graphql/introspection.Type"}},
- "__TypeKind": {Model: StringList{"github.com/99designs/gqlgen/graphql.String"}},
- "__Field": {Model: StringList{"github.com/99designs/gqlgen/graphql/introspection.Field"}},
- "__EnumValue": {Model: StringList{"github.com/99designs/gqlgen/graphql/introspection.EnumValue"}},
- "__InputValue": {Model: StringList{"github.com/99designs/gqlgen/graphql/introspection.InputValue"}},
- "__Schema": {Model: StringList{"github.com/99designs/gqlgen/graphql/introspection.Schema"}},
- "Float": {Model: StringList{"github.com/99designs/gqlgen/graphql.Float"}},
- "String": {Model: StringList{"github.com/99designs/gqlgen/graphql.String"}},
- "Boolean": {Model: StringList{"github.com/99designs/gqlgen/graphql.Boolean"}},
- "Int": {Model: StringList{
- "github.com/99designs/gqlgen/graphql.Int",
- "github.com/99designs/gqlgen/graphql.Int32",
- "github.com/99designs/gqlgen/graphql.Int64",
- }},
- "ID": {
- Model: StringList{
- "github.com/99designs/gqlgen/graphql.ID",
- "github.com/99designs/gqlgen/graphql.IntID",
- },
- },
- }
-
- for typeName, entry := range builtins {
- if !c.Models.Exists(typeName) {
- c.Models[typeName] = entry
- }
- }
-
- // These are additional types that are injected if defined in the schema as scalars.
- extraBuiltins := TypeMap{
- "Time": {Model: StringList{"github.com/99designs/gqlgen/graphql.Time"}},
- "Map": {Model: StringList{"github.com/99designs/gqlgen/graphql.Map"}},
- "Upload": {Model: StringList{"github.com/99designs/gqlgen/graphql.Upload"}},
- "Any": {Model: StringList{"github.com/99designs/gqlgen/graphql.Any"}},
- }
-
- for typeName, entry := range extraBuiltins {
- if t, ok := s.Types[typeName]; !c.Models.Exists(typeName) && ok && t.Kind == ast.Scalar {
- c.Models[typeName] = entry
- }
- }
-}
-
-func (c *Config) LoadSchema() (*ast.Schema, map[string]string, error) {
- schemaStrings := map[string]string{}
-
- sources := make([]*ast.Source, len(c.SchemaFilename))
-
- for i, filename := range c.SchemaFilename {
- filename = filepath.ToSlash(filename)
- var err error
- var schemaRaw []byte
- schemaRaw, err = ioutil.ReadFile(filename)
- if err != nil {
- fmt.Fprintln(os.Stderr, "unable to open schema: "+err.Error())
- os.Exit(1)
- }
- schemaStrings[filename] = string(schemaRaw)
- sources[i] = &ast.Source{Name: filename, Input: schemaStrings[filename]}
- }
-
- schema, err := gqlparser.LoadSchema(sources...)
- if err != nil {
- return nil, nil, err
- }
- return schema, schemaStrings, nil
-}
-
-func abs(path string) string {
- absPath, err := filepath.Abs(path)
- if err != nil {
- panic(err)
- }
- return filepath.ToSlash(absPath)
-}