forked from wailsapp/wails
/
staticanalysis.go
76 lines (70 loc) · 1.76 KB
/
staticanalysis.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
package staticanalysis
import (
"go/ast"
"golang.org/x/tools/go/packages"
"path/filepath"
"strings"
)
type EmbedDetails struct {
BaseDir string
EmbedPath string
All bool
}
func (e *EmbedDetails) GetFullPath() string {
return filepath.Join(e.BaseDir, e.EmbedPath)
}
func GetEmbedDetails(sourcePath string) ([]*EmbedDetails, error) {
// read in project files and determine which directories are used for embedding
// return a list of directories
absPath, err := filepath.Abs(sourcePath)
if err != nil {
return nil, err
}
pkgs, err := packages.Load(&packages.Config{
Mode: packages.NeedName | packages.NeedSyntax | packages.NeedTypes | packages.NeedTypesInfo | packages.NeedCompiledGoFiles,
Dir: absPath,
}, "./...")
if err != nil {
return nil, err
}
var result []*EmbedDetails
for _, pkg := range pkgs {
for index, file := range pkg.Syntax {
baseDir := filepath.Dir(pkg.CompiledGoFiles[index])
embedPaths := GetEmbedDetailsForFile(file, baseDir)
if len(embedPaths) > 0 {
result = append(result, embedPaths...)
}
}
}
return result, nil
}
func GetEmbedDetailsForFile(file *ast.File, baseDir string) []*EmbedDetails {
var result []*EmbedDetails
for _, comment := range file.Comments {
for _, c := range comment.List {
if strings.HasPrefix(c.Text, "//go:embed") {
sl := strings.Split(c.Text, " ")
path := ""
all := false
if len(sl) == 1 {
continue
}
embedPath := strings.TrimSpace(sl[1])
switch true {
case strings.HasPrefix(embedPath, "all:"):
path = strings.TrimPrefix(embedPath, "all:")
all = true
default:
path = embedPath
}
result = append(result, &EmbedDetails{
EmbedPath: path,
All: all,
BaseDir: baseDir,
})
}
}
}
return result
}