From a991e3e73ec4d624f6b23124d83198ce51af8ae3 Mon Sep 17 00:00:00 2001 From: Michael Tibben Date: Wed, 8 Sep 2021 21:50:43 +1000 Subject: [PATCH 01/19] Update errors to use go1.13 semantics --- api/generate.go | 22 +++++++++++----------- cmd/gen.go | 4 ++-- codegen/args.go | 3 +-- codegen/config/binder.go | 8 ++++---- codegen/config/config.go | 27 +++++++++++++-------------- codegen/config/config_test.go | 4 ++-- codegen/data.go | 7 +++---- codegen/directive.go | 5 ++--- codegen/field.go | 17 ++++++++--------- codegen/interface.go | 3 +-- codegen/object.go | 4 ++-- codegen/templates/templates.go | 13 ++++++------- codegen/util.go | 7 +++---- go.mod | 3 +-- internal/code/packages.go | 5 +++-- plugin/resolvergen/resolver.go | 4 ++-- plugin/servergen/server.go | 4 ++-- 17 files changed, 66 insertions(+), 74 deletions(-) diff --git a/api/generate.go b/api/generate.go index d9484005173..8d4b88de69d 100644 --- a/api/generate.go +++ b/api/generate.go @@ -1,6 +1,7 @@ package api import ( + "fmt" "syscall" "github.com/99designs/gqlgen/codegen" @@ -9,7 +10,6 @@ import ( "github.com/99designs/gqlgen/plugin/federation" "github.com/99designs/gqlgen/plugin/modelgen" "github.com/99designs/gqlgen/plugin/resolvergen" - "github.com/pkg/errors" ) func Generate(cfg *config.Config, option ...Option) error { @@ -40,7 +40,7 @@ func Generate(cfg *config.Config, option ...Option) error { } if err := cfg.LoadSchema(); err != nil { - return errors.Wrap(err, "failed to load schema") + return fmt.Errorf("failed to load schema: %w", err) } for _, p := range plugins { @@ -53,50 +53,50 @@ func Generate(cfg *config.Config, option ...Option) error { // LoadSchema again now we have everything if err := cfg.LoadSchema(); err != nil { - return errors.Wrap(err, "failed to load schema") + return fmt.Errorf("failed to load schema: %w", err) } if err := cfg.Init(); err != nil { - return errors.Wrap(err, "generating core failed") + return fmt.Errorf("generating core failed: %w", err) } for _, p := range plugins { if mut, ok := p.(plugin.ConfigMutator); ok { err := mut.MutateConfig(cfg) if err != nil { - return errors.Wrap(err, p.Name()) + return fmt.Errorf("%s: %w", p.Name(), err) } } } // Merge again now that the generated models have been injected into the typemap data, err := codegen.BuildData(cfg) if err != nil { - return errors.Wrap(err, "merging type systems failed") + return fmt.Errorf("merging type systems failed: %w", err) } if err = codegen.GenerateCode(data); err != nil { - return errors.Wrap(err, "generating core failed") + return fmt.Errorf("generating core failed: %w", err) } if err = cfg.Packages.ModTidy(); err != nil { - return errors.Wrap(err, "tidy failed") + return fmt.Errorf("tidy failed: %w", err) } for _, p := range plugins { if mut, ok := p.(plugin.CodeGenerator); ok { err := mut.GenerateCode(data) if err != nil { - return errors.Wrap(err, p.Name()) + return fmt.Errorf("%s: %w", p.Name(), err) } } } if err = codegen.GenerateCode(data); err != nil { - return errors.Wrap(err, "generating core failed") + return fmt.Errorf("generating core failed: %w", err) } if !cfg.SkipValidation { if err := validate(cfg); err != nil { - return errors.Wrap(err, "validation failed") + return fmt.Errorf("validation failed: %w", err) } } diff --git a/cmd/gen.go b/cmd/gen.go index b875bb43d02..9c564e6a414 100644 --- a/cmd/gen.go +++ b/cmd/gen.go @@ -1,11 +1,11 @@ package cmd import ( + "errors" "os" "github.com/99designs/gqlgen/api" "github.com/99designs/gqlgen/codegen/config" - "github.com/pkg/errors" "github.com/urfave/cli/v2" ) @@ -26,7 +26,7 @@ var genCmd = &cli.Command{ } } else { cfg, err = config.LoadConfigFromDefaultLocations() - if os.IsNotExist(errors.Cause(err)) { + if os.IsNotExist(errors.Unwrap(err)) { cfg, err = config.LoadDefaultConfig() } diff --git a/codegen/args.go b/codegen/args.go index 20a26e97542..09254262aef 100644 --- a/codegen/args.go +++ b/codegen/args.go @@ -7,7 +7,6 @@ import ( "github.com/99designs/gqlgen/codegen/config" "github.com/99designs/gqlgen/codegen/templates" - "github.com/pkg/errors" "github.com/vektah/gqlparser/v2/ast" ) @@ -67,7 +66,7 @@ func (b *builder) buildArg(obj *Object, arg *ast.ArgumentDefinition) (*FieldArgu if arg.DefaultValue != nil { newArg.Default, err = arg.DefaultValue.Value(nil) if err != nil { - return nil, errors.Errorf("default value is not valid: %s", err.Error()) + return nil, fmt.Errorf("default value is not valid: %w", err) } } diff --git a/codegen/config/binder.go b/codegen/config/binder.go index 68211834081..209c1205d19 100644 --- a/codegen/config/binder.go +++ b/codegen/config/binder.go @@ -1,13 +1,13 @@ package config import ( + "errors" "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/v2/ast" ) @@ -119,9 +119,9 @@ func (b *Binder) FindObject(pkgName string, typeName string) (types.Object, erro if pkg == nil { err := b.pkgs.Errors() if err != nil { - return nil, errors.Wrapf(err, "package could not be loaded: %s", fullName) + return nil, fmt.Errorf("package could not be loaded: %s: %w", fullName, err) } - return nil, errors.Errorf("required package was not loaded: %s", fullName) + return nil, fmt.Errorf("required package was not loaded: %s", fullName) } // function based marshalers take precedence @@ -148,7 +148,7 @@ func (b *Binder) FindObject(pkgName string, typeName string) (types.Object, erro } } - return nil, errors.Errorf("unable to find type %s\n", fullName) + return nil, fmt.Errorf("unable to find type %s\n", fullName) } func (b *Binder) PointerTo(ref *TypeReference) *TypeReference { diff --git a/codegen/config/config.go b/codegen/config/config.go index cfb22b4bf7e..75af82e5808 100644 --- a/codegen/config/config.go +++ b/codegen/config/config.go @@ -10,7 +10,6 @@ import ( "strings" "github.com/99designs/gqlgen/internal/code" - "github.com/pkg/errors" "github.com/vektah/gqlparser/v2" "github.com/vektah/gqlparser/v2/ast" "gopkg.in/yaml.v2" @@ -59,7 +58,7 @@ func LoadDefaultConfig() (*Config, error) { var schemaRaw []byte schemaRaw, err = ioutil.ReadFile(filename) if err != nil { - return nil, errors.Wrap(err, "unable to open schema") + return nil, fmt.Errorf("unable to open schema: %w", err) } config.Sources = append(config.Sources, &ast.Source{Name: filename, Input: string(schemaRaw)}) @@ -78,7 +77,7 @@ func LoadConfigFromDefaultLocations() (*Config, error) { err = os.Chdir(filepath.Dir(cfgFile)) if err != nil { - return nil, errors.Wrap(err, "unable to enter config dir") + return nil, fmt.Errorf("unable to enter config dir: %w", err) } return LoadConfig(cfgFile) } @@ -96,11 +95,11 @@ func LoadConfig(filename string) (*Config, error) { b, err := ioutil.ReadFile(filename) if err != nil { - return nil, errors.Wrap(err, "unable to read config") + return nil, fmt.Errorf("unable to read config: %w", err) } if err := yaml.UnmarshalStrict(b, config); err != nil { - return nil, errors.Wrap(err, "unable to parse config") + return nil, fmt.Errorf("unable to parse config: %w", err) } if err := CompleteConfig(config); err != nil { @@ -150,13 +149,13 @@ func CompleteConfig(config *Config) error { return nil }); err != nil { - return errors.Wrapf(err, "failed to walk schema at root %s", pathParts[0]) + return fmt.Errorf("failed to walk schema at root %s: %w", pathParts[0], err) } } else { var err error matches, err = filepath.Glob(f) if err != nil { - return errors.Wrapf(err, "failed to glob schema filename %s", f) + return fmt.Errorf("failed to glob schema filename %s: %w", f, err) } } @@ -174,7 +173,7 @@ func CompleteConfig(config *Config) error { var schemaRaw []byte schemaRaw, err = ioutil.ReadFile(filename) if err != nil { - return errors.Wrap(err, "unable to open schema") + return fmt.Errorf("unable to open schema: %w", err) } config.Sources = append(config.Sources, &ast.Source{Name: filename, Input: string(schemaRaw)}) @@ -343,10 +342,10 @@ func (c *Config) check() error { fileList := map[string][]FilenamePackage{} if err := c.Models.Check(); err != nil { - return errors.Wrap(err, "config.models") + return fmt.Errorf("config.models: %w", err) } if err := c.Exec.Check(); err != nil { - return errors.Wrap(err, "config.exec") + return fmt.Errorf("config.exec: %w", err) } fileList[c.Exec.ImportPath()] = append(fileList[c.Exec.ImportPath()], FilenamePackage{ Filename: c.Exec.Filename, @@ -356,7 +355,7 @@ func (c *Config) check() error { if c.Model.IsDefined() { if err := c.Model.Check(); err != nil { - return errors.Wrap(err, "config.model") + return fmt.Errorf("config.model: %w", err) } fileList[c.Model.ImportPath()] = append(fileList[c.Model.ImportPath()], FilenamePackage{ Filename: c.Model.Filename, @@ -366,7 +365,7 @@ func (c *Config) check() error { } if c.Resolver.IsDefined() { if err := c.Resolver.Check(); err != nil { - return errors.Wrap(err, "config.resolver") + return fmt.Errorf("config.resolver: %w", err) } fileList[c.Resolver.ImportPath()] = append(fileList[c.Resolver.ImportPath()], FilenamePackage{ Filename: c.Resolver.Filename, @@ -376,7 +375,7 @@ func (c *Config) check() error { } if c.Federation.IsDefined() { if err := c.Federation.Check(); err != nil { - return errors.Wrap(err, "config.federation") + return fmt.Errorf("config.federation: %w", err) } fileList[c.Federation.ImportPath()] = append(fileList[c.Federation.ImportPath()], FilenamePackage{ Filename: c.Federation.Filename, @@ -480,7 +479,7 @@ func inStrSlice(haystack []string, needle string) bool { func findCfg() (string, error) { dir, err := os.Getwd() if err != nil { - return "", errors.Wrap(err, "unable to get working dir to findCfg") + return "", fmt.Errorf("unable to get working dir to findCfg: %w", err) } cfg := findCfgInDir(dir) diff --git a/codegen/config/config_test.go b/codegen/config/config_test.go index b16e90c11a5..8ac68dd8360 100644 --- a/codegen/config/config_test.go +++ b/codegen/config/config_test.go @@ -1,12 +1,12 @@ package config import ( + "errors" "os" "path/filepath" "runtime" "testing" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/vektah/gqlparser/v2" @@ -105,7 +105,7 @@ func TestLoadDefaultConfig(t *testing.T) { require.NoError(t, err) cfg, err = LoadDefaultConfig() - require.True(t, os.IsNotExist(errors.Cause(err))) + require.True(t, os.IsNotExist(errors.Unwrap(err))) }) } diff --git a/codegen/data.go b/codegen/data.go index bedbef9d441..1a92b787801 100644 --- a/codegen/data.go +++ b/codegen/data.go @@ -4,7 +4,6 @@ import ( "fmt" "sort" - "github.com/pkg/errors" "github.com/vektah/gqlparser/v2/ast" "github.com/99designs/gqlgen/codegen/config" @@ -67,14 +66,14 @@ func BuildData(cfg *config.Config) (*Data, error) { case ast.Object: obj, err := b.buildObject(schemaType) if err != nil { - return nil, errors.Wrap(err, "unable to build object definition") + return nil, fmt.Errorf("unable to build object definition: %w", err) } s.Objects = append(s.Objects, obj) case ast.InputObject: input, err := b.buildObject(schemaType) if err != nil { - return nil, errors.Wrap(err, "unable to build input definition") + return nil, fmt.Errorf("unable to build input definition: %w", err) } s.Inputs = append(s.Inputs, input) @@ -82,7 +81,7 @@ func BuildData(cfg *config.Config) (*Data, error) { case ast.Union, ast.Interface: s.Interfaces[schemaType.Name], err = b.buildInterface(schemaType) if err != nil { - return nil, errors.Wrap(err, "unable to bind to interface") + return nil, fmt.Errorf("unable to bind to interface: %w", err) } } } diff --git a/codegen/directive.go b/codegen/directive.go index 5d4c038ffa7..2be102c2ca0 100644 --- a/codegen/directive.go +++ b/codegen/directive.go @@ -6,7 +6,6 @@ import ( "strings" "github.com/99designs/gqlgen/codegen/templates" - "github.com/pkg/errors" "github.com/vektah/gqlparser/v2/ast" ) @@ -52,7 +51,7 @@ func (b *builder) buildDirectives() (map[string]*Directive, error) { for name, dir := range b.Schema.Directives { if _, ok := directives[name]; ok { - return nil, errors.Errorf("directive with name %s already exists", name) + return nil, fmt.Errorf("directive with name %s already exists", name) } var args []*FieldArgument @@ -72,7 +71,7 @@ func (b *builder) buildDirectives() (map[string]*Directive, error) { var err error newArg.Default, err = arg.DefaultValue.Value(nil) if err != nil { - return nil, errors.Errorf("default value for directive argument %s(%s) is not valid: %s", dir.Name, arg.Name, err.Error()) + return nil, fmt.Errorf("default value for directive argument %s(%s) is not valid: %w", dir.Name, arg.Name, err) } } args = append(args, newArg) diff --git a/codegen/field.go b/codegen/field.go index e091e7fe6c0..86fee340d4a 100644 --- a/codegen/field.go +++ b/codegen/field.go @@ -10,7 +10,6 @@ import ( "github.com/99designs/gqlgen/codegen/config" "github.com/99designs/gqlgen/codegen/templates" - "github.com/pkg/errors" "github.com/vektah/gqlparser/v2/ast" ) @@ -51,7 +50,7 @@ func (b *builder) buildField(obj *Object, field *ast.FieldDefinition) (*Field, e var err error f.Default, err = field.DefaultValue.Value(nil) if err != nil { - return nil, errors.Errorf("default value %s is not valid: %s", field.Name, err.Error()) + return nil, fmt.Errorf("default value %s is not valid: %w", field.Name, err) } } @@ -177,7 +176,7 @@ func (b *builder) bindField(obj *Object, f *Field) (errret error) { } if err = b.bindArgs(f, params); err != nil { - return errors.Wrapf(err, "%s:%d", pos.Filename, pos.Line) + return fmt.Errorf("%s:%d: %w", pos.Filename, pos.Line, err) } result := sig.Results().At(0) @@ -246,7 +245,7 @@ func (b *builder) findBindTarget(t types.Type, name string) (types.Object, error return foundField, nil case foundField != nil && foundMethod != nil: // Error - return nil, errors.Errorf("found more than one way to bind for %s", name) + return nil, fmt.Errorf("found more than one way to bind for %s", name) } // Search embeds @@ -271,7 +270,7 @@ func (b *builder) findBindStructTagTarget(in types.Type, name string) (types.Obj tags := reflect.StructTag(t.Tag(i)) if val, ok := tags.Lookup(b.Config.StructTag); ok && equalFieldName(val, name) { if found != nil { - return nil, errors.Errorf("tag %s is ambigious; multiple fields have the same tag value of %s", b.Config.StructTag, val) + return nil, fmt.Errorf("tag %s is ambigious; multiple fields have the same tag value of %s", b.Config.StructTag, val) } found = field @@ -309,7 +308,7 @@ func (b *builder) findBindMethoderTarget(methodFunc func(i int) *types.Func, met } if found != nil { - return nil, errors.Errorf("found more than one matching method to bind for %s", name) + return nil, fmt.Errorf("found more than one matching method to bind for %s", name) } found = method @@ -331,7 +330,7 @@ func (b *builder) findBindFieldTarget(in types.Type, name string) (types.Object, } if found != nil { - return nil, errors.Errorf("found more than one matching field to bind for %s", name) + return nil, fmt.Errorf("found more than one matching field to bind for %s", name) } found = field @@ -375,7 +374,7 @@ func (b *builder) findBindStructEmbedsTarget(strukt *types.Struct, name string) } if f != nil && found != nil { - return nil, errors.Errorf("found more than one way to bind for %s", name) + return nil, fmt.Errorf("found more than one way to bind for %s", name) } if f != nil { @@ -397,7 +396,7 @@ func (b *builder) findBindInterfaceEmbedsTarget(iface *types.Interface, name str } if f != nil && found != nil { - return nil, errors.Errorf("found more than one way to bind for %s", name) + return nil, fmt.Errorf("found more than one way to bind for %s", name) } if f != nil { diff --git a/codegen/interface.go b/codegen/interface.go index a55ce1e6bf9..cdc4d4d32ed 100644 --- a/codegen/interface.go +++ b/codegen/interface.go @@ -4,7 +4,6 @@ import ( "fmt" "go/types" - "github.com/pkg/errors" "github.com/vektah/gqlparser/v2/ast" "github.com/99designs/gqlgen/codegen/config" @@ -49,7 +48,7 @@ func (b *builder) buildInterface(typ *ast.Definition) (*Interface, error) { implementorType, err := findGoNamedType(obj) if err != nil { - return nil, errors.Wrapf(err, "can not find backing go type %s", obj.String()) + return nil, fmt.Errorf("can not find backing go type %s: %w", obj.String(), err) } else if implementorType == nil { return nil, fmt.Errorf("can not find backing go type %s", obj.String()) } diff --git a/codegen/object.go b/codegen/object.go index 7b91c900497..f730a7e1e31 100644 --- a/codegen/object.go +++ b/codegen/object.go @@ -1,13 +1,13 @@ package codegen import ( + "fmt" "go/types" "strconv" "strings" "unicode" "github.com/99designs/gqlgen/codegen/config" - "github.com/pkg/errors" "github.com/vektah/gqlparser/v2/ast" ) @@ -36,7 +36,7 @@ type Object struct { func (b *builder) buildObject(typ *ast.Definition) (*Object, error) { dirs, err := b.getDirectives(typ.Directives) if err != nil { - return nil, errors.Wrap(err, typ.Name) + return nil, fmt.Errorf("%s: %w", typ.Name, err) } obj := &Object{ diff --git a/codegen/templates/templates.go b/codegen/templates/templates.go index 79b0c5c7d46..637b43515dc 100644 --- a/codegen/templates/templates.go +++ b/codegen/templates/templates.go @@ -18,7 +18,6 @@ import ( "github.com/99designs/gqlgen/internal/code" "github.com/99designs/gqlgen/internal/imports" - "github.com/pkg/errors" ) // CurrentImports keeps track of all the import declarations that are needed during the execution of a plugin. @@ -79,7 +78,7 @@ func Render(cfg Options) error { var err error t, err = t.New("template.gotpl").Parse(cfg.Template) if err != nil { - return errors.Wrap(err, "error with provided template") + return fmt.Errorf("error with provided template: %w", err) } roots = append(roots, "template.gotpl") } else { @@ -99,7 +98,7 @@ func Render(cfg Options) error { t, err = t.New(name).Parse(string(b)) if err != nil { - return errors.Wrap(err, cfg.Filename) + return fmt.Errorf("%s: %w", cfg.Filename, err) } roots = append(roots, name) @@ -107,7 +106,7 @@ func Render(cfg Options) error { return nil }) if err != nil { - return errors.Wrap(err, "locating templates") + return fmt.Errorf("locating templates: %w", err) } } @@ -129,7 +128,7 @@ func Render(cfg Options) error { } err := t.Lookup(root).Execute(&buf, cfg.Data) if err != nil { - return errors.Wrap(err, root) + return fmt.Errorf("%s: %w", root, err) } if cfg.RegionTags { buf.WriteString("\n// endregion " + center(70, "*", " "+root+" ") + "\n") @@ -584,7 +583,7 @@ func render(filename string, tpldata interface{}) (*bytes.Buffer, error) { func write(filename string, b []byte, packages *code.Packages) error { err := os.MkdirAll(filepath.Dir(filename), 0755) if err != nil { - return errors.Wrap(err, "failed to create directory") + return fmt.Errorf("failed to create directory: %w", err) } formatted, err := imports.Prune(filename, b, packages) @@ -595,7 +594,7 @@ func write(filename string, b []byte, packages *code.Packages) error { err = ioutil.WriteFile(filename, formatted, 0644) if err != nil { - return errors.Wrapf(err, "failed to write %s", filename) + return fmt.Errorf("failed to write %s: %w", filename, err) } return nil diff --git a/codegen/util.go b/codegen/util.go index 59dfde08cdc..d1c4533809a 100644 --- a/codegen/util.go +++ b/codegen/util.go @@ -1,10 +1,9 @@ package codegen import ( + "fmt" "go/types" "strings" - - "github.com/pkg/errors" ) func findGoNamedType(def types.Type) (*types.Named, error) { @@ -14,7 +13,7 @@ func findGoNamedType(def types.Type) (*types.Named, error) { namedType, ok := def.(*types.Named) if !ok { - return nil, errors.Errorf("expected %s to be a named type, instead found %T\n", def.String(), def) + return nil, fmt.Errorf("expected %s to be a named type, instead found %T\n", def.String(), def) } return namedType, nil @@ -34,7 +33,7 @@ func findGoInterface(def types.Type) (*types.Interface, error) { underlying, ok := namedType.Underlying().(*types.Interface) if !ok { - return nil, errors.Errorf("expected %s to be a named interface, instead found %s", def.String(), namedType.String()) + return nil, fmt.Errorf("expected %s to be a named interface, instead found %s", def.String(), namedType.String()) } return underlying, nil diff --git a/go.mod b/go.mod index bbd03943083..0d2e66841ab 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/99designs/gqlgen -go 1.12 +go 1.13 require ( github.com/agnivade/levenshtein v1.1.0 // indirect @@ -16,7 +16,6 @@ require ( github.com/mitchellh/mapstructure v0.0.0-20180203102830-a4e142e9c047 github.com/opentracing/basictracer-go v1.0.0 // indirect github.com/opentracing/opentracing-go v1.0.2 - github.com/pkg/errors v0.8.1 github.com/rs/cors v1.6.0 github.com/shurcooL/httpfs v0.0.0-20171119174359-809beceb2371 // indirect github.com/shurcooL/vfsgen v0.0.0-20180121065927-ffb13db8def0 // indirect diff --git a/internal/code/packages.go b/internal/code/packages.go index d3a4058530b..c9491802eb9 100644 --- a/internal/code/packages.go +++ b/internal/code/packages.go @@ -2,10 +2,11 @@ package code import ( "bytes" + "errors" + "fmt" "os/exec" "path/filepath" - "github.com/pkg/errors" "golang.org/x/tools/go/packages" ) @@ -154,7 +155,7 @@ func (p *Packages) ModTidy() error { p.packages = nil tidyCmd := exec.Command("go", "mod", "tidy") if err := tidyCmd.Run(); err != nil { - return errors.Wrap(err, "go mod tidy failed") + return fmt.Errorf("go mod tidy failed: %w", err) } return nil } diff --git a/plugin/resolvergen/resolver.go b/plugin/resolvergen/resolver.go index 204801efbe5..1a76b1053c0 100644 --- a/plugin/resolvergen/resolver.go +++ b/plugin/resolvergen/resolver.go @@ -1,6 +1,7 @@ package resolvergen import ( + "errors" "os" "path/filepath" "strings" @@ -10,7 +11,6 @@ import ( "github.com/99designs/gqlgen/codegen/templates" "github.com/99designs/gqlgen/internal/rewrite" "github.com/99designs/gqlgen/plugin" - "github.com/pkg/errors" ) func New() plugin.Plugin { @@ -144,7 +144,7 @@ func (m *Plugin) generatePerSchema(data *codegen.Data) error { } } - if _, err := os.Stat(data.Config.Resolver.Filename); os.IsNotExist(errors.Cause(err)) { + if _, err := os.Stat(data.Config.Resolver.Filename); os.IsNotExist(errors.Unwrap(err)) { err := templates.Render(templates.Options{ PackageName: data.Config.Resolver.Package, FileNotice: ` diff --git a/plugin/servergen/server.go b/plugin/servergen/server.go index 029c9ae398e..e430310c539 100644 --- a/plugin/servergen/server.go +++ b/plugin/servergen/server.go @@ -1,13 +1,13 @@ package servergen import ( + "errors" "log" "os" "github.com/99designs/gqlgen/codegen" "github.com/99designs/gqlgen/codegen/templates" "github.com/99designs/gqlgen/plugin" - "github.com/pkg/errors" ) func New(filename string) plugin.Plugin { @@ -29,7 +29,7 @@ func (m *Plugin) GenerateCode(data *codegen.Data) error { ResolverPackageName: data.Config.Resolver.ImportPath(), } - if _, err := os.Stat(m.filename); os.IsNotExist(errors.Cause(err)) { + if _, err := os.Stat(m.filename); os.IsNotExist(errors.Unwrap(err)) { return templates.Render(templates.Options{ PackageName: "main", Filename: m.filename, From 60d80d4aee61337793d2cade8a7ab35c2892613a Mon Sep 17 00:00:00 2001 From: Michael Tibben Date: Thu, 9 Sep 2021 14:32:57 +1000 Subject: [PATCH 02/19] Update cmd/gen.go Co-authored-by: Luke Cawood --- cmd/gen.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/gen.go b/cmd/gen.go index 9c564e6a414..706313cee30 100644 --- a/cmd/gen.go +++ b/cmd/gen.go @@ -26,7 +26,7 @@ var genCmd = &cli.Command{ } } else { cfg, err = config.LoadConfigFromDefaultLocations() - if os.IsNotExist(errors.Unwrap(err)) { + if errors.Is(err, fs.ErrNotExist) { cfg, err = config.LoadDefaultConfig() } From de7d19c812bed562d2841c6c08fb080d706195d1 Mon Sep 17 00:00:00 2001 From: Michael Tibben Date: Thu, 9 Sep 2021 14:33:10 +1000 Subject: [PATCH 03/19] Update codegen/config/config_test.go Co-authored-by: Luke Cawood --- codegen/config/config_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/codegen/config/config_test.go b/codegen/config/config_test.go index 8ac68dd8360..f0d6ab89822 100644 --- a/codegen/config/config_test.go +++ b/codegen/config/config_test.go @@ -105,7 +105,7 @@ func TestLoadDefaultConfig(t *testing.T) { require.NoError(t, err) cfg, err = LoadDefaultConfig() - require.True(t, os.IsNotExist(errors.Unwrap(err))) + require.True(t, errors.Is(err, fs.ErrNotExist)) }) } From a6c6de6b73741caa1ac02cf8adea79afcd4ed78b Mon Sep 17 00:00:00 2001 From: Michael Tibben Date: Thu, 9 Sep 2021 14:33:21 +1000 Subject: [PATCH 04/19] Update plugin/resolvergen/resolver.go Co-authored-by: Luke Cawood --- plugin/resolvergen/resolver.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin/resolvergen/resolver.go b/plugin/resolvergen/resolver.go index 1a76b1053c0..8c61836f750 100644 --- a/plugin/resolvergen/resolver.go +++ b/plugin/resolvergen/resolver.go @@ -144,7 +144,7 @@ func (m *Plugin) generatePerSchema(data *codegen.Data) error { } } - if _, err := os.Stat(data.Config.Resolver.Filename); os.IsNotExist(errors.Unwrap(err)) { + if _, err := os.Stat(data.Config.Resolver.Filename); errors.Is(err, fs.ErrNotExist) { err := templates.Render(templates.Options{ PackageName: data.Config.Resolver.Package, FileNotice: ` From d747387036fb300fc384fa6f17a76f6547dc6a1b Mon Sep 17 00:00:00 2001 From: Michael Tibben Date: Thu, 9 Sep 2021 14:33:30 +1000 Subject: [PATCH 05/19] Update plugin/servergen/server.go Co-authored-by: Luke Cawood --- plugin/servergen/server.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin/servergen/server.go b/plugin/servergen/server.go index e430310c539..05fe885fcd6 100644 --- a/plugin/servergen/server.go +++ b/plugin/servergen/server.go @@ -29,7 +29,7 @@ func (m *Plugin) GenerateCode(data *codegen.Data) error { ResolverPackageName: data.Config.Resolver.ImportPath(), } - if _, err := os.Stat(m.filename); os.IsNotExist(errors.Unwrap(err)) { + if _, err := os.Stat(m.filename); errors.Is(err, fs.ErrNotExist) { return templates.Render(templates.Options{ PackageName: "main", Filename: m.filename, From 5c7acc1bc8198ed57a38867ae0c452987da91911 Mon Sep 17 00:00:00 2001 From: Michael Tibben Date: Fri, 10 Sep 2021 09:21:30 +1000 Subject: [PATCH 06/19] Fix imports --- cmd/gen.go | 2 +- codegen/config/config_test.go | 1 + plugin/resolvergen/resolver.go | 1 + plugin/servergen/server.go | 1 + 4 files changed, 4 insertions(+), 1 deletion(-) diff --git a/cmd/gen.go b/cmd/gen.go index 706313cee30..f973cc22c0f 100644 --- a/cmd/gen.go +++ b/cmd/gen.go @@ -2,7 +2,7 @@ package cmd import ( "errors" - "os" + "io/fs" "github.com/99designs/gqlgen/api" "github.com/99designs/gqlgen/codegen/config" diff --git a/codegen/config/config_test.go b/codegen/config/config_test.go index f0d6ab89822..9dcd0a59958 100644 --- a/codegen/config/config_test.go +++ b/codegen/config/config_test.go @@ -2,6 +2,7 @@ package config import ( "errors" + "io/fs" "os" "path/filepath" "runtime" diff --git a/plugin/resolvergen/resolver.go b/plugin/resolvergen/resolver.go index 8c61836f750..e63501d2bc6 100644 --- a/plugin/resolvergen/resolver.go +++ b/plugin/resolvergen/resolver.go @@ -2,6 +2,7 @@ package resolvergen import ( "errors" + "io/fs" "os" "path/filepath" "strings" diff --git a/plugin/servergen/server.go b/plugin/servergen/server.go index 05fe885fcd6..cdabc409fe6 100644 --- a/plugin/servergen/server.go +++ b/plugin/servergen/server.go @@ -2,6 +2,7 @@ package servergen import ( "errors" + "io/fs" "log" "os" From ed210385722431111b8842ec7da7b42051b77d91 Mon Sep 17 00:00:00 2001 From: Michael Tibben Date: Fri, 10 Sep 2021 09:38:37 +1000 Subject: [PATCH 07/19] Update to go 1.17 --- .github/workflows/integration.yml | 6 +++--- .github/workflows/lint.yml | 4 ++-- .github/workflows/test.yml | 2 +- go.mod | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 8000b49bd50..7f0fb419433 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -5,7 +5,7 @@ jobs: integration: runs-on: ubuntu-latest timeout-minutes: 3 - container: golang:1.13-alpine + container: golang:1.17-alpine steps: - uses: actions/checkout@v1 - run: apk add --no-cache --no-progress nodejs npm git bash @@ -15,7 +15,7 @@ jobs: federation: runs-on: ubuntu-latest - container: golang:1.13-alpine + container: golang:1.17-alpine steps: - uses: actions/checkout@v1 - run: apk add --no-cache --no-progress nodejs npm git bash @@ -25,7 +25,7 @@ jobs: init: runs-on: ubuntu-latest - container: golang:1.16-alpine + container: golang:1.17-alpine steps: - uses: actions/checkout@v1 - run: apk add --no-cache --no-progress alpine-sdk bash diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 27b256b6f9f..44695d14b86 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -7,7 +7,7 @@ jobs: steps: - uses: actions/checkout@v1 - uses: actions/setup-go@v2 - with: { go-version: 1.14 } + with: { go-version: 1.17 } - run: go mod download - run: .github/workflows/check-fmt - run: .github/workflows/check-linting @@ -18,7 +18,7 @@ jobs: steps: - uses: actions/checkout@v1 - uses: actions/setup-go@v2 - with: { go-version: 1.14 } + with: { go-version: 1.17 } - run: go mod download - run: .github/workflows/check-coverage env: diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 1df7ffaf751..a27fff46648 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -5,7 +5,7 @@ jobs: test: strategy: matrix: - go: [1.13, 1.14] + go: 1.17 os: [ubuntu-latest, windows-latest] runs-on: ${{ matrix.os }} diff --git a/go.mod b/go.mod index 0d2e66841ab..8ebf9dc744a 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/99designs/gqlgen -go 1.13 +go 1.17 require ( github.com/agnivade/levenshtein v1.1.0 // indirect From 10bb1ef262af49031c3d5224eb094586e6fd8083 Mon Sep 17 00:00:00 2001 From: Michael Tibben Date: Fri, 10 Sep 2021 09:41:17 +1000 Subject: [PATCH 08/19] Go mod tidy --- go.mod | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/go.mod b/go.mod index 8ebf9dc744a..b1dd02f0e3c 100644 --- a/go.mod +++ b/go.mod @@ -28,3 +28,16 @@ require ( sourcegraph.com/sourcegraph/appdash v0.0.0-20190731080439-ebfcffb1b5c0 sourcegraph.com/sourcegraph/appdash-data v0.0.0-20151005221446-73f23eafcf67 // indirect ) + +require ( + github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pkg/errors v0.8.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/russross/blackfriday/v2 v2.0.1 // indirect + github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect + golang.org/x/mod v0.3.0 // indirect + golang.org/x/net v0.0.0-20201021035429-f5854403a974 // indirect + golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f // indirect + golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect +) From 402f44950b4694a3a5fd65d3225e06ccd76fbf9d Mon Sep 17 00:00:00 2001 From: Michael Tibben Date: Fri, 10 Sep 2021 09:44:59 +1000 Subject: [PATCH 09/19] go fmt --- graphql/executable_schema_mock.go | 3 ++- internal/imports/testdata/unused.go | 8 +++++--- internal/rewrite/testdata/example.go | 6 ++++-- tools.go | 1 + 4 files changed, 12 insertions(+), 6 deletions(-) diff --git a/graphql/executable_schema_mock.go b/graphql/executable_schema_mock.go index 0c021d3d003..6f38818391f 100644 --- a/graphql/executable_schema_mock.go +++ b/graphql/executable_schema_mock.go @@ -5,8 +5,9 @@ package graphql import ( "context" - "github.com/vektah/gqlparser/v2/ast" "sync" + + "github.com/vektah/gqlparser/v2/ast" ) var ( diff --git a/internal/imports/testdata/unused.go b/internal/imports/testdata/unused.go index db4c9b4d278..95cbe2d00ff 100644 --- a/internal/imports/testdata/unused.go +++ b/internal/imports/testdata/unused.go @@ -1,8 +1,10 @@ package testdata -import _ "underscore" -import a "fmt" -import "time" +import ( + a "fmt" + "time" + _ "underscore" +) type foo struct { Time time.Time `json:"text"` diff --git a/internal/rewrite/testdata/example.go b/internal/rewrite/testdata/example.go index a688348210b..949bbe8235d 100644 --- a/internal/rewrite/testdata/example.go +++ b/internal/rewrite/testdata/example.go @@ -1,8 +1,10 @@ package testdata -import "fmt" +import ( + "fmt" -import lol "bytes" + lol "bytes" +) type Foo struct { Field int diff --git a/tools.go b/tools.go index e63a71a8055..47e0bd690cb 100644 --- a/tools.go +++ b/tools.go @@ -1,3 +1,4 @@ +//go:build tools // +build tools package main From 90c5eb59b0fde89eb0c42e5b9c5ad276a8335f8f Mon Sep 17 00:00:00 2001 From: Michael Tibben Date: Fri, 10 Sep 2021 09:49:50 +1000 Subject: [PATCH 10/19] go generate --- graphql/executable_schema_mock.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/graphql/executable_schema_mock.go b/graphql/executable_schema_mock.go index 6f38818391f..0c021d3d003 100644 --- a/graphql/executable_schema_mock.go +++ b/graphql/executable_schema_mock.go @@ -5,9 +5,8 @@ package graphql import ( "context" - "sync" - "github.com/vektah/gqlparser/v2/ast" + "sync" ) var ( From 5216db5849eb5298722ee233cc98fa1e85db3237 Mon Sep 17 00:00:00 2001 From: Michael Tibben Date: Fri, 10 Sep 2021 10:54:05 +1000 Subject: [PATCH 11/19] Fix TestAutobinding test failure by checking the module --- codegen/config/config.go | 2 +- go.mod | 8 ++++---- go.sum | 11 +++++++++++ internal/code/packages.go | 3 ++- 4 files changed, 18 insertions(+), 6 deletions(-) diff --git a/codegen/config/config.go b/codegen/config/config.go index 75af82e5808..09ae7835600 100644 --- a/codegen/config/config.go +++ b/codegen/config/config.go @@ -519,7 +519,7 @@ func (c *Config) autobind() error { } for i, p := range ps { - if p == nil { + if p.Module == nil { return fmt.Errorf("unable to load %s - make sure you're using an import path to a package that exists", c.AutoBind[i]) } if t := p.Types.Scope().Lookup(t.Name); t != nil { diff --git a/go.mod b/go.mod index b1dd02f0e3c..78a5fb6b034 100644 --- a/go.mod +++ b/go.mod @@ -23,7 +23,7 @@ require ( github.com/urfave/cli/v2 v2.1.1 github.com/vektah/dataloaden v0.2.1-0.20190515034641-a19b9a6e7c9e github.com/vektah/gqlparser/v2 v2.2.0 - golang.org/x/tools v0.0.0-20210106214847-113979e3529a + golang.org/x/tools v0.1.5 gopkg.in/yaml.v2 v2.2.4 sourcegraph.com/sourcegraph/appdash v0.0.0-20190731080439-ebfcffb1b5c0 sourcegraph.com/sourcegraph/appdash-data v0.0.0-20151005221446-73f23eafcf67 // indirect @@ -36,8 +36,8 @@ require ( github.com/pmezard/go-difflib v1.0.0 // indirect github.com/russross/blackfriday/v2 v2.0.1 // indirect github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect - golang.org/x/mod v0.3.0 // indirect - golang.org/x/net v0.0.0-20201021035429-f5854403a974 // indirect - golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f // indirect + golang.org/x/mod v0.4.2 // indirect + golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4 // indirect + golang.org/x/sys v0.0.0-20210510120138-977fb7262007 // indirect golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect ) diff --git a/go.sum b/go.sum index fe1fd7471b6..d580c9b649a 100644 --- a/go.sum +++ b/go.sum @@ -79,12 +79,16 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20201021035429-f5854403a974 h1:IX6qOQeG5uLjB/hjjwjedwfjND0hgjPMMyO1RoIXQNI= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4 h1:4nGaVu0QrbjT/AK2PRLuQfQuh6DJve+pELhqTdAj3x0= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -94,6 +98,11 @@ golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f h1:+Nyd8tzPX9R7BWHguqsrbFdRx3WQ/1ib8I44HXV5yTA= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007 h1:gG67DSER+11cZvqIMb8S8bt0vZtiN6xWYARwirrOSfE= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -103,6 +112,8 @@ golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210106214847-113979e3529a h1:CB3a9Nez8M13wwlr/E2YtwoU+qYHKfC+JrDa45RXXoQ= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.1.5 h1:ouewzE6p+/VEB31YYnTbEJdi8pFqKp4P4n85vwo3DHA= +golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/internal/code/packages.go b/internal/code/packages.go index c9491802eb9..39ba374eab6 100644 --- a/internal/code/packages.go +++ b/internal/code/packages.go @@ -15,7 +15,8 @@ var mode = packages.NeedName | packages.NeedImports | packages.NeedTypes | packages.NeedSyntax | - packages.NeedTypesInfo + packages.NeedTypesInfo | + packages.NeedModule // Packages is a wrapper around x/tools/go/packages that maintains a (hopefully prewarmed) cache of packages // that can be invalidated as writes are made and packages are known to change. From 59da23feb5e135b3c2c0ce976b0214643147e85c Mon Sep 17 00:00:00 2001 From: Michael Tibben Date: Fri, 10 Sep 2021 21:19:23 +1000 Subject: [PATCH 12/19] Create a temporary file on init so go recognises the directory as a package --- .github/workflows/check-init | 2 +- cmd/init.go | 97 ++++++++++++++++++------------------ codegen/config/config.go | 2 +- 3 files changed, 50 insertions(+), 51 deletions(-) diff --git a/.github/workflows/check-init b/.github/workflows/check-init index 9c09e84f407..4197a5644e8 100755 --- a/.github/workflows/check-init +++ b/.github/workflows/check-init @@ -4,7 +4,7 @@ set -euo pipefail cd example/init -go get github.com/99designs/gqlgen +go get -d github.com/99designs/gqlgen if { go run github.com/99designs/gqlgen init 2>&1 >&3 3>&- | grep '^' >&2; } 3>&1; then echo "gqlgen init failed validation" diff --git a/cmd/init.go b/cmd/init.go index ad95a5cec50..daa449969a7 100644 --- a/cmd/init.go +++ b/cmd/init.go @@ -2,8 +2,10 @@ package cmd import ( "bytes" + "errors" "fmt" "html/template" + "io/fs" "io/ioutil" "os" "path/filepath" @@ -122,77 +124,74 @@ var initCmd = &cli.Command{ return fmt.Errorf("unable to determine import path for current directory, you probably need to run go mod init first") } - if err := initSchema(ctx.String("schema")); err != nil { + if err := initFile(ctx.String("schema"), schemaDefault); err != nil { return err } - if !configExists(configFilename) { - if err := initConfig(configFilename, pkgName); err != nil { + + cfg, err := loadConfig(configFilename) + + if err != nil { + if configFilename == "" { + configFilename = "gqlgen.yml" + } + + fmt.Println("Creating", configFilename) + if err := initFile(configFilename, executeConfigTemplate(pkgName)); err != nil { return err } - } - GenerateGraphServer(serverFilename) - return nil - }, -} + // create the package directory with a temporary file so that go recognises it as a package + // and autobinding doesn't error out + tmpPackageNameFile := "graph/model/_tmp_gqlgen_init.go" + if err := initFile(tmpPackageNameFile, "package model"); err != nil { + return err + } + defer os.Remove(tmpPackageNameFile) -func GenerateGraphServer(serverFilename string) { - cfg, err := config.LoadConfigFromDefaultLocations() - if err != nil { - fmt.Fprintln(os.Stderr, err.Error()) - } + if cfg, err = loadConfig(configFilename); err != nil { + panic(err) + } + } else { + fmt.Println("Skipping creating gqlgen.yml as it already exists") + } - if err := api.Generate(cfg, api.AddPlugin(servergen.New(serverFilename))); err != nil { - fmt.Fprintln(os.Stderr, err.Error()) - } + fmt.Println("Creating graph/...") + fmt.Println("Creating", serverFilename) + if err := api.Generate(cfg, api.AddPlugin(servergen.New(serverFilename))); err != nil { + fmt.Fprintln(os.Stderr, err.Error()) + } - fmt.Fprintf(os.Stdout, "Exec \"go run ./%s\" to start GraphQL server\n", serverFilename) + fmt.Fprintf(os.Stdout, "\nExec \"go run ./%s\" to start GraphQL server\n", serverFilename) + return nil + }, } -func configExists(configFilename string) bool { - var cfg *config.Config - +func loadConfig(configFilename string) (*config.Config, error) { if configFilename != "" { - cfg, _ = config.LoadConfig(configFilename) + return config.LoadConfig(configFilename) } else { - cfg, _ = config.LoadConfigFromDefaultLocations() + return config.LoadConfigFromDefaultLocations() } - return cfg != nil } -func initConfig(configFilename string, pkgName string) error { - if configFilename == "" { - configFilename = "gqlgen.yml" - } - - if err := os.MkdirAll(filepath.Dir(configFilename), 0755); err != nil { - return fmt.Errorf("unable to create config dir: " + err.Error()) - } - +func executeConfigTemplate(pkgName string) string { var buf bytes.Buffer if err := configTemplate.Execute(&buf, pkgName); err != nil { panic(err) } - if err := ioutil.WriteFile(configFilename, buf.Bytes(), 0644); err != nil { - return fmt.Errorf("unable to write cfg file: " + err.Error()) - } - - return nil + return buf.String() } -func initSchema(schemaFilename string) error { - _, err := os.Stat(schemaFilename) - if !os.IsNotExist(err) { - return nil - } - - if err := os.MkdirAll(filepath.Dir(schemaFilename), 0755); err != nil { - return fmt.Errorf("unable to create schema dir: " + err.Error()) - } - - if err = ioutil.WriteFile(schemaFilename, []byte(schemaDefault), 0644); err != nil { - return fmt.Errorf("unable to write schema file: " + err.Error()) +func initFile(filename, contents string) error { + _, err := os.Stat(filename) + if errors.Is(err, fs.ErrNotExist) { + if err := os.MkdirAll(filepath.Dir(filename), 0755); err != nil { + return fmt.Errorf("unable to create directory for file '%s': %w", filename, err) + } + if err = ioutil.WriteFile(filename, []byte(contents), 0644); err != nil { + return fmt.Errorf("unable to write file '%s': %w", filename, err) + } } return nil } diff --git a/codegen/config/config.go b/codegen/config/config.go index 09ae7835600..d29630d027e 100644 --- a/codegen/config/config.go +++ b/codegen/config/config.go @@ -519,7 +519,7 @@ func (c *Config) autobind() error { } for i, p := range ps { - if p.Module == nil { + if p == nil || p.Module == nil { return fmt.Errorf("unable to load %s - make sure you're using an import path to a package that exists", c.AutoBind[i]) } if t := p.Types.Scope().Lookup(t.Name); t != nil { From 1c63cfff8f2943d2ab3316f850b89bba83548c05 Mon Sep 17 00:00:00 2001 From: Michael Tibben Date: Fri, 10 Sep 2021 21:29:35 +1000 Subject: [PATCH 13/19] Add missing model package file --- example/federation/accounts/graph/model/model.go | 1 + example/federation/products/graph/model/model.go | 1 + 2 files changed, 2 insertions(+) create mode 100644 example/federation/accounts/graph/model/model.go create mode 100644 example/federation/products/graph/model/model.go diff --git a/example/federation/accounts/graph/model/model.go b/example/federation/accounts/graph/model/model.go new file mode 100644 index 00000000000..8b537907051 --- /dev/null +++ b/example/federation/accounts/graph/model/model.go @@ -0,0 +1 @@ +package model diff --git a/example/federation/products/graph/model/model.go b/example/federation/products/graph/model/model.go new file mode 100644 index 00000000000..8b537907051 --- /dev/null +++ b/example/federation/products/graph/model/model.go @@ -0,0 +1 @@ +package model From c6b9f2926b14c0367ffb82db4e2c250c4fc7aab2 Mon Sep 17 00:00:00 2001 From: Michael Tibben Date: Fri, 10 Sep 2021 21:30:02 +1000 Subject: [PATCH 14/19] go mod tidy --- go.sum | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/go.sum b/go.sum index d580c9b649a..14f53f5b1ab 100644 --- a/go.sum +++ b/go.sum @@ -73,11 +73,11 @@ github.com/vektah/gqlparser/v2 v2.2.0 h1:bAc3slekAAJW6sZTi07aGq0OrfaCjj4jxARAaC7 github.com/vektah/gqlparser/v2 v2.2.0/go.mod h1:i3mQIGIrbK2PD1RrCeMTlVbkF2FJ6WkU1KJlJlC+3F4= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= @@ -85,18 +85,17 @@ golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20201021035429-f5854403a974 h1:IX6qOQeG5uLjB/hjjwjedwfjND0hgjPMMyO1RoIXQNI= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4 h1:4nGaVu0QrbjT/AK2PRLuQfQuh6DJve+pELhqTdAj3x0= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f h1:+Nyd8tzPX9R7BWHguqsrbFdRx3WQ/1ib8I44HXV5yTA= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -110,7 +109,6 @@ golang.org/x/tools v0.0.0-20190125232054-d66bd3c5d5a6/go.mod h1:n7NCudcB/nEzxVGm golang.org/x/tools v0.0.0-20190515012406-7d7faa4812bd/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20210106214847-113979e3529a h1:CB3a9Nez8M13wwlr/E2YtwoU+qYHKfC+JrDa45RXXoQ= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.5 h1:ouewzE6p+/VEB31YYnTbEJdi8pFqKp4P4n85vwo3DHA= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= From a644175b8f80ba1fbc220799b4cd9ce257ccc7ac Mon Sep 17 00:00:00 2001 From: Michael Tibben Date: Fri, 10 Sep 2021 21:36:34 +1000 Subject: [PATCH 15/19] Update error checks for go 1.17 --- codegen/config/config_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/codegen/config/config_test.go b/codegen/config/config_test.go index 9dcd0a59958..56001118afb 100644 --- a/codegen/config/config_test.go +++ b/codegen/config/config_test.go @@ -83,7 +83,7 @@ func TestLoadConfigFromDefaultLocation(t *testing.T) { require.NoError(t, err) cfg, err = LoadConfigFromDefaultLocations() - require.True(t, os.IsNotExist(err)) + require.True(t, errors.Is(err, fs.ErrNotExist)) }) } From a8903ca2aca700217fe29c2b8c262b6ee45959fb Mon Sep 17 00:00:00 2001 From: Michael Tibben Date: Fri, 10 Sep 2021 21:42:48 +1000 Subject: [PATCH 16/19] Wrap errors --- client/client.go | 8 ++++---- client/websocket.go | 18 +++++++++--------- internal/rewrite/rewriter.go | 2 +- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/client/client.go b/client/client.go index 64367931e9f..9c5f56c8fc3 100644 --- a/client/client.go +++ b/client/client.go @@ -82,7 +82,7 @@ func (p *Client) Post(query string, response interface{}, options ...Option) err func (p *Client) RawPost(query string, options ...Option) (*Response, error) { r, err := p.newRequest(query, options...) if err != nil { - return nil, fmt.Errorf("build: %s", err.Error()) + return nil, fmt.Errorf("build: %w", err) } w := httptest.NewRecorder() @@ -97,7 +97,7 @@ func (p *Client) RawPost(query string, options ...Option) (*Response, error) { respDataRaw := &Response{} err = json.Unmarshal(w.Body.Bytes(), &respDataRaw) if err != nil { - return nil, fmt.Errorf("decode: %s", err.Error()) + return nil, fmt.Errorf("decode: %w", err) } return respDataRaw, nil @@ -123,7 +123,7 @@ func (p *Client) newRequest(query string, options ...Option) (*http.Request, err case "application/json": requestBody, err := json.Marshal(bd) if err != nil { - return nil, fmt.Errorf("encode: %s", err.Error()) + return nil, fmt.Errorf("encode: %w", err) } bd.HTTP.Body = ioutil.NopCloser(bytes.NewBuffer(requestBody)) default: @@ -141,7 +141,7 @@ func unpack(data interface{}, into interface{}) error { ZeroFields: true, }) if err != nil { - return fmt.Errorf("mapstructure: %s", err.Error()) + return fmt.Errorf("mapstructure: %w", err) } return d.Decode(data) diff --git a/client/websocket.go b/client/websocket.go index 35c74dddcd3..ca6ee7c4723 100644 --- a/client/websocket.go +++ b/client/websocket.go @@ -53,12 +53,12 @@ func (p *Client) WebsocketOnce(query string, resp interface{}, options ...Option func (p *Client) WebsocketWithPayload(query string, initPayload map[string]interface{}, options ...Option) *Subscription { r, err := p.newRequest(query, options...) if err != nil { - return errorSubscription(fmt.Errorf("request: %s", err.Error())) + return errorSubscription(fmt.Errorf("request: %w", err)) } requestBody, err := ioutil.ReadAll(r.Body) if err != nil { - return errorSubscription(fmt.Errorf("parse body: %s", err.Error())) + return errorSubscription(fmt.Errorf("parse body: %w", err)) } srv := httptest.NewServer(p.h) @@ -66,24 +66,24 @@ func (p *Client) WebsocketWithPayload(query string, initPayload map[string]inter c, _, err := websocket.DefaultDialer.Dial(host+r.URL.Path, r.Header) if err != nil { - return errorSubscription(fmt.Errorf("dial: %s", err.Error())) + return errorSubscription(fmt.Errorf("dial: %w", err)) } initMessage := operationMessage{Type: connectionInitMsg} if initPayload != nil { initMessage.Payload, err = json.Marshal(initPayload) if err != nil { - return errorSubscription(fmt.Errorf("parse payload: %s", err.Error())) + return errorSubscription(fmt.Errorf("parse payload: %w", err)) } } if err = c.WriteJSON(initMessage); err != nil { - return errorSubscription(fmt.Errorf("init: %s", err.Error())) + return errorSubscription(fmt.Errorf("init: %w", err)) } var ack operationMessage if err = c.ReadJSON(&ack); err != nil { - return errorSubscription(fmt.Errorf("ack: %s", err.Error())) + return errorSubscription(fmt.Errorf("ack: %w", err)) } if ack.Type != connectionAckMsg { @@ -92,7 +92,7 @@ func (p *Client) WebsocketWithPayload(query string, initPayload map[string]inter var ka operationMessage if err = c.ReadJSON(&ka); err != nil { - return errorSubscription(fmt.Errorf("ack: %s", err.Error())) + return errorSubscription(fmt.Errorf("ack: %w", err)) } if ka.Type != connectionKaMsg { @@ -100,7 +100,7 @@ func (p *Client) WebsocketWithPayload(query string, initPayload map[string]inter } if err = c.WriteJSON(operationMessage{Type: startMsg, ID: "1", Payload: requestBody}); err != nil { - return errorSubscription(fmt.Errorf("start: %s", err.Error())) + return errorSubscription(fmt.Errorf("start: %w", err)) } return &Subscription{ @@ -125,7 +125,7 @@ func (p *Client) WebsocketWithPayload(query string, initPayload map[string]inter var respDataRaw Response err = json.Unmarshal(op.Payload, &respDataRaw) if err != nil { - return fmt.Errorf("decode: %s", err.Error()) + return fmt.Errorf("decode: %w", err) } // we want to unpack even if there is an error, so we can see partial responses diff --git a/internal/rewrite/rewriter.go b/internal/rewrite/rewriter.go index 1b9adb171ee..f70fbdc1d59 100644 --- a/internal/rewrite/rewriter.go +++ b/internal/rewrite/rewriter.go @@ -58,7 +58,7 @@ func (r *Rewriter) getFile(filename string) string { if _, ok := r.files[filename]; !ok { b, err := ioutil.ReadFile(filename) if err != nil { - panic(fmt.Errorf("unable to load file, already exists: %s", err.Error())) + panic(fmt.Errorf("unable to load file, already exists: %w", err)) } r.files[filename] = string(b) From 71e5784352a3c6d7b91bf9f2307fcebc959ab8b0 Mon Sep 17 00:00:00 2001 From: Michael Tibben Date: Fri, 10 Sep 2021 22:53:55 +1000 Subject: [PATCH 17/19] Simplify init --- cmd/init.go | 95 ++++++++++++++++++++++++++++------------------------- 1 file changed, 50 insertions(+), 45 deletions(-) diff --git a/cmd/init.go b/cmd/init.go index daa449969a7..4cf70dde68b 100644 --- a/cmd/init.go +++ b/cmd/init.go @@ -111,69 +111,71 @@ var initCmd = &cli.Command{ Usage: "create a new gqlgen project", Flags: []cli.Flag{ &cli.BoolFlag{Name: "verbose, v", Usage: "show logs"}, - &cli.StringFlag{Name: "config, c", Usage: "the config filename"}, + &cli.StringFlag{Name: "config, c", Usage: "the config filename", Value: "gqlgen.yml"}, &cli.StringFlag{Name: "server", Usage: "where to write the server stub to", Value: "server.go"}, &cli.StringFlag{Name: "schema", Usage: "where to write the schema stub to", Value: "graph/schema.graphqls"}, }, Action: func(ctx *cli.Context) error { configFilename := ctx.String("config") serverFilename := ctx.String("server") + schemaFilename := ctx.String("schema") pkgName := code.ImportPathForDir(".") if pkgName == "" { return fmt.Errorf("unable to determine import path for current directory, you probably need to run go mod init first") } - if err := initFile(ctx.String("schema"), schemaDefault); err != nil { + // check schema and config don't already exist + if fileExists(configFilename) { + return fmt.Errorf("%s already exists\n", configFilename) + } + if fileExists(schemaFilename) { + return fmt.Errorf("%s already exists\n", schemaFilename) + } + if fileExists(serverFilename) { + return fmt.Errorf("%s already exists\n", serverFilename) + } + _, err := config.LoadConfigFromDefaultLocations() + if err == nil { + return fmt.Errorf("gqlgen.yml already exists in a parent directory\n") + } + + // create config + fmt.Println("Creating", configFilename) + if err := initFile(configFilename, executeConfigTemplate(pkgName)); err != nil { + return err + } + + // create schema + fmt.Println("Creating", schemaFilename) + if err := initFile(schemaFilename, schemaDefault); err != nil { + return err + } + + // create the package directory with a temporary file so that go recognises it as a package + // and autobinding doesn't error out + tmpPackageNameFile := "graph/model/_tmp_gqlgen_init.go" + if err := initFile(tmpPackageNameFile, "package model"); err != nil { return err } + defer os.Remove(tmpPackageNameFile) - cfg, err := loadConfig(configFilename) - - if err != nil { - if configFilename == "" { - configFilename = "gqlgen.yml" - } - - fmt.Println("Creating", configFilename) - if err := initFile(configFilename, executeConfigTemplate(pkgName)); err != nil { - return err - } - - // create the package directory with a temporary file so that go recognises it as a package - // and autobinding doesn't error out - tmpPackageNameFile := "graph/model/_tmp_gqlgen_init.go" - if err := initFile(tmpPackageNameFile, "package model"); err != nil { - return err - } - defer os.Remove(tmpPackageNameFile) - - if cfg, err = loadConfig(configFilename); err != nil { - panic(err) - } - } else { - fmt.Println("Skipping creating gqlgen.yml as it already exists") + var cfg *config.Config + if cfg, err = config.LoadConfig(configFilename); err != nil { + panic(err) } - fmt.Println("Creating graph/...") fmt.Println("Creating", serverFilename) + fmt.Println("Generating...") if err := api.Generate(cfg, api.AddPlugin(servergen.New(serverFilename))); err != nil { fmt.Fprintln(os.Stderr, err.Error()) } - fmt.Fprintf(os.Stdout, "\nExec \"go run ./%s\" to start GraphQL server\n", serverFilename) + fmt.Printf("\nExec \"go run ./%s\" to start GraphQL server\n", serverFilename) return nil }, } -func loadConfig(configFilename string) (*config.Config, error) { - if configFilename != "" { - return config.LoadConfig(configFilename) - } else { - return config.LoadConfigFromDefaultLocations() - } -} - func executeConfigTemplate(pkgName string) string { var buf bytes.Buffer if err := configTemplate.Execute(&buf, pkgName); err != nil { @@ -183,15 +185,18 @@ func executeConfigTemplate(pkgName string) string { return buf.String() } -func initFile(filename, contents string) error { +func fileExists(filename string) bool { _, err := os.Stat(filename) - if errors.Is(err, fs.ErrNotExist) { - if err := os.MkdirAll(filepath.Dir(filename), 0755); err != nil { - return fmt.Errorf("unable to create directory for file '%s': %w", filename, err) - } - if err = ioutil.WriteFile(filename, []byte(contents), 0644); err != nil { - return fmt.Errorf("unable to write file '%s': %w", filename, err) - } + return !errors.Is(err, fs.ErrNotExist) +} + +func initFile(filename, contents string) error { + if err := os.MkdirAll(filepath.Dir(filename), 0755); err != nil { + return fmt.Errorf("unable to create directory for file '%s': %w\n", filename, err) } + if err := ioutil.WriteFile(filename, []byte(contents), 0644); err != nil { + return fmt.Errorf("unable to write file '%s': %w\n", filename, err) + } + return nil } From f67a5b2611ca89dfb0ffd3dd4c72cebb8f2532ef Mon Sep 17 00:00:00 2001 From: Michael Tibben Date: Mon, 13 Sep 2021 12:46:35 +1000 Subject: [PATCH 18/19] Update github.com/urfave/cli/v2 --- go.mod | 7 +++---- go.sum | 12 +++++++----- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/go.mod b/go.mod index 78a5fb6b034..f63d58e4b43 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( github.com/shurcooL/httpfs v0.0.0-20171119174359-809beceb2371 // indirect github.com/shurcooL/vfsgen v0.0.0-20180121065927-ffb13db8def0 // indirect github.com/stretchr/testify v1.4.0 - github.com/urfave/cli/v2 v2.1.1 + github.com/urfave/cli/v2 v2.3.0 github.com/vektah/dataloaden v0.2.1-0.20190515034641-a19b9a6e7c9e github.com/vektah/gqlparser/v2 v2.2.0 golang.org/x/tools v0.1.5 @@ -30,12 +30,11 @@ require ( ) require ( - github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d // indirect + github.com/cpuguy83/go-md2man/v2 v2.0.1 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/pkg/errors v0.8.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/russross/blackfriday/v2 v2.0.1 // indirect - github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect + github.com/russross/blackfriday/v2 v2.1.0 // indirect golang.org/x/mod v0.4.2 // indirect golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4 // indirect golang.org/x/sys v0.0.0-20210510120138-977fb7262007 // indirect diff --git a/go.sum b/go.sum index 14f53f5b1ab..e80fdd19148 100644 --- a/go.sum +++ b/go.sum @@ -6,8 +6,9 @@ github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 h1:bvNMNQO63//z+xNg github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8= github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0 h1:jfIu9sQUG6Ig+0+Ap1h4unLjW6YQJpKZVmUzxsD4E/Q= github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0/go.mod h1:t2tdKJDJF9BV14lnkjHmOQgcvEKgtqs5a1N3LNdJhGE= -github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d h1:U+s90UTSYgptZMwQh2aRr3LuazLJIa+Pg3Kc1ylSYVY= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= +github.com/cpuguy83/go-md2man/v2 v2.0.1 h1:r/myEWzV9lfsM1tFLgDyu0atFtJ1fXn261LKYj/3DxU= +github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -51,13 +52,13 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/rs/cors v1.6.0 h1:G9tHG9lebljV9mfp9SNPDL36nCDxmo3zTlAf1YgvzmI= github.com/rs/cors v1.6.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= -github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0RK8m9o+Q= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/shurcooL/httpfs v0.0.0-20171119174359-809beceb2371 h1:SWV2fHctRpRrp49VXJ6UZja7gU9QLHwRpIPBN89SKEo= github.com/shurcooL/httpfs v0.0.0-20171119174359-809beceb2371/go.mod h1:ZY1cvUeJuFPAdZ/B6v7RHavJWZn2YPVFQ1OSXhCGOkg= -github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/shurcooL/vfsgen v0.0.0-20180121065927-ffb13db8def0 h1:JJV9CsgM9EC9w2iVkwuz+sMx8yRFe89PJRUrv6hPCIA= github.com/shurcooL/vfsgen v0.0.0-20180121065927-ffb13db8def0/go.mod h1:TrYk7fJVaAttu97ZZKrO9UbRa8izdowaMIZcxYMbVaw= @@ -65,8 +66,8 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/testify v1.2.1/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/urfave/cli/v2 v2.1.1 h1:Qt8FeAtxE/vfdrLmR3rxR6JRE0RoVmbXu8+6kZtYU4k= -github.com/urfave/cli/v2 v2.1.1/go.mod h1:SE9GqnLQmjVa0iPEY0f1w3ygNIYcIJ0OKPMoW2caLfQ= +github.com/urfave/cli/v2 v2.3.0 h1:qph92Y649prgesehzOrQjdWyxFOp/QVM+6imKHad91M= +github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI= github.com/vektah/dataloaden v0.2.1-0.20190515034641-a19b9a6e7c9e h1:+w0Zm/9gaWpEAyDlU1eKOuk5twTjAjuevXqcJJw8hrg= github.com/vektah/dataloaden v0.2.1-0.20190515034641-a19b9a6e7c9e/go.mod h1:/HUdMve7rvxZma+2ZELQeNh88+003LL7Pf/CZ089j8U= github.com/vektah/gqlparser/v2 v2.2.0 h1:bAc3slekAAJW6sZTi07aGq0OrfaCjj4jxARAaC7g2EM= @@ -121,6 +122,7 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8 gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4 h1:/eiJrUcujPVeJ3xlSWaiNi3uSVmDGBK1pDHUHAnao1I= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= sourcegraph.com/sourcegraph/appdash v0.0.0-20190731080439-ebfcffb1b5c0 h1:ucqkfpjg9WzSUubAO62csmucvxl4/JeW3F4I4909XkM= From 9162c53fc32471c96d874764b47bf71f0c493fce Mon Sep 17 00:00:00 2001 From: Michael Tibben Date: Mon, 13 Sep 2021 13:20:57 +1000 Subject: [PATCH 19/19] Fix newlines in error messages --- cmd/init.go | 12 ++++-------- cmd/root.go | 2 +- 2 files changed, 5 insertions(+), 9 deletions(-) diff --git a/cmd/init.go b/cmd/init.go index 4cf70dde68b..1a528be4d85 100644 --- a/cmd/init.go +++ b/cmd/init.go @@ -126,14 +126,10 @@ var initCmd = &cli.Command{ } // check schema and config don't already exist - if fileExists(configFilename) { - return fmt.Errorf("%s already exists\n", configFilename) - } - if fileExists(schemaFilename) { - return fmt.Errorf("%s already exists\n", schemaFilename) - } - if fileExists(serverFilename) { - return fmt.Errorf("%s already exists\n", serverFilename) + for _, filename := range []string{configFilename, schemaFilename, serverFilename} { + if fileExists(filename) { + return fmt.Errorf("%s already exists", filename) + } } _, err := config.LoadConfigFromDefaultLocations() if err == nil { diff --git a/cmd/root.go b/cmd/root.go index 2776aa2842f..ce96c1b86d2 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -39,7 +39,7 @@ func Execute() { } if err := app.Run(os.Args); err != nil { - fmt.Fprint(os.Stderr, err.Error()) + fmt.Fprint(os.Stderr, err.Error()+"\n") os.Exit(1) } }