]> Cypherpunks repositories - gostls13.git/commitdiff
cmd/go: do not permit importing a main package
authorIan Lance Taylor <iant@golang.org>
Thu, 11 Jun 2015 19:04:30 +0000 (12:04 -0700)
committerIan Lance Taylor <iant@golang.org>
Fri, 19 Jun 2015 01:06:36 +0000 (01:06 +0000)
Fixes #4210.

Change-Id: Id981814a6e55a57403ce7a8ac45ab3ba081a3a86
Reviewed-on: https://go-review.googlesource.com/10925
Reviewed-by: Russ Cox <rsc@golang.org>
src/cmd/go/go_test.go
src/cmd/go/pkg.go

index 4360603326173f723249de160b5d4502010ac5c4..0ba72b04869d90be7dc052e045cc10f701952071 100644 (file)
@@ -1830,3 +1830,21 @@ func TestGoGetRscIoToolstash(t *testing.T) {
        tg.cd(tg.path("src/rsc.io"))
        tg.run("get", "./toolstash")
 }
+
+// Test that you can not import a main package.
+func TestIssue4210(t *testing.T) {
+       tg := testgo(t)
+       defer tg.cleanup()
+       tg.tempFile("src/x/main.go", `package main
+               var X int
+               func main() {}`)
+       tg.tempFile("src/y/main.go", `package main
+               import "fmt"
+               import xmain "x"
+               func main() {
+                       fmt.Println(xmain.X)
+               }`)
+       tg.setenv("GOPATH", tg.path("."))
+       tg.runFail("build", "y")
+       tg.grepBoth("is a program", `did not find expected error message ("is a program")`)
+}
index cf3e8b38aafb9c9cf0b5531476c5e4c176a58d9f..71d6587116b2c22c75e9574b3c48aee8621451e9 100644 (file)
@@ -631,6 +631,16 @@ func (p *Package) load(stk *importStack, bp *build.Package, err error) *Package
                        continue
                }
                p1 := loadImport(path, p.Dir, stk, p.build.ImportPos[path])
+               if p1.Name == "main" {
+                       p.Error = &PackageError{
+                               ImportStack: stk.copy(),
+                               Err:         fmt.Sprintf("import %q is a program, not an importable package", path),
+                       }
+                       pos := p.build.ImportPos[path]
+                       if len(pos) > 0 {
+                               p.Error.Pos = pos[0].String()
+                       }
+               }
                if p1.local {
                        if !p.local && p.Error == nil {
                                p.Error = &PackageError{