Skip to content
Snippets Groups Projects
Commit be0d52b7 authored by Jonathan Amsterdam's avatar Jonathan Amsterdam
Browse files

gopls/internal/cache: improve build constraint trimming

Generalize trimContentForPortMatch to handle +build directives.

It assumed only go:build directives, but the +build variety is still
valid, and in fact there is a file in the Go build on my local
Google-internal machine that has them.

This fixes a test that was failing for me because of that file.

Change-Id: I534a18ef6e66575d242406e7b81c32055e3c8ace
Reviewed-on: https://go-review.googlesource.com/c/tools/+/658195


Reviewed-by: default avatarRobert Findley <rfindley@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
parent a70d348b
No related branches found
No related tags found
No related merge requests found
......@@ -7,6 +7,7 @@ package cache
import (
"bytes"
"go/build"
"go/build/constraint"
"go/parser"
"go/token"
"io"
......@@ -173,12 +174,16 @@ func (p port) matches(path string, content []byte) bool {
// without trimming content.
func trimContentForPortMatch(content []byte) []byte {
buildComment := buildComment(content)
return []byte(buildComment + "\npackage p") // package name does not matter
// The package name does not matter, but +build lines
// require a blank line before the package declaration.
return []byte(buildComment + "\n\npackage p")
}
// buildComment returns the first matching //go:build comment in the given
// content, or "" if none exists.
func buildComment(content []byte) string {
var lines []string
f, err := parser.ParseFile(token.NewFileSet(), "", content, parser.PackageClauseOnly|parser.ParseComments)
if err != nil {
return ""
......@@ -186,24 +191,15 @@ func buildComment(content []byte) string {
for _, cg := range f.Comments {
for _, c := range cg.List {
if isGoBuildComment(c.Text) {
if constraint.IsGoBuild(c.Text) {
// A file must have only one //go:build line.
return c.Text
}
if constraint.IsPlusBuild(c.Text) {
// A file may have several // +build lines.
lines = append(lines, c.Text)
}
}
}
return ""
}
// Adapted from go/build/build.go.
//
// TODO(rfindley): use constraint.IsGoBuild once we are on 1.19+.
func isGoBuildComment(line string) bool {
const goBuildComment = "//go:build"
if !strings.HasPrefix(line, goBuildComment) {
return false
}
// Report whether //go:build is followed by a word boundary.
line = strings.TrimSpace(line)
rest := line[len(goBuildComment):]
return len(rest) == 0 || len(strings.TrimSpace(rest)) < len(rest)
return strings.Join(lines, "\n")
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment