-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanalysis.go
93 lines (88 loc) · 1.92 KB
/
analysis.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
package main
import (
"bufio"
"fmt"
"go/ast"
"os"
"path/filepath"
"strings"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/packages"
)
func Analysis(path string, analyzer *analysis.Analyzer) error {
packages, err := packages.Load(&packages.Config{
Mode: packages.LoadAllSyntax, // nolint:staticcheck
BuildFlags: strings.Split(buildFlag, " "),
}, getAllPackageName(path)...)
if err != nil {
return err
}
// comment
for _, pkg := range packages {
_ = analysisComment(pkg)
}
pass := &analysis.Pass{
Analyzer: analyzer,
Files: []*ast.File{},
ResultOf: map[*analysis.Analyzer]interface{}{},
}
for _, pkg := range packages {
if len(pkg.Errors) > 0 {
return pkg.Errors[0]
}
pass.Fset = pkg.Fset
pass.Files = pkg.Syntax
pass.TypesInfo = pkg.TypesInfo
pass.Pkg = pkg.Types
_, err := analyzer.Run(pass)
if err != nil {
return err
}
}
return nil
}
func getAllPackageName(root string) (packages []string) {
m := make(map[string]int)
var rootmodule string
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
if pkgName, err := getPackageName(path); err == nil {
pkgName = strings.TrimSpace(pkgName)
if path == root {
rootmodule = pkgName
}
if rootmodule != "" {
if !strings.HasPrefix(pkgName, rootmodule) {
return nil
}
}
v := strings.TrimSpace(pkgName) + "/..."
m[v] = 1
}
}
return nil
})
if err != nil {
fmt.Println("Error:", err)
return
}
for k := range m {
packages = append(packages, k)
}
return
}
func getPackageName(dir string) (string, error) {
goModPath := filepath.Join(dir, "go.mod")
file, err := os.Open(goModPath)
if err != nil {
return "", err
}
defer file.Close()
buf := bufio.NewReader(file)
line, _, _ := buf.ReadLine()
packageName := line[6:] // 去除 "module " 前缀
return string(packageName), nil
}