File: syntax.go

package info (click to toggle)
golang-github-mmcloughlin-avo 0.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 15,024 kB
  • sloc: xml: 71,029; asm: 14,862; sh: 194; makefile: 21; ansic: 11
file content (46 lines) | stat: -rw-r--r-- 1,315 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package buildtags

import (
	"bufio"
	"bytes"
	"fmt"
	"go/format"
	"strings"
)

// PlusBuildSyntaxSupported reports whether the current Go version supports the
// "// +build" constraint syntax.
func PlusBuildSyntaxSupported() bool { return plusbuild }

// GoBuildSyntaxSupported reports whether the current Go version supports the
// "//go:build" constraint syntax.
func GoBuildSyntaxSupported() bool { return gobuild }

// Format constraints according to the syntax supported by the current Go version.
func Format(t ConstraintsConvertable) (string, error) {
	// Print build tags to minimal Go source that can be passed to go/format.
	src := t.ToConstraints().GoString() + "\npackage stub"

	// Format them.
	formatted, err := format.Source([]byte(src))
	if err != nil {
		return "", fmt.Errorf("format build constraints: %w", err)
	}

	// Extract the comment lines.
	buf := bytes.NewReader(formatted)
	scanner := bufio.NewScanner(buf)
	output := ""
	for scanner.Scan() {
		line := scanner.Text()
		if (PlusBuildSyntaxSupported() && strings.HasPrefix(line, "// +build")) ||
			(GoBuildSyntaxSupported() && strings.HasPrefix(line, "//go:build")) {
			output += line + "\n"
		}
	}
	if err := scanner.Err(); err != nil {
		return "", fmt.Errorf("parse formatted build constraints: %w", err)
	}

	return output, nil
}