Skip to content

Commit be0d52b

Browse files
committed
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: Robert Findley <[email protected]> LUCI-TryBot-Result: Go LUCI <[email protected]>
1 parent a70d348 commit be0d52b

File tree

1 file changed

+13
-17
lines changed

1 file changed

+13
-17
lines changed

gopls/internal/cache/port.go

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ package cache
77
import (
88
"bytes"
99
"go/build"
10+
"go/build/constraint"
1011
"go/parser"
1112
"go/token"
1213
"io"
@@ -173,37 +174,32 @@ func (p port) matches(path string, content []byte) bool {
173174
// without trimming content.
174175
func trimContentForPortMatch(content []byte) []byte {
175176
buildComment := buildComment(content)
176-
return []byte(buildComment + "\npackage p") // package name does not matter
177+
// The package name does not matter, but +build lines
178+
// require a blank line before the package declaration.
179+
return []byte(buildComment + "\n\npackage p")
177180
}
178181

179182
// buildComment returns the first matching //go:build comment in the given
180183
// content, or "" if none exists.
181184
func buildComment(content []byte) string {
185+
var lines []string
186+
182187
f, err := parser.ParseFile(token.NewFileSet(), "", content, parser.PackageClauseOnly|parser.ParseComments)
183188
if err != nil {
184189
return ""
185190
}
186191

187192
for _, cg := range f.Comments {
188193
for _, c := range cg.List {
189-
if isGoBuildComment(c.Text) {
194+
if constraint.IsGoBuild(c.Text) {
195+
// A file must have only one //go:build line.
190196
return c.Text
191197
}
198+
if constraint.IsPlusBuild(c.Text) {
199+
// A file may have several // +build lines.
200+
lines = append(lines, c.Text)
201+
}
192202
}
193203
}
194-
return ""
195-
}
196-
197-
// Adapted from go/build/build.go.
198-
//
199-
// TODO(rfindley): use constraint.IsGoBuild once we are on 1.19+.
200-
func isGoBuildComment(line string) bool {
201-
const goBuildComment = "//go:build"
202-
if !strings.HasPrefix(line, goBuildComment) {
203-
return false
204-
}
205-
// Report whether //go:build is followed by a word boundary.
206-
line = strings.TrimSpace(line)
207-
rest := line[len(goBuildComment):]
208-
return len(rest) == 0 || len(strings.TrimSpace(rest)) < len(rest)
204+
return strings.Join(lines, "\n")
209205
}

0 commit comments

Comments
 (0)