-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathreadme_test.go
More file actions
109 lines (92 loc) · 2.5 KB
/
readme_test.go
File metadata and controls
109 lines (92 loc) · 2.5 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package braintrust
import (
_ "embed"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"testing"
)
//go:embed README.md
var readme string
func TestReadmeSnippets(t *testing.T) {
lines := strings.Split(readme, "\n")
var snippet []string
snippetCount := 0
// Collect all snippets first
type codeSnippet struct {
num int
code string
}
var snippets []codeSnippet
for _, line := range lines {
if strings.HasPrefix(line, "```go") {
snippet = []string{}
continue
}
if strings.HasPrefix(line, "```") && snippet != nil {
snippetCount++
code := strings.Join(snippet, "\n")
snippets = append(snippets, codeSnippet{num: snippetCount, code: code})
snippet = nil
continue
}
if snippet != nil {
snippet = append(snippet, line)
}
}
if len(snippets) == 0 {
t.Error("No Go code snippets found in README.md")
return
}
// Compile all snippets in parallel using subtests
for _, s := range snippets {
s := s // capture loop variable
t.Run(strconv.Itoa(s.num), func(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
if err := tryCompile(t, tmpDir, s.num, s.code); err != nil {
t.Errorf("README snippet %d failed to compile: %v\n%s", s.num, err, s.code)
}
})
}
}
func tryCompile(t *testing.T, tmpDir string, snippetNum int, code string) error {
t.Helper()
trimmed := strings.TrimSpace(code)
// Skip build-constrained files (e.g., //go:build tools) - they can't be compiled standalone
if strings.HasPrefix(trimmed, "//go:build") {
t.Skip("skipping build-constrained snippet")
return nil
}
// Skip import-only snippets (no package declaration, just imports)
if strings.HasPrefix(trimmed, "import (") {
t.Skip("skipping import-only snippet")
return nil
}
// Create snippet file in temp directory
snippetPath := filepath.Join(tmpDir, "snippet"+strconv.Itoa(snippetNum)+".go")
// Don't add "package main" if it's already there
if !strings.HasPrefix(trimmed, "package main") {
code = "package main\n\n" + code
}
if err := os.WriteFile(snippetPath, []byte(code), 0644); err != nil {
return err
}
// Build in temp directory to avoid conflicts
outputBinary := filepath.Join(tmpDir, "snippet")
cmd := exec.Command("go", "build", "-o", outputBinary, snippetPath)
output, err := cmd.CombinedOutput()
if err != nil {
return &compileError{err: err, output: string(output)}
}
return nil
}
type compileError struct {
err error
output string
}
func (e *compileError) Error() string {
return e.err.Error() + "\nCompilation output:\n" + e.output
}