Skip to content

Commit

Permalink
imports: handle missing main module
Browse files Browse the repository at this point in the history
If GO111MODULE=on but there's no go.mod, GOMOD will be set to /dev/null
or NUL and there will be no main module. goimports should handle this
case roughly the same way the go command does.

Fixes #30855

Change-Id: I6fbf4c056000db5abd8788a6014ae5f13b1c8cd4
Reviewed-on: https://go-review.googlesource.com/c/tools/+/167860
Run-TryBot: Heschi Kreinick <heschi@google.com>
Reviewed-by: Ian Cottrell <iancottrell@google.com>
  • Loading branch information
heschi committed Mar 15, 2019
1 parent e6df0c1 commit c74ccfb
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
8 changes: 6 additions & 2 deletions imports/mod.go
Expand Up @@ -24,6 +24,7 @@ import (
type moduleResolver struct {
env *fixEnv

initialized bool
main *moduleJSON
modsByModPath []*moduleJSON // All modules, ordered by # of path components in module Path...
modsByDir []*moduleJSON // ...or Dir.
Expand All @@ -48,7 +49,7 @@ type moduleErrorJSON struct {
}

func (r *moduleResolver) init() error {
if r.main != nil {
if r.initialized {
return nil
}
stdout, err := r.env.invokeGo("list", "-m", "-json", "...")
Expand Down Expand Up @@ -87,6 +88,7 @@ func (r *moduleResolver) init() error {
return count(j) < count(i) // descending order
})

r.initialized = true
return nil
}

Expand Down Expand Up @@ -202,7 +204,9 @@ func (r *moduleResolver) scan(_ references) ([]*pkg, error) {
// Walk GOROOT, GOPATH/pkg/mod, and the main module.
roots := []gopathwalk.Root{
{filepath.Join(r.env.GOROOT, "/src"), gopathwalk.RootGOROOT},
{r.main.Dir, gopathwalk.RootCurrentModule},
}
if r.main != nil {
roots = append(roots, gopathwalk.Root{r.main.Dir, gopathwalk.RootCurrentModule})
}
for _, p := range filepath.SplitList(r.env.GOPATH) {
roots = append(roots, gopathwalk.Root{filepath.Join(p, "/pkg/mod"), gopathwalk.RootModuleCache})
Expand Down
21 changes: 21 additions & 0 deletions imports/mod_112_test.go
@@ -0,0 +1,21 @@
// +build go1.12

package imports

import (
"testing"
)

// Tests that we handle GO111MODULE=on with no go.mod file. See #30855.
func TestNoMainModule(t *testing.T) {
mt := setup(t, `
-- x.go --
package x
`, "")
defer mt.cleanup()
if _, err := mt.env.invokeGo("mod", "download", "rsc.io/quote@v1.5.1"); err != nil {
t.Fatal(err)
}

mt.assertScanFinds("rsc.io/quote", "quote")
}
2 changes: 2 additions & 0 deletions imports/mod_test.go
Expand Up @@ -5,6 +5,7 @@ package imports
import (
"archive/zip"
"fmt"
"go/build"
"io/ioutil"
"os"
"path/filepath"
Expand Down Expand Up @@ -515,6 +516,7 @@ func setup(t *testing.T, main, wd string) *modTest {
}

env := &fixEnv{
GOROOT: build.Default.GOROOT,
GOPATH: filepath.Join(dir, "gopath"),
GO111MODULE: "on",
GOPROXY: "file://" + filepath.ToSlash(proxyDir),
Expand Down

0 comments on commit c74ccfb

Please sign in to comment.