-
Notifications
You must be signed in to change notification settings - Fork 16
/
check_test.go
82 lines (64 loc) · 1.75 KB
/
check_test.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
package main
import (
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"testing"
_ "github.com/go-rod/rod"
"github.com/go-rod/rod/lib/utils"
"github.com/ysmood/got"
)
func TestCheckCode(t *testing.T) {
g := got.T(t)
g.E(os.RemoveAll("tmp"))
g.E(filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
g.E(err)
if info.IsDir() || path[0] == '.' || strings.HasPrefix(path, "i18n") || filepath.Ext(path) != ".md" {
return nil
}
b, err := os.ReadFile(path)
g.E(err)
checkGoCode(g, path, string(b))
return nil
}))
defer func() {
if e := recover(); e != nil {
t.Error(e)
}
}()
utils.ExecLine(false, "go run golang.org/x/tools/cmd/goimports@latest -w tmp")
utils.ExecLine(false, "go run github.com/ysmood/golangci-lint@latest")
}
var count = 0
func checkGoCode(g got.G, path, body string) {
reg := regexp.MustCompile("(?s)```go\r?\n(.+?)```")
for _, m := range reg.FindAllStringSubmatch(body, -1) {
code := strings.TrimSpace(m[1])
if strings.HasPrefix(code, "package ") {
noop()
} else if strings.Contains(code, "func ") {
code = "package main\n" + vars(code) + code
} else {
code = "package main\n" + vars(code) + "func main() {\n" + code + "\n}"
}
p := filepath.FromSlash(fmt.Sprintf("tmp/code-check/c%03d/main.go", count))
count++
code = "// Source markdown file: " + path + "\n\n" + code
g.E(os.MkdirAll(filepath.Dir(p), 0o755))
g.E(os.WriteFile(p, []byte(code), 0o755))
}
}
func vars(code string) string {
vars := ""
if strings.Contains(code, "page.") && !strings.Contains(code, "page :=") {
vars += "var page *rod.Page\n"
}
if strings.Contains(code, "browser.") && !strings.Contains(code, "browser :=") {
vars += "var browser *rod.Browser\n"
}
return vars
}
func noop() {
}