Skip to content

Commit 1e6ecd4

Browse files
committed
go/packages: don't crash if given an invalid overlay
If the user of go/packages passes an overlay package that results in a package having Go files in multiple directories, return an error instead of crashing. This is more of a bandaid than a fix for anything, but go/packages is hard to follow even with full data. Without it I don't really have a clue, so this is the best I've got. Fixes golang/go#43520, I guess. Change-Id: I37537ae2e0126f715719273ed9a6708ed53b850f Reviewed-on: https://go-review.googlesource.com/c/tools/+/282732 Trust: Heschi Kreinick <heschi@google.com> Run-TryBot: Heschi Kreinick <heschi@google.com> gopls-CI: kokoro <noreply+kokoro@google.com> TryBot-Result: Go Bot <gobot@golang.org> Reviewed-by: Rebecca Stambler <rstambler@golang.org>
1 parent 88ba5d0 commit 1e6ecd4

File tree

1 file changed

+14
-11
lines changed

1 file changed

+14
-11
lines changed

go/packages/golist_overlay.go

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ import (
99
"fmt"
1010
"go/parser"
1111
"go/token"
12-
"log"
1312
"os"
1413
"path/filepath"
1514
"regexp"
@@ -35,9 +34,12 @@ func (state *golistState) processGolistOverlay(response *responseDeduper) (modif
3534
// This is an approximation of import path to id. This can be
3635
// wrong for tests, vendored packages, and a number of other cases.
3736
havePkgs[pkg.PkgPath] = pkg.ID
38-
x := commonDir(pkg.GoFiles)
39-
if x != "" {
40-
pkgOfDir[x] = append(pkgOfDir[x], pkg)
37+
dir, err := commonDir(pkg.GoFiles)
38+
if err != nil {
39+
return nil, nil, err
40+
}
41+
if dir != "" {
42+
pkgOfDir[dir] = append(pkgOfDir[dir], pkg)
4143
}
4244
}
4345

@@ -441,20 +443,21 @@ func extractPackageName(filename string, contents []byte) (string, bool) {
441443
return f.Name.Name, true
442444
}
443445

444-
func commonDir(a []string) string {
446+
// commonDir returns the directory that all files are in, "" if files is empty,
447+
// or an error if they aren't in the same directory.
448+
func commonDir(files []string) (string, error) {
445449
seen := make(map[string]bool)
446-
x := append([]string{}, a...)
447-
for _, f := range x {
450+
for _, f := range files {
448451
seen[filepath.Dir(f)] = true
449452
}
450453
if len(seen) > 1 {
451-
log.Fatalf("commonDir saw %v for %v", seen, x)
454+
return "", fmt.Errorf("files (%v) are in more than one directory: %v", files, seen)
452455
}
453456
for k := range seen {
454-
// len(seen) == 1
455-
return k
457+
// seen has only one element; return it.
458+
return k, nil
456459
}
457-
return "" // no files
460+
return "", nil // no files
458461
}
459462

460463
// It is possible that the files in the disk directory dir have a different package

0 commit comments

Comments
 (0)