-
Notifications
You must be signed in to change notification settings - Fork 2
/
imports.go
54 lines (49 loc) · 1.15 KB
/
imports.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
package fake
import (
"go/ast"
"strings"
"golang.org/x/tools/go/packages"
)
type PackageInfo struct {
Ref *ast.ImportSpec
Alias string
Name string
Path string
}
// ParsePackageInfo parses the specified package and returns its package name and import path.
func ParsePackageInfo(importPath string) (*PackageInfo, bool) {
cfg := &packages.Config{
Mode: packages.NeedName | packages.NeedFiles,
}
pkgs, err := packages.Load(cfg, importPath)
if err != nil {
return nil, false
}
if len(pkgs) == 0 {
return nil, false
}
// Assuming the first package is the main package, you might need to adjust this logic.
mainPkg := pkgs[0]
return &PackageInfo{
Name: mainPkg.Name,
Path: mainPkg.PkgPath,
}, true
}
func ParseImports(imports []*ast.ImportSpec) *map[string]*PackageInfo {
importNamePathMap := make(map[string]*PackageInfo)
for _, i := range imports {
trimmedPath := strings.Trim(i.Path.Value, "\"")
info, ok := ParsePackageInfo(trimmedPath)
if !ok {
continue
}
info.Ref = i
name := info.Name
if i.Name != nil {
name = i.Name.Name
info.Alias = name
}
importNamePathMap[name] = info
}
return &importNamePathMap
}