-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_compile_test.go
More file actions
122 lines (97 loc) · 2.1 KB
/
example_compile_test.go
File metadata and controls
122 lines (97 loc) · 2.1 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
110
111
112
113
114
115
116
117
118
119
120
121
122
package crypt
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
func TestExamplesBuild(t *testing.T) {
examplesDir := "examples"
entries, err := os.ReadDir(examplesDir)
if err != nil {
t.Fatalf("cannot read examples directory: %v", err)
}
for _, e := range entries {
if !e.IsDir() {
continue
}
// CAPTURE LOOP VARS
name := e.Name()
path := filepath.Join(examplesDir, name)
t.Run(name, func(t *testing.T) {
t.Parallel() // 🔑 enable concurrency
if err := buildExampleWithoutTags(path); err != nil {
t.Fatalf("example %q failed to build:\n%s", name, err)
}
})
}
}
func abs(p string) string {
a, err := filepath.Abs(p)
if err != nil {
panic(err)
}
return a
}
func buildExampleWithoutTags(exampleDir string) error {
orig := filepath.Join(exampleDir, "main.go")
src, err := os.ReadFile(orig)
if err != nil {
return fmt.Errorf("read main.go: %w", err)
}
clean := stripBuildTags(src)
tmpDir, err := os.MkdirTemp("", "example-overlay-*")
if err != nil {
return err
}
defer os.RemoveAll(tmpDir)
tmpFile := filepath.Join(tmpDir, "main.go")
if err := os.WriteFile(tmpFile, clean, 0644); err != nil {
return err
}
overlay := map[string]any{
"Replace": map[string]string{
abs(orig): abs(tmpFile),
},
}
overlayJSON, err := json.Marshal(overlay)
if err != nil {
return err
}
overlayPath := filepath.Join(tmpDir, "overlay.json")
if err := os.WriteFile(overlayPath, overlayJSON, 0644); err != nil {
return err
}
cmd := exec.Command(
"go", "build",
"-overlay", overlayPath,
"-o", os.DevNull,
"./"+exampleDir,
)
var stderr bytes.Buffer
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return errors.New(stderr.String())
}
return nil
}
func stripBuildTags(src []byte) []byte {
lines := strings.Split(string(src), "\n")
i := 0
for i < len(lines) {
line := strings.TrimSpace(lines[i])
if strings.HasPrefix(line, "//go:build") ||
strings.HasPrefix(line, "// +build") ||
line == "" {
i++
continue
}
break
}
return []byte(strings.Join(lines[i:], "\n"))
}