summaryrefslogtreecommitdiff
path: root/script/check-MakeGitError-thread-lock.go
blob: 10ab39f806ad110f42eb64e23419ca8d4150aa0f (plain)
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
package main

import (
	"bytes"
	"fmt"
	"go/ast"
	"go/build"
	"go/parser"
	"go/printer"
	"go/token"
	"log"
	"strings"
)

var (
	fset = token.NewFileSet()
)

func main() {
	log.SetFlags(0)

	bpkg, err := build.ImportDir(".", 0)
	if err != nil {
		log.Fatal(err)
	}

	pkgs, err := parser.ParseDir(fset, bpkg.Dir, nil, 0)
	if err != nil {
		log.Fatal(err)
	}

	for _, pkg := range pkgs {
		if err := checkPkg(pkg); err != nil {
			log.Fatal(err)
		}
	}
	if len(pkgs) == 0 {
		log.Fatal("No packages to check.")
	}
}

var ignoreViolationsInFunc = map[string]bool{
	"MakeGitError":  true,
	"MakeGitError2": true,
}

func checkPkg(pkg *ast.Package) error {
	var violations []string
	ast.Inspect(pkg, func(node ast.Node) bool {
		switch node := node.(type) {
		case *ast.FuncDecl:
			var b bytes.Buffer
			if err := printer.Fprint(&b, fset, node); err != nil {
				log.Fatal(err)
			}
			src := b.String()

			if strings.Contains(src, "MakeGitError") && !strings.Contains(src, "runtime.LockOSThread()") && !strings.Contains(src, "defer runtime.UnlockOSThread()") && !ignoreViolationsInFunc[node.Name.Name] {
				pos := fset.Position(node.Pos())
				violations = append(violations, fmt.Sprintf("%s at %s:%d", node.Name.Name, pos.Filename, pos.Line))
			}
		}
		return true
	})
	if len(violations) > 0 {
		return fmt.Errorf("%d non-thread-locked calls to MakeGitError found. To fix, add the following to each func below that calls MakeGitError, before the cgo call that might produce the error:\n\n\truntime.LockOSThread()\n\tdefer runtime.UnlockOSThread()\n\n%s", len(violations), strings.Join(violations, "\n"))
	}
	return nil
}