go/packages: Load with no patterns should load "."

At least on the go list driver, which is the default fallback. Note that
we need to call 'go list' on Load("foo") and Load(), but not
Load("name=bar"). This is what the current logic was trying to
accomplish.

But it didn't take into account the case where there are zero initial
patterns, in which case we should still call 'go list'. Fix that, and
add a test.

Fixes #28767.

Change-Id: I40af9eb7f2407449c5683df1403928e2c57c86a4
Reviewed-on: https://go-review.googlesource.com/c/155898
Run-TryBot: Daniel Martí <mvdan@mvdan.cc>
Reviewed-by: Michael Matloob <matloob@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
diff --git a/go/packages/golist.go b/go/packages/golist.go
index ffe36d2..a5717cc 100644
--- a/go/packages/golist.go
+++ b/go/packages/golist.go
@@ -120,7 +120,6 @@
 			}
 		}
 	}
-	patterns = restPatterns
 
 	// TODO(matloob): Remove the definition of listfunc and just use golistPackages once go1.12 is released.
 	var listfunc driver
@@ -139,8 +138,10 @@
 	response := &responseDeduper{}
 	var err error
 
-	// see if we have any patterns to pass through to go list.
-	if len(restPatterns) > 0 {
+	// See if we have any patterns to pass through to go list. Zero initial
+	// patterns also requires a go list call, since it's the equivalent of
+	// ".".
+	if len(restPatterns) > 0 || len(patterns) == 0 {
 		dr, err := listfunc(cfg, restPatterns...)
 		if err != nil {
 			return nil, err
diff --git a/go/packages/packages_test.go b/go/packages/packages_test.go
index b5d451f..3ef87ff 100644
--- a/go/packages/packages_test.go
+++ b/go/packages/packages_test.go
@@ -1277,6 +1277,30 @@
 	}
 }
 
+// Test that Load with no patterns is equivalent to loading "." via the golist
+// driver.
+func TestNoPatterns(t *testing.T) { packagestest.TestAll(t, testNoPatterns) }
+func testNoPatterns(t *testing.T, exporter packagestest.Exporter) {
+	exported := packagestest.Export(t, exporter, []packagestest.Module{{
+		Name: "golang.org/fake",
+		Files: map[string]interface{}{
+			"a/a.go":   `package a;`,
+			"a/b/b.go": `package b;`,
+		}}})
+	defer exported.Cleanup()
+
+	aDir := filepath.Dir(exported.File("golang.org/fake", "a/a.go"))
+	exported.Config.Dir = aDir
+
+	initial, err := packages.Load(exported.Config)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(initial) != 1 || initial[0].Name != "a" {
+		t.Fatalf(`Load() = %v, wanted just the package in the current directory`, initial)
+	}
+}
+
 func TestJSON(t *testing.T) { packagestest.TestAll(t, testJSON) }
 func testJSON(t *testing.T, exporter packagestest.Exporter) {
 	//TODO: add in some errors