cmd/go/internal/modfetch: report error when querying excluded version

This addresses the issue where silently a new version was selected
instead of downloading the version specified by the user when the
version was excluded in the go.mod file.

Fixes golang/go#24549

Change-Id: I94403025f9629981adf6d90f079e0e820bba0931
Reviewed-on: https://go-review.googlesource.com/113836
Reviewed-by: Russ Cox <rsc@golang.org>
diff --git a/vendor/cmd/go/internal/modfetch/query.go b/vendor/cmd/go/internal/modfetch/query.go
index 3cd7e27..525b594 100644
--- a/vendor/cmd/go/internal/modfetch/query.go
+++ b/vendor/cmd/go/internal/modfetch/query.go
@@ -36,7 +36,11 @@
 	if strings.HasPrefix(vers, "v") && semver.IsValid(vers) {
 		// TODO: This turns query for "v2" into Stat "v2.0.0",
 		// but probably it should allow checking for a branch named "v2".
-		return repo.Stat(semver.Canonical(vers))
+		vers = semver.Canonical(vers)
+		if allowed != nil && !allowed(module.Version{path, vers}) {
+			return nil, fmt.Errorf("%s@%s excluded", path, vers)
+		}
+		return repo.Stat(vers)
 	}
 	if strings.HasPrefix(vers, ">") || strings.HasPrefix(vers, "<") || vers == "latest" {
 		var op string
diff --git a/vendor/cmd/go/vgo_test.go b/vendor/cmd/go/vgo_test.go
index 68060a8..91e3527 100644
--- a/vendor/cmd/go/vgo_test.go
+++ b/vendor/cmd/go/vgo_test.go
@@ -220,7 +220,35 @@
 	tg.grepStderr("copying requirements from .*Gopkg.lock", "did not copy Gopkg.lock")
 	tg.run("-vgo", "list")
 	tg.grepStderrNot("copying requirements from .*Gopkg.lock", "should not copy Gopkg.lock again")
+}
 
+func TestQueryExcluded(t *testing.T) {
+	tg := testgo(t)
+	defer tg.cleanup()
+	tg.makeTempdir()
+
+	tg.must(os.MkdirAll(tg.path("x"), 0777))
+	tg.must(ioutil.WriteFile(tg.path("x/x.go"), []byte(`package x; import _ "github.com/gorilla/mux"`), 0666))
+	gomod := []byte(`
+		module x
+
+		exclude github.com/gorilla/mux v1.6.0
+	`)
+
+	tg.setenv(homeEnvName(), tg.path("home"))
+	tg.cd(tg.path("x"))
+
+	tg.must(ioutil.WriteFile(tg.path("x/go.mod"), gomod, 0666))
+	tg.runFail("-vgo", "get", "github.com/gorilla/mux@v1.6.0")
+	tg.grepStderr("github.com/gorilla/mux@v1.6.0 excluded", "print version excluded")
+
+	tg.must(ioutil.WriteFile(tg.path("x/go.mod"), gomod, 0666))
+	tg.run("-vgo", "get", "github.com/gorilla/mux@v1.6.1")
+	tg.grepStderr("finding github.com/gorilla/mux v1.6.1", "find version 1.6.1")
+
+	tg.must(ioutil.WriteFile(tg.path("x/go.mod"), gomod, 0666))
+	tg.runFail("-vgo", "get", "github.com/gorilla/mux@v1.6")
+	tg.grepStderr("github.com/gorilla/mux@v1.6.0 excluded", "print version excluded")
 }
 
 func TestConvertLegacyConfig(t *testing.T) {