/
parser.go
56 lines (49 loc) · 1.5 KB
/
parser.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
package gounexport
import (
"github.com/dooman87/gounexport/fs"
"github.com/dooman87/gounexport/importer"
"github.com/dooman87/gounexport/util"
"go/token"
"go/types"
)
//ParsePackage parses package and filling info structure.
//It's filling info about all internal packages even if they
//are not imported in the root package.
func ParsePackage(pkgName string, info *types.Info) (*types.Package, *token.FileSet, error) {
collectImporter := new(importer.CollectInfoImporter)
collectImporter.Info = info
var resultPkg *types.Package
var resultFset *token.FileSet
parsedPackages := make(map[string]bool)
notParsedPackage := pkgName
for len(notParsedPackage) > 0 {
collectImporter.Pkg = notParsedPackage
pkg, fset, err := collectImporter.Collect()
if err != nil {
return nil, nil, err
}
//Filling results only from first package
//that was passed as argument to function
if resultPkg == nil {
resultPkg = pkg
resultFset = fset
}
parsedPackages[notParsedPackage] = true
//Searching for a new package that was not parsed before
notParsedPackage = ""
files, err := fs.GetUnusedSources(pkgName, fset)
if err != nil {
return nil, nil, err
}
for _, f := range files {
newNotParsedPackage := fs.GetPackagePath(f)
if !parsedPackages[newNotParsedPackage] {
notParsedPackage = newNotParsedPackage
break
} else {
util.Info("package %s has been already parsed, however %s file is still unused", newNotParsedPackage, f)
}
}
}
return resultPkg, resultFset, nil
}