Commit 4f80b50e authored by Jens Frederich's avatar Jens Frederich Committed by Russ Cox

go/build: Return MultiplePackageError on importing a dir containing multiple packages

When the Import function in go/build encounters a directory
without any buildable Go source files, it returns a handy
NoGoError. Now if, instead it encounters multiple Go source files
from multiple packages, it returns a handy MultiplePackageError.

A new test for NoGoError and MultiplePackageError is also provided.

Fixes #8286.

LGTM=adg, rsc
R=bradfitz, rsc, adg
CC=golang-codereviews
https://golang.org/cl/155050043
parent ff6d0a4d
......@@ -417,6 +417,19 @@ func (e *NoGoError) Error() string {
return "no buildable Go source files in " + e.Dir
}
// MultiplePackageError describes a directory containing
// multiple buildable Go source files for multiple packages.
type MultiplePackageError struct {
Dir string // directory containing files
Packages []string // package names found
Files []string // corresponding files: Files[i] declares package Packages[i]
}
func (e *MultiplePackageError) Error() string {
// Error string limited to two entries for compatibility.
return fmt.Sprintf("found packages %s (%s) and %s (%s) in %s", e.Packages[0], e.Files[0], e.Packages[1], e.Files[1], e.Dir)
}
func nameExt(name string) string {
i := strings.LastIndex(name, ".")
if i < 0 {
......@@ -675,7 +688,7 @@ Found:
p.Name = pkg
firstFile = name
} else if pkg != p.Name {
return p, fmt.Errorf("found packages %s (%s) and %s (%s) in %s", p.Name, firstFile, pkg, name, p.Dir)
return p, &MultiplePackageError{p.Dir, []string{firstFile, name}, []string{p.Name, pkg}}
}
if pf.Doc != nil && p.Doc == "" {
p.Doc = doc.Synopsis(pf.Doc.Text())
......
......@@ -85,6 +85,20 @@ func TestEmptyImport(t *testing.T) {
}
}
func TestEmptyFolderImport(t *testing.T) {
_, err := Import(".", "testdata/empty", 0)
if _, ok := err.(*NoGoError); !ok {
t.Fatal(`Import("testdata/empty") did not return NoGoError.`)
}
}
func TestMultiplePackageImport(t *testing.T) {
_, err := Import(".", "testdata/multi", 0)
if _, ok := err.(*MultiplePackageError); !ok {
t.Fatal(`Import("testdata/multi") did not return MultiplePackageError.`)
}
}
func TestLocalDirectory(t *testing.T) {
cwd, err := os.Getwd()
if err != nil {
......
// Test data - not compiled.
package main
func main() {}
// Test data - not compiled.
package test_package
func init() {}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment