-
Notifications
You must be signed in to change notification settings - Fork 49
/
info.go
78 lines (62 loc) · 1.33 KB
/
info.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
package stat
import (
"errors"
"fmt"
"go/parser"
"go/token"
"os"
"golang.org/x/tools/go/packages"
)
type Stat struct {
PackageCount int64
Go Source
OtherFiles Source
Decls Decls
Tokens Tokens
}
func (info *Stat) AllFiles() Source {
var c Source
c.Add(info.Go)
c.Add(info.OtherFiles)
return c
}
func (s *Stat) Add(b Stat) {
s.PackageCount += b.PackageCount
s.Go.Add(b.Go)
s.OtherFiles.Add(b.OtherFiles)
s.Decls.Add(b.Decls)
s.Tokens.Add(b.Tokens)
}
func Package(p *packages.Package) (Stat, []error) {
var info Stat
var errs []error
info.PackageCount = 1
fset := token.NewFileSet()
for _, filename := range p.GoFiles {
src, err := os.ReadFile(filename)
if err != nil {
errs = append(errs, fmt.Errorf("failed to read %q: %w", filename, err))
continue
}
count := SourceFromBytes(src)
info.Go.Add(count)
f, err := parser.ParseFile(fset, filename, src, parser.ParseComments)
if err != nil {
errs = append(errs, fmt.Errorf("failed to parse %q: %w", filename, err))
continue
}
info.Decls.Add(DeclsFromAst(f))
info.Tokens.Add(TokensFromAst(f))
}
for _, filename := range p.OtherFiles {
count, err := SourceFromPath(filename)
info.OtherFiles.Add(count)
if err != nil {
if !errors.Is(err, ErrEmptyFile) {
errs = append(errs, err)
}
continue
}
}
return info, errs
}