-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathast.go
77 lines (61 loc) · 1.56 KB
/
ast.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
package inspector
import (
"go/ast"
"go/parser"
"go/token"
)
// Reading files requires checking most calls for errors.
// This helper will streamline our error checks below.
func check(e error) {
if e != nil {
panic(e)
}
}
// Extracts all of the functions and structures from the file
func ParseFileContents(filePath string, contents string) *File {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, filePath, contents, 0)
check(err)
file := File{
Path: filePath,
NumberOfLines: fset.Position(f.End()).Line,
Units: []*Unit{},
Commits: []*Commit{},
}
// We walk the syntax tree
ast.Inspect(f, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.FuncDecl:
// Functions have the position of their brackets
u := Unit{
Type: UNIT_TYPE_FUNCTION,
Name: x.Name.Name,
LineStart: fset.Position(x.Body.Lbrace).Line,
LineEnd: fset.Position(x.Body.Rbrace).Line,
RatioSum: 0.0,
TimesChanged: 0,
Commits: []*Commit{},
File: &file,
}
file.Units = append(file.Units, &u)
break
case *ast.TypeSpec:
if _, ok := x.Type.(*ast.StructType); ok {
// Structures only have the position of their beginning and their end (unfortunately no bracket positions)
u := Unit{
Type: UNIT_TYPE_STRUCT,
Name: x.Name.Name,
LineStart: fset.Position(x.Pos()).Line,
LineEnd: fset.Position(x.End()).Line,
RatioSum: 0.0,
TimesChanged: 0,
Commits: []*Commit{},
File: &file,
}
file.Units = append(file.Units, &u)
}
}
return true
})
return &file
}