github.com/apipluspower/gqlgen@v0.15.2/codegen/config/resolver.go (about) 1 package config 2 3 import ( 4 "fmt" 5 "go/types" 6 "path/filepath" 7 "strings" 8 9 "github.com/apipluspower/gqlgen/internal/code" 10 ) 11 12 type ResolverConfig struct { 13 Filename string `yaml:"filename,omitempty"` 14 FilenameTemplate string `yaml:"filename_template,omitempty"` 15 Package string `yaml:"package,omitempty"` 16 Type string `yaml:"type,omitempty"` 17 Layout ResolverLayout `yaml:"layout,omitempty"` 18 DirName string `yaml:"dir"` 19 } 20 21 type ResolverLayout string 22 23 var ( 24 LayoutSingleFile ResolverLayout = "single-file" 25 LayoutFollowSchema ResolverLayout = "follow-schema" 26 ) 27 28 func (r *ResolverConfig) Check() error { 29 if r.Layout == "" { 30 r.Layout = LayoutSingleFile 31 } 32 if r.Type == "" { 33 r.Type = "Resolver" 34 } 35 36 switch r.Layout { 37 case LayoutSingleFile: 38 if r.Filename == "" { 39 return fmt.Errorf("filename must be specified with layout=%s", r.Layout) 40 } 41 if !strings.HasSuffix(r.Filename, ".go") { 42 return fmt.Errorf("filename should be path to a go source file with layout=%s", r.Layout) 43 } 44 r.Filename = abs(r.Filename) 45 case LayoutFollowSchema: 46 if r.DirName == "" { 47 return fmt.Errorf("dirname must be specified with layout=%s", r.Layout) 48 } 49 r.DirName = abs(r.DirName) 50 if r.Filename == "" { 51 r.Filename = filepath.Join(r.DirName, "resolver.go") 52 } else { 53 r.Filename = abs(r.Filename) 54 } 55 default: 56 return fmt.Errorf("invalid layout %s. must be %s or %s", r.Layout, LayoutSingleFile, LayoutFollowSchema) 57 } 58 59 if strings.ContainsAny(r.Package, "./\\") { 60 return fmt.Errorf("package should be the output package name only, do not include the output filename") 61 } 62 63 if r.Package == "" && r.Dir() != "" { 64 r.Package = code.NameForDir(r.Dir()) 65 } 66 67 return nil 68 } 69 70 func (r *ResolverConfig) ImportPath() string { 71 if r.Dir() == "" { 72 return "" 73 } 74 return code.ImportPathForDir(r.Dir()) 75 } 76 77 func (r *ResolverConfig) Dir() string { 78 switch r.Layout { 79 case LayoutSingleFile: 80 if r.Filename == "" { 81 return "" 82 } 83 return filepath.Dir(r.Filename) 84 case LayoutFollowSchema: 85 return r.DirName 86 default: 87 panic("invalid layout " + r.Layout) 88 } 89 } 90 91 func (r *ResolverConfig) Pkg() *types.Package { 92 if r.Dir() == "" { 93 return nil 94 } 95 return types.NewPackage(r.ImportPath(), r.Package) 96 } 97 98 func (r *ResolverConfig) IsDefined() bool { 99 return r.Filename != "" || r.DirName != "" 100 }