Skip to content

Commit

Permalink
#2298: fix gqlgen extracting module name from comment line
Browse files Browse the repository at this point in the history
  • Loading branch information
mobiletoly committed Jul 21, 2022
1 parent 779d7cd commit 8215791
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 1 deletion.
25 changes: 24 additions & 1 deletion internal/code/imports.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package code

import (
"bufio"
"fmt"
"go/build"
"go/parser"
"go/token"
Expand Down Expand Up @@ -74,7 +76,7 @@ func goModuleRoot(dir string) (string, bool) {
}

if content, err := os.ReadFile(filepath.Join(modDir, "go.mod")); err == nil {
moduleName := string(modregex.FindSubmatch(content)[1])
moduleName := extractModuleName(content)
result = goModuleSearchResult{
path: moduleName,
goModPath: modDir,
Expand Down Expand Up @@ -126,6 +128,27 @@ func goModuleRoot(dir string) (string, bool) {
return res.path, true
}

func extractModuleName(content []byte) string {
for {
advance, tkn, err := bufio.ScanLines(content, false)
if err != nil {
panic(fmt.Errorf("error parsing mod file: %w", err))
}
if advance == 0 {
break
}
s := strings.Trim(string(tkn), " \t")
if len(s) != 0 && !strings.HasPrefix(s, "//") {
break
}
if advance <= len(content) {
content = content[advance:]
}
}
moduleName := string(modregex.FindSubmatch(content)[1])
return moduleName
}

// ImportPathForDir takes a path and returns a golang import path for the package
func ImportPathForDir(dir string) (res string) {
dir, err := filepath.Abs(dir)
Expand Down
12 changes: 12 additions & 0 deletions internal/code/imports_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,23 @@ import (
"github.com/stretchr/testify/require"
)

func TestExtractModuleName(t *testing.T) {
wd, err := os.Getwd()
require.NoError(t, err)

modDir := filepath.Join(wd, "..", "..", "testdata")
content, err := os.ReadFile(filepath.Join(modDir, "gomod-with-leading-comments.mod"))
require.NoError(t, err)
assert.Equal(t, "github.com/99designs/gqlgen", extractModuleName(content))
}

func TestImportPathForDir(t *testing.T) {
wd, err := os.Getwd()

require.NoError(t, err)

assert.Equal(t, "github.com/99designs/gqlgen/internal/code", ImportPathForDir(wd))

assert.Equal(t, "github.com/99designs/gqlgen/internal/code", ImportPathForDir(wd))
assert.Equal(t, "github.com/99designs/gqlgen/api", ImportPathForDir(filepath.Join(wd, "..", "..", "api")))

Expand Down
7 changes: 7 additions & 0 deletions testdata/gomod-with-leading-comments.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// main module of gqlgen

// and another module to test stripping of comment lines

module github.com/99designs/gqlgen // replace it for new project

go 1.16

0 comments on commit 8215791

Please sign in to comment.