Skip to content

Commit

Permalink
Merge pull request #1038 from 99designs/feat-check-len
Browse files Browse the repository at this point in the history
check slice length
  • Loading branch information
vektah authored Feb 18, 2020
2 parents 07a1386 + 2c3853c commit bc07188
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 18 deletions.
7 changes: 5 additions & 2 deletions internal/rewrite/rewriter.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ func New(importPath string) (*Rewriter, error) {
if err != nil {
return nil, err
}
if len(pkgs) == 0 {
return nil, fmt.Errorf("package not found for importPath: %s", importPath)
}

return &Rewriter{
pkg: pkgs[0],
Expand Down Expand Up @@ -70,11 +73,11 @@ func (r *Rewriter) GetMethodBody(structname string, methodname string) string {
if d.Name.Name != methodname {
continue
}
if d.Recv == nil || d.Recv.List == nil {
if d.Recv == nil || len(d.Recv.List) == 0 {
continue
}
recv := d.Recv.List[0].Type
if star, isStar := d.Recv.List[0].Type.(*ast.StarExpr); isStar {
if star, isStar := recv.(*ast.StarExpr); isStar {
recv = star.X
}
ident, ok := recv.(*ast.Ident)
Expand Down
40 changes: 24 additions & 16 deletions internal/rewrite/rewriter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@ import (
)

func TestRewriter(t *testing.T) {
r, err := New("github.com/99designs/gqlgen/internal/rewrite/testdata")
require.NoError(t, err)
t.Run("default", func(t *testing.T) {
r, err := New("github.com/99designs/gqlgen/internal/rewrite/testdata")
require.NoError(t, err)

body := r.GetMethodBody("Foo", "Method")
require.Equal(t, `
body := r.GetMethodBody("Foo", "Method")
require.Equal(t, `
// leading comment
// field comment
Expand All @@ -21,16 +22,23 @@ func TestRewriter(t *testing.T) {
// trailing comment
`, body)

imps := r.ExistingImports("testdata/example.go")
require.Len(t, imps, 2)
assert.Equal(t, []Import{
{
Alias: "",
ImportPath: "fmt",
},
{
Alias: "lol",
ImportPath: "bytes",
},
}, imps)
imps := r.ExistingImports("testdata/example.go")
require.Len(t, imps, 2)
assert.Equal(t, []Import{
{
Alias: "",
ImportPath: "fmt",
},
{
Alias: "lol",
ImportPath: "bytes",
},
}, imps)

})

t.Run("out of scope dir", func(t *testing.T) {
_, err := New("../../../out-of-gomod/package")
require.Error(t, err)
})
}

0 comments on commit bc07188

Please sign in to comment.