Debian Codegraph @

internal/godocfx/pkgload/load.go

raw
1 // Copyright 2021 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package pkgload
16
17 import (
18 "fmt"
19 "go/ast"
20 "go/doc"
21 "go/parser"
22 "go/token"
23 "sort"
24 "strconv"
25 "strings"
26
27 "golang.org/x/tools/go/packages"
28 )
29
30 // Info holds info about a package.
31 type Info struct {
32 Pkg *packages.Package
33 Doc *doc.Package
34 Fset *token.FileSet
35 // ImportRenames is a map from package path to local name or "".
36 ImportRenames map[string]string
37 Status string
38 }
39
40 // Load parses the given glob and returns info for the matching packages.
41 // The workingDir is used for module detection.
42 // Packages that match the filter are ignored.
43 func Load(glob, workingDir string, filter []string) ([]Info, error) {
44 config := &packages.Config{
45 Mode: packages.NeedName | packages.NeedSyntax | packages.NeedTypes | packages.NeedTypesInfo | packages.NeedModule | packages.NeedImports | packages.NeedDeps,
46 Tests: true,
47 Dir: workingDir,
48 }
49
50 allPkgs, err := packages.Load(config, glob)
51 if err != nil {
52 return nil, fmt.Errorf("packages.Load: %v", err)
53 }
54 packages.PrintErrors(allPkgs) // Don't fail everything because of one package.
55
56 if len(allPkgs) == 0 {
57 return nil, fmt.Errorf("pattern %q matched 0 packages", glob)
58 }
59
60 // To sort v1 modules before v2+
61 sort.Slice(allPkgs, func(i, j int) bool {
62 return allPkgs[i].PkgPath < allPkgs[j].PkgPath
63 })
64 modulePath := getModulePath(allPkgs)
65 skippedModules := map[string]struct{}{}
66
67 // First, collect all of the files grouped by package, including test
68 // packages.
69 pkgFiles := map[string][]string{}
70
71 idToPkg := map[string]*packages.Package{}
72 pkgNames := []string{}
73 for _, pkg := range allPkgs {
74 // Ignore filtered packages.
75 if hasPrefix(pkg.PkgPath, filter) {
76 continue
77 }
78
79 id := pkg.ID
80 // See https://pkg.go.dev/golang.org/x/tools/go/packages#Config.
81 // The uncompiled test package shows up as "foo_test [foo.test]".
82 if strings.HasSuffix(id, ".test") ||
83 strings.Contains(id, "internal") ||
84 strings.Contains(id, "third_party") ||
85 (strings.Contains(id, " [") && !strings.Contains(id, "_test [")) {
86 continue
87 }
88 if strings.Contains(id, "_test") {
89 id = id[0:strings.Index(id, "_test [")]
90 } else if pkg.Module != nil {
91 idToPkg[pkg.PkgPath] = pkg
92 pkgNames = append(pkgNames, pkg.PkgPath)
93 // The test package doesn't have Module set.
94 if pkg.Module.Path != modulePath {
95 skippedModules[pkg.Module.Path] = struct{}{}
96 continue
97 }
98 }
99 for _, f := range pkg.Syntax {
100 name := pkg.Fset.File(f.Pos()).Name()
101 if strings.HasSuffix(name, ".go") {
102 pkgFiles[id] = append(pkgFiles[id], name)
103 }
104 }
105 }
106
107 sort.Strings(pkgNames)
108
109 result := []Info{}
110
111 for _, pkgPath := range pkgNames {
112 // Check if pkgPath has prefix of skipped module.
113 skip := false
114 for skipModule := range skippedModules {
115 if strings.HasPrefix(pkgPath, skipModule) {
116 skip = true
117 break
118 }
119 }
120 if skip {
121 continue
122 }
123 parsedFiles := []*ast.File{}
124 fset := token.NewFileSet()
125 for _, f := range pkgFiles[pkgPath] {
126 pf, err := parser.ParseFile(fset, f, nil, parser.ParseComments)
127 if err != nil {
128 return nil, fmt.Errorf("ParseFile: %v", err)
129 }
130 parsedFiles = append(parsedFiles, pf)
131 }
132
133 // Parse out GoDoc.
134 docPkg, err := doc.NewFromFiles(fset, parsedFiles, pkgPath)
135 if err != nil {
136 return nil, fmt.Errorf("doc.NewFromFiles: %v", err)
137 }
138
139 // Extra filter in case the file filtering didn't catch everything.
140 if !strings.HasPrefix(docPkg.ImportPath, modulePath) {
141 continue
142 }
143
144 imports := map[string]string{}
145 for _, f := range parsedFiles {
146 for _, i := range f.Imports {
147 name := ""
148 // i.Name is nil for imports that aren't renamed.
149 if i.Name != nil {
150 name = i.Name.Name
151 }
152 iPath, err := strconv.Unquote(i.Path.Value)
153 if err != nil {
154 return nil, fmt.Errorf("strconv.Unquote: %v", err)
155 }
156 imports[iPath] = name
157 }
158 }
159
160 result = append(result, Info{
161 Pkg: idToPkg[pkgPath],
162 Doc: docPkg,
163 Fset: fset,
164 ImportRenames: imports,
165 Status: pkgStatus(pkgPath, docPkg.Doc, idToPkg[pkgPath].Module.Version),
166 })
167 }
168
169 return result, nil
170 }
171
172 func getModulePath(pkgs []*packages.Package) string {
173 for _, pkg := range pkgs {
174 if pkg.Module != nil && pkg.Module.Path != "" {
175 return pkg.Module.Path
176 }
177 }
178 return ""
179 }
180
181 // pkgStatus returns the status of the given package with the
182 // given GoDoc.
183 //
184 // pkgStatus does not use repo-metadata-full.json because it's
185 // not available for all modules nor all versions.
186 func pkgStatus(importPath, doc, version string) string {
187 switch {
188 case strings.Contains(version, "-"):
189 return "preview"
190
191 case strings.Contains(doc, "\nDeprecated:"):
192 return "deprecated"
193 case strings.Contains(doc, "This package is in alpha"):
194 return "alpha"
195 case strings.Contains(doc, "This package is in beta"):
196 return "beta"
197
198 case strings.Contains(importPath, "alpha"):
199 return "alpha"
200 case strings.Contains(importPath, "beta"):
201 return "beta"
202 }
203
204 return ""
205 }
206
207 func hasPrefix(s string, prefixes []string) bool {
208 for _, prefix := range prefixes {
209 if strings.HasPrefix(s, prefix) {
210 return true
211 }
212 }
213 return false
214 }