-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
115 lines (98 loc) · 2.5 KB
/
main.go
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
// testdetect provides a testingDetector generator.
package main
import (
"errors"
"fmt"
"os"
"golang.org/x/tools/go/packages"
)
//nolint:lll
const testingDetector = `// Code generated by lesiw.io/testdetect. DO NOT EDIT.
package %s
type testingDetector struct{ testingDetectorEmbed }
type testingDetectorEmbed struct{}
func (t testingDetectorEmbed) Testing() bool { return false }
var _ = (testingDetector{}).testingDetectorEmbed
`
//nolint:lll
const testingDetectorTamperProtection = `
import (
"fmt"
"testing"
)
var testingDetectorCovHack bool
func init() { testingDetectorInit() }
func testingDetectorInit() {
if got, want := (testingDetector{}).Testing(), testing.Testing(); testingDetectorCovHack || got != want {
panic(fmt.Sprintf("bad testingDetector state: got %t, want %t", got, want))
}
}`
//nolint:lll
const testingDetectorTest = `// Code generated by lesiw.io/testdetect. DO NOT EDIT.
package %s
func (t testingDetector) Testing() bool { return true }
var _ = (testingDetector{}).testingDetectorEmbed.Testing()
`
var testingDetectorTamperProtectionTest = `func init() {
testingDetectorCovHack = true
defer func() { recover() }()
testingDetectorInit()
}
`
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run() error {
pkg, err := pkgname(".")
if err != nil {
return err
}
ins := pkg
if pkg == "main" {
ins += testingDetectorTamperProtection
}
err = os.WriteFile(
"testing_detector.go",
[]byte(fmt.Sprintf(testingDetector, ins)), 0644,
)
if err != nil {
return fmt.Errorf("could not write testing_detector.go: %w", err)
}
data := []byte(fmt.Sprintf(testingDetectorTest, pkg))
if pkg == "main" {
data = append(data, []byte(testingDetectorTamperProtectionTest)...)
}
err = os.WriteFile("testing_detector_test.go", data, 0644)
if err != nil {
return fmt.Errorf("could not write testing_detector_test.go: %w", err)
}
return nil
}
func pkgname(path string) (string, error) {
pkgs, err := packages.Load(&packages.Config{Mode: packages.NeedName}, ".")
if err != nil {
return "", fmt.Errorf("could not load package in %q: %w", path, err)
}
if len(pkgs) < 1 {
return "", fmt.Errorf("could not find packages in %q", path)
}
var pkgErrs []error
for _, pkg := range pkgs {
if len(pkg.Errors) > 0 {
for _, err := range pkg.Errors {
pkgErrs = append(pkgErrs, err)
}
continue
}
return pkg.Name, nil
}
return "", errors.Join(
append(
[]error{fmt.Errorf("could not load package in %q", path)},
pkgErrs...,
)...,
)
}