build: module-aware FindMainPackages (#32736)

This fixes `go run build/ci.go install`. It was failing because we
resolved all main packages by parsing sources, which fails when the
source directory contains multiple modules.
This commit is contained in:
Felix Lange 2025-09-24 19:40:49 +02:00 committed by GitHub
parent 48c74f4593
commit 15a94b4331
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 11 additions and 23 deletions

View file

@ -221,7 +221,7 @@ func doInstall(cmdline []string) {
// Default: collect all 'main' packages in cmd/ and build those.
packages := flag.Args()
if len(packages) == 0 {
packages = build.FindMainPackages("./cmd")
packages = build.FindMainPackages(&tc, "./cmd/...")
}
// Do the build!

View file

@ -21,8 +21,6 @@ import (
"bytes"
"flag"
"fmt"
"go/parser"
"go/token"
"io"
"log"
"os"
@ -219,28 +217,18 @@ func UploadSFTP(identityFile, host, dir string, files []string) error {
// FindMainPackages finds all 'main' packages in the given directory and returns their
// package paths.
func FindMainPackages(dir string) []string {
var commands []string
cmds, err := os.ReadDir(dir)
func FindMainPackages(tc *GoToolchain, pattern string) []string {
list := tc.Go("list", "-f", `{{if eq .Name "main"}}{{.ImportPath}}{{end}}`, pattern)
output, err := list.Output()
if err != nil {
log.Fatal(err)
log.Fatal("go list failed:", err)
}
for _, cmd := range cmds {
pkgdir := filepath.Join(dir, cmd.Name())
if !cmd.IsDir() {
continue
}
pkgs, err := parser.ParseDir(token.NewFileSet(), pkgdir, nil, parser.PackageClauseOnly)
if err != nil {
log.Fatal(err)
}
for name := range pkgs {
if name == "main" {
path := "./" + filepath.ToSlash(pkgdir)
commands = append(commands, path)
break
}
var result []string
for l := range bytes.Lines(output) {
l = bytes.TrimSpace(l)
if len(l) > 0 {
result = append(result, string(l))
}
}
return commands
return result
}