This repository has been archived by the owner on Jun 9, 2021. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
load.go
72 lines (67 loc) · 1.64 KB
/
load.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
// Copyright (c) 2017, Daniel Martí <mvdan@mvdan.cc>
// See LICENSE for licensing information
package main
import (
"fmt"
"sort"
"strings"
"golang.org/x/tools/go/packages"
)
func (m *matcher) load(wd string, args ...string) ([]*packages.Package, error) {
mode := packages.NeedName | packages.NeedSyntax |
packages.NeedTypes | packages.NeedTypesInfo
if m.recursive { // need the syntax trees for the dependencies too
mode |= packages.NeedDeps | packages.NeedImports
}
cfg := &packages.Config{
Mode: mode,
Dir: wd,
Fset: m.fset,
Tests: m.tests,
}
pkgs, err := packages.Load(cfg, args...)
if err != nil {
return nil, err
}
jointErr := ""
packages.Visit(pkgs, nil, func(pkg *packages.Package) {
for _, err := range pkg.Errors {
jointErr += err.Error() + "\n"
}
})
if jointErr != "" {
return nil, fmt.Errorf("%s", jointErr)
}
// Make a sorted list of the packages, including transitive dependencies
// if recurse is true.
byPath := make(map[string]*packages.Package)
var addDeps func(*packages.Package)
addDeps = func(pkg *packages.Package) {
if strings.HasSuffix(pkg.PkgPath, ".test") {
// don't add recursive test deps
return
}
for _, imp := range pkg.Imports {
if _, ok := byPath[imp.PkgPath]; ok {
continue // seen; avoid recursive call
}
byPath[imp.PkgPath] = imp
addDeps(imp)
}
}
for _, pkg := range pkgs {
byPath[pkg.PkgPath] = pkg
if m.recursive {
// add all dependencies once
addDeps(pkg)
}
}
pkgs = pkgs[:0]
for _, pkg := range byPath {
pkgs = append(pkgs, pkg)
}
sort.Slice(pkgs, func(i, j int) bool {
return pkgs[i].PkgPath < pkgs[j].PkgPath
})
return pkgs, nil
}