Debian Codegraph @

buildtags/syntax.go

raw symbols SCIP
1 package buildtags
2
3 import (
4 "bufio"
5 "bytes"
6 "fmt"
7 "go/format"
8 "strings"
9 )
10
11 // PlusBuildSyntaxSupported reports whether the current Go version supports the
12 // "// +build" constraint syntax.
13 func PlusBuildSyntaxSupported() bool { return plusbuild }
14
15 // GoBuildSyntaxSupported reports whether the current Go version supports the
16 // "//go:build" constraint syntax.
17 func GoBuildSyntaxSupported() bool { return gobuild }
18
19 // Format constraints according to the syntax supported by the current Go version.
20 func Format(t ConstraintsConvertable) (string, error) {
21 // Print build tags to minimal Go source that can be passed to go/format.
22 src := t.ToConstraints().GoString() + "\npackage stub"
23
24 // Format them.
25 formatted, err := format.Source([]byte(src))
26 if err != nil {
27 return "", fmt.Errorf("format build constraints: %w", err)
28 }
29
30 // Extract the comment lines.
31 buf := bytes.NewReader(formatted)
32 scanner := bufio.NewScanner(buf)
33 output := ""
34 for scanner.Scan() {
35 line := scanner.Text()
36 if (PlusBuildSyntaxSupported() && strings.HasPrefix(line, "// +build")) ||
37 (GoBuildSyntaxSupported() && strings.HasPrefix(line, "//go:build")) {
38 output += line + "\n"
39 }
40 }
41 if err := scanner.Err(); err != nil {
42 return "", fmt.Errorf("parse formatted build constraints: %w", err)
43 }
44
45 return output, nil
46 }