-
Notifications
You must be signed in to change notification settings - Fork 0
/
imports.go
47 lines (39 loc) · 922 Bytes
/
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
package traceable
import (
"fmt"
"strings"
"golang.org/x/tools/go/packages"
)
type ImportedPackage struct {
Name string
Path string
Duplicates []string
}
func createPackageMap(importPaths []string) (map[string]string, error) {
cfg := &packages.Config{
Mode: packages.NeedName |
packages.NeedTypesInfo |
packages.NeedSyntax |
packages.NeedTypes,
}
pkgs, err := packages.Load(cfg, importPaths...)
if err != nil {
return nil, err
}
pkgMap := make(map[string]string)
found := map[string]struct{}{}
for _, pkg := range pkgs {
pkgMap[pkg.PkgPath] = pkg.Name
found[pkg.PkgPath] = struct{}{}
}
var missing []string
for _, importPath := range importPaths {
if _, ok := found[importPath]; !ok {
missing = append(missing, importPath)
}
}
if len(missing) > 0 {
return nil, fmt.Errorf("failed to load packages: %s", strings.Join(missing, ", "))
}
return pkgMap, nil
}