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. // Default: collect all 'main' packages in cmd/ and build those.
packages := flag.Args() packages := flag.Args()
if len(packages) == 0 { if len(packages) == 0 {
packages = build.FindMainPackages("./cmd") packages = build.FindMainPackages(&tc, "./cmd/...")
} }
// Do the build! // Do the build!

View file

@ -21,8 +21,6 @@ import (
"bytes" "bytes"
"flag" "flag"
"fmt" "fmt"
"go/parser"
"go/token"
"io" "io"
"log" "log"
"os" "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 // FindMainPackages finds all 'main' packages in the given directory and returns their
// package paths. // package paths.
func FindMainPackages(dir string) []string { func FindMainPackages(tc *GoToolchain, pattern string) []string {
var commands []string list := tc.Go("list", "-f", `{{if eq .Name "main"}}{{.ImportPath}}{{end}}`, pattern)
cmds, err := os.ReadDir(dir) output, err := list.Output()
if err != nil { if err != nil {
log.Fatal(err) log.Fatal("go list failed:", err)
} }
for _, cmd := range cmds { var result []string
pkgdir := filepath.Join(dir, cmd.Name()) for l := range bytes.Lines(output) {
if !cmd.IsDir() { l = bytes.TrimSpace(l)
continue if len(l) > 0 {
} result = append(result, string(l))
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
} }
} }
} return result
return commands
} }