Skip to content

Commit 679fd5b

Browse files
cmd/go: do not permit importing a main package
Fixes #4210. Change-Id: Id981814a6e55a57403ce7a8ac45ab3ba081a3a86 Reviewed-on: https://go-review.googlesource.com/10925 Reviewed-by: Russ Cox <[email protected]>
1 parent 8668ac0 commit 679fd5b

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/cmd/go/go_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1830,3 +1830,21 @@ func TestGoGetRscIoToolstash(t *testing.T) {
18301830
tg.cd(tg.path("src/rsc.io"))
18311831
tg.run("get", "./toolstash")
18321832
}
1833+
1834+
// Test that you can not import a main package.
1835+
func TestIssue4210(t *testing.T) {
1836+
tg := testgo(t)
1837+
defer tg.cleanup()
1838+
tg.tempFile("src/x/main.go", `package main
1839+
var X int
1840+
func main() {}`)
1841+
tg.tempFile("src/y/main.go", `package main
1842+
import "fmt"
1843+
import xmain "x"
1844+
func main() {
1845+
fmt.Println(xmain.X)
1846+
}`)
1847+
tg.setenv("GOPATH", tg.path("."))
1848+
tg.runFail("build", "y")
1849+
tg.grepBoth("is a program", `did not find expected error message ("is a program")`)
1850+
}

src/cmd/go/pkg.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -631,6 +631,16 @@ func (p *Package) load(stk *importStack, bp *build.Package, err error) *Package
631631
continue
632632
}
633633
p1 := loadImport(path, p.Dir, stk, p.build.ImportPos[path])
634+
if p1.Name == "main" {
635+
p.Error = &PackageError{
636+
ImportStack: stk.copy(),
637+
Err: fmt.Sprintf("import %q is a program, not an importable package", path),
638+
}
639+
pos := p.build.ImportPos[path]
640+
if len(pos) > 0 {
641+
p.Error.Pos = pos[0].String()
642+
}
643+
}
634644
if p1.local {
635645
if !p.local && p.Error == nil {
636646
p.Error = &PackageError{

0 commit comments

Comments
 (0)