Skip to content

Commit

Permalink
Add lookup by go type to import collection
Browse files Browse the repository at this point in the history
  • Loading branch information
vektah committed Jan 7, 2019
1 parent eb10116 commit 70c852e
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
8 changes: 8 additions & 0 deletions codegen/templates/import.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"go/build"
"strconv"

"go/types"

"github.com/99designs/gqlgen/internal/gopath"
)

Expand Down Expand Up @@ -116,6 +118,12 @@ func (s *Imports) Lookup(path string) string {
return imp.Alias
}

func (s *Imports) LookupType(t types.Type) string {
return types.TypeString(t, func(i *types.Package) string {
return s.Lookup(i.Path())
})
}

func (s Imports) findByPath(importPath string) *Import {
for _, imp := range s.imports {
if imp.Path == importPath {
Expand Down
12 changes: 12 additions & 0 deletions codegen/templates/import_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"os"
"testing"

"go/types"

"github.com/stretchr/testify/require"
)

Expand All @@ -22,6 +24,15 @@ func TestImports(t *testing.T) {
require.Equal(t, "bar", a.Lookup(aBar))
})

t.Run("lookup by type", func(t *testing.T) {
a := Imports{destDir: wd}

pkg := types.NewPackage("github.com/99designs/gqlgen/codegen/templates/testdata/b/bar", "bar")
typ := types.NewNamed(types.NewTypeName(0, pkg, "Boolean", types.Typ[types.Bool]), types.Typ[types.Bool], nil)

require.Equal(t, "bar.Boolean", a.LookupType(typ))
})

t.Run("duplicates are decollisioned", func(t *testing.T) {
a := Imports{destDir: wd}

Expand Down Expand Up @@ -83,4 +94,5 @@ bar1 "github.com/99designs/gqlgen/codegen/templates/testdata/b/bar"
require.Equal(t, `abar "github.com/99designs/gqlgen/codegen/templates/testdata/a/bar"
bbar "github.com/99designs/gqlgen/codegen/templates/testdata/b/bar"`, a.String())
})

}
1 change: 0 additions & 1 deletion codegen/templates/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import (
"unicode"

"github.com/99designs/gqlgen/internal/imports"

"github.com/pkg/errors"
)

Expand Down

0 comments on commit 70c852e

Please sign in to comment.