Giant blob of minor changes
[dotfiles/.git] / .config / coc / extensions / coc-go-data / tools / pkg / mod / golang.org / x / tools@v0.0.0-20201028153306-37f0764111ff / internal / imports / mod.go
1 package imports
2
3 import (
4         "bytes"
5         "context"
6         "encoding/json"
7         "fmt"
8         "io/ioutil"
9         "os"
10         "path"
11         "path/filepath"
12         "regexp"
13         "sort"
14         "strconv"
15         "strings"
16
17         "golang.org/x/mod/module"
18         "golang.org/x/tools/internal/gocommand"
19         "golang.org/x/tools/internal/gopathwalk"
20 )
21
22 // ModuleResolver implements resolver for modules using the go command as little
23 // as feasible.
24 type ModuleResolver struct {
25         env            *ProcessEnv
26         moduleCacheDir string
27         dummyVendorMod *gocommand.ModuleJSON // If vendoring is enabled, the pseudo-module that represents the /vendor directory.
28         roots          []gopathwalk.Root
29         scanSema       chan struct{} // scanSema prevents concurrent scans and guards scannedRoots.
30         scannedRoots   map[gopathwalk.Root]bool
31
32         initialized   bool
33         main          *gocommand.ModuleJSON
34         modsByModPath []*gocommand.ModuleJSON // All modules, ordered by # of path components in module Path...
35         modsByDir     []*gocommand.ModuleJSON // ...or Dir.
36
37         // moduleCacheCache stores information about the module cache.
38         moduleCacheCache *dirInfoCache
39         otherCache       *dirInfoCache
40 }
41
42 func newModuleResolver(e *ProcessEnv) *ModuleResolver {
43         r := &ModuleResolver{
44                 env:      e,
45                 scanSema: make(chan struct{}, 1),
46         }
47         r.scanSema <- struct{}{}
48         return r
49 }
50
51 func (r *ModuleResolver) init() error {
52         if r.initialized {
53                 return nil
54         }
55
56         goenv, err := r.env.goEnv()
57         if err != nil {
58                 return err
59         }
60         inv := gocommand.Invocation{
61                 BuildFlags: r.env.BuildFlags,
62                 ModFlag:    r.env.ModFlag,
63                 ModFile:    r.env.ModFile,
64                 Env:        r.env.env(),
65                 Logf:       r.env.Logf,
66                 WorkingDir: r.env.WorkingDir,
67         }
68         mainMod, vendorEnabled, err := gocommand.VendorEnabled(context.TODO(), inv, r.env.GocmdRunner)
69         if err != nil {
70                 return err
71         }
72
73         if mainMod != nil && vendorEnabled {
74                 // Vendor mode is on, so all the non-Main modules are irrelevant,
75                 // and we need to search /vendor for everything.
76                 r.main = mainMod
77                 r.dummyVendorMod = &gocommand.ModuleJSON{
78                         Path: "",
79                         Dir:  filepath.Join(mainMod.Dir, "vendor"),
80                 }
81                 r.modsByModPath = []*gocommand.ModuleJSON{mainMod, r.dummyVendorMod}
82                 r.modsByDir = []*gocommand.ModuleJSON{mainMod, r.dummyVendorMod}
83         } else {
84                 // Vendor mode is off, so run go list -m ... to find everything.
85                 r.initAllMods()
86         }
87
88         if gmc := r.env.Env["GOMODCACHE"]; gmc != "" {
89                 r.moduleCacheDir = gmc
90         } else {
91                 r.moduleCacheDir = filepath.Join(filepath.SplitList(goenv["GOPATH"])[0], "/pkg/mod")
92         }
93
94         sort.Slice(r.modsByModPath, func(i, j int) bool {
95                 count := func(x int) int {
96                         return strings.Count(r.modsByModPath[x].Path, "/")
97                 }
98                 return count(j) < count(i) // descending order
99         })
100         sort.Slice(r.modsByDir, func(i, j int) bool {
101                 count := func(x int) int {
102                         return strings.Count(r.modsByDir[x].Dir, "/")
103                 }
104                 return count(j) < count(i) // descending order
105         })
106
107         r.roots = []gopathwalk.Root{
108                 {filepath.Join(goenv["GOROOT"], "/src"), gopathwalk.RootGOROOT},
109         }
110         if r.main != nil {
111                 r.roots = append(r.roots, gopathwalk.Root{r.main.Dir, gopathwalk.RootCurrentModule})
112         }
113         if vendorEnabled {
114                 r.roots = append(r.roots, gopathwalk.Root{r.dummyVendorMod.Dir, gopathwalk.RootOther})
115         } else {
116                 addDep := func(mod *gocommand.ModuleJSON) {
117                         if mod.Replace == nil {
118                                 // This is redundant with the cache, but we'll skip it cheaply enough.
119                                 r.roots = append(r.roots, gopathwalk.Root{mod.Dir, gopathwalk.RootModuleCache})
120                         } else {
121                                 r.roots = append(r.roots, gopathwalk.Root{mod.Dir, gopathwalk.RootOther})
122                         }
123                 }
124                 // Walk dependent modules before scanning the full mod cache, direct deps first.
125                 for _, mod := range r.modsByModPath {
126                         if !mod.Indirect && !mod.Main {
127                                 addDep(mod)
128                         }
129                 }
130                 for _, mod := range r.modsByModPath {
131                         if mod.Indirect && !mod.Main {
132                                 addDep(mod)
133                         }
134                 }
135                 r.roots = append(r.roots, gopathwalk.Root{r.moduleCacheDir, gopathwalk.RootModuleCache})
136         }
137
138         r.scannedRoots = map[gopathwalk.Root]bool{}
139         if r.moduleCacheCache == nil {
140                 r.moduleCacheCache = &dirInfoCache{
141                         dirs:      map[string]*directoryPackageInfo{},
142                         listeners: map[*int]cacheListener{},
143                 }
144         }
145         if r.otherCache == nil {
146                 r.otherCache = &dirInfoCache{
147                         dirs:      map[string]*directoryPackageInfo{},
148                         listeners: map[*int]cacheListener{},
149                 }
150         }
151         r.initialized = true
152         return nil
153 }
154
155 func (r *ModuleResolver) initAllMods() error {
156         stdout, err := r.env.invokeGo(context.TODO(), "list", "-m", "-json", "...")
157         if err != nil {
158                 return err
159         }
160         for dec := json.NewDecoder(stdout); dec.More(); {
161                 mod := &gocommand.ModuleJSON{}
162                 if err := dec.Decode(mod); err != nil {
163                         return err
164                 }
165                 if mod.Dir == "" {
166                         if r.env.Logf != nil {
167                                 r.env.Logf("module %v has not been downloaded and will be ignored", mod.Path)
168                         }
169                         // Can't do anything with a module that's not downloaded.
170                         continue
171                 }
172                 // golang/go#36193: the go command doesn't always clean paths.
173                 mod.Dir = filepath.Clean(mod.Dir)
174                 r.modsByModPath = append(r.modsByModPath, mod)
175                 r.modsByDir = append(r.modsByDir, mod)
176                 if mod.Main {
177                         r.main = mod
178                 }
179         }
180         return nil
181 }
182
183 func (r *ModuleResolver) ClearForNewScan() {
184         <-r.scanSema
185         r.scannedRoots = map[gopathwalk.Root]bool{}
186         r.otherCache = &dirInfoCache{
187                 dirs:      map[string]*directoryPackageInfo{},
188                 listeners: map[*int]cacheListener{},
189         }
190         r.scanSema <- struct{}{}
191 }
192
193 func (r *ModuleResolver) ClearForNewMod() {
194         <-r.scanSema
195         *r = ModuleResolver{
196                 env:              r.env,
197                 moduleCacheCache: r.moduleCacheCache,
198                 otherCache:       r.otherCache,
199                 scanSema:         r.scanSema,
200         }
201         r.init()
202         r.scanSema <- struct{}{}
203 }
204
205 // findPackage returns the module and directory that contains the package at
206 // the given import path, or returns nil, "" if no module is in scope.
207 func (r *ModuleResolver) findPackage(importPath string) (*gocommand.ModuleJSON, string) {
208         // This can't find packages in the stdlib, but that's harmless for all
209         // the existing code paths.
210         for _, m := range r.modsByModPath {
211                 if !strings.HasPrefix(importPath, m.Path) {
212                         continue
213                 }
214                 pathInModule := importPath[len(m.Path):]
215                 pkgDir := filepath.Join(m.Dir, pathInModule)
216                 if r.dirIsNestedModule(pkgDir, m) {
217                         continue
218                 }
219
220                 if info, ok := r.cacheLoad(pkgDir); ok {
221                         if loaded, err := info.reachedStatus(nameLoaded); loaded {
222                                 if err != nil {
223                                         continue // No package in this dir.
224                                 }
225                                 return m, pkgDir
226                         }
227                         if scanned, err := info.reachedStatus(directoryScanned); scanned && err != nil {
228                                 continue // Dir is unreadable, etc.
229                         }
230                         // This is slightly wrong: a directory doesn't have to have an
231                         // importable package to count as a package for package-to-module
232                         // resolution. package main or _test files should count but
233                         // don't.
234                         // TODO(heschi): fix this.
235                         if _, err := r.cachePackageName(info); err == nil {
236                                 return m, pkgDir
237                         }
238                 }
239
240                 // Not cached. Read the filesystem.
241                 pkgFiles, err := ioutil.ReadDir(pkgDir)
242                 if err != nil {
243                         continue
244                 }
245                 // A module only contains a package if it has buildable go
246                 // files in that directory. If not, it could be provided by an
247                 // outer module. See #29736.
248                 for _, fi := range pkgFiles {
249                         if ok, _ := r.env.matchFile(pkgDir, fi.Name()); ok {
250                                 return m, pkgDir
251                         }
252                 }
253         }
254         return nil, ""
255 }
256
257 func (r *ModuleResolver) cacheLoad(dir string) (directoryPackageInfo, bool) {
258         if info, ok := r.moduleCacheCache.Load(dir); ok {
259                 return info, ok
260         }
261         return r.otherCache.Load(dir)
262 }
263
264 func (r *ModuleResolver) cacheStore(info directoryPackageInfo) {
265         if info.rootType == gopathwalk.RootModuleCache {
266                 r.moduleCacheCache.Store(info.dir, info)
267         } else {
268                 r.otherCache.Store(info.dir, info)
269         }
270 }
271
272 func (r *ModuleResolver) cacheKeys() []string {
273         return append(r.moduleCacheCache.Keys(), r.otherCache.Keys()...)
274 }
275
276 // cachePackageName caches the package name for a dir already in the cache.
277 func (r *ModuleResolver) cachePackageName(info directoryPackageInfo) (string, error) {
278         if info.rootType == gopathwalk.RootModuleCache {
279                 return r.moduleCacheCache.CachePackageName(info)
280         }
281         return r.otherCache.CachePackageName(info)
282 }
283
284 func (r *ModuleResolver) cacheExports(ctx context.Context, env *ProcessEnv, info directoryPackageInfo) (string, []string, error) {
285         if info.rootType == gopathwalk.RootModuleCache {
286                 return r.moduleCacheCache.CacheExports(ctx, env, info)
287         }
288         return r.otherCache.CacheExports(ctx, env, info)
289 }
290
291 // findModuleByDir returns the module that contains dir, or nil if no such
292 // module is in scope.
293 func (r *ModuleResolver) findModuleByDir(dir string) *gocommand.ModuleJSON {
294         // This is quite tricky and may not be correct. dir could be:
295         // - a package in the main module.
296         // - a replace target underneath the main module's directory.
297         //    - a nested module in the above.
298         // - a replace target somewhere totally random.
299         //    - a nested module in the above.
300         // - in the mod cache.
301         // - in /vendor/ in -mod=vendor mode.
302         //    - nested module? Dunno.
303         // Rumor has it that replace targets cannot contain other replace targets.
304         for _, m := range r.modsByDir {
305                 if !strings.HasPrefix(dir, m.Dir) {
306                         continue
307                 }
308
309                 if r.dirIsNestedModule(dir, m) {
310                         continue
311                 }
312
313                 return m
314         }
315         return nil
316 }
317
318 // dirIsNestedModule reports if dir is contained in a nested module underneath
319 // mod, not actually in mod.
320 func (r *ModuleResolver) dirIsNestedModule(dir string, mod *gocommand.ModuleJSON) bool {
321         if !strings.HasPrefix(dir, mod.Dir) {
322                 return false
323         }
324         if r.dirInModuleCache(dir) {
325                 // Nested modules in the module cache are pruned,
326                 // so it cannot be a nested module.
327                 return false
328         }
329         if mod != nil && mod == r.dummyVendorMod {
330                 // The /vendor pseudomodule is flattened and doesn't actually count.
331                 return false
332         }
333         modDir, _ := r.modInfo(dir)
334         if modDir == "" {
335                 return false
336         }
337         return modDir != mod.Dir
338 }
339
340 func (r *ModuleResolver) modInfo(dir string) (modDir string, modName string) {
341         readModName := func(modFile string) string {
342                 modBytes, err := ioutil.ReadFile(modFile)
343                 if err != nil {
344                         return ""
345                 }
346                 return modulePath(modBytes)
347         }
348
349         if r.dirInModuleCache(dir) {
350                 matches := modCacheRegexp.FindStringSubmatch(dir)
351                 index := strings.Index(dir, matches[1]+"@"+matches[2])
352                 modDir := filepath.Join(dir[:index], matches[1]+"@"+matches[2])
353                 return modDir, readModName(filepath.Join(modDir, "go.mod"))
354         }
355         for {
356                 if info, ok := r.cacheLoad(dir); ok {
357                         return info.moduleDir, info.moduleName
358                 }
359                 f := filepath.Join(dir, "go.mod")
360                 info, err := os.Stat(f)
361                 if err == nil && !info.IsDir() {
362                         return dir, readModName(f)
363                 }
364
365                 d := filepath.Dir(dir)
366                 if len(d) >= len(dir) {
367                         return "", "" // reached top of file system, no go.mod
368                 }
369                 dir = d
370         }
371 }
372
373 func (r *ModuleResolver) dirInModuleCache(dir string) bool {
374         if r.moduleCacheDir == "" {
375                 return false
376         }
377         return strings.HasPrefix(dir, r.moduleCacheDir)
378 }
379
380 func (r *ModuleResolver) loadPackageNames(importPaths []string, srcDir string) (map[string]string, error) {
381         if err := r.init(); err != nil {
382                 return nil, err
383         }
384         names := map[string]string{}
385         for _, path := range importPaths {
386                 _, packageDir := r.findPackage(path)
387                 if packageDir == "" {
388                         continue
389                 }
390                 name, err := packageDirToName(packageDir)
391                 if err != nil {
392                         continue
393                 }
394                 names[path] = name
395         }
396         return names, nil
397 }
398
399 func (r *ModuleResolver) scan(ctx context.Context, callback *scanCallback) error {
400         if err := r.init(); err != nil {
401                 return err
402         }
403
404         processDir := func(info directoryPackageInfo) {
405                 // Skip this directory if we were not able to get the package information successfully.
406                 if scanned, err := info.reachedStatus(directoryScanned); !scanned || err != nil {
407                         return
408                 }
409                 pkg, err := r.canonicalize(info)
410                 if err != nil {
411                         return
412                 }
413
414                 if !callback.dirFound(pkg) {
415                         return
416                 }
417                 pkg.packageName, err = r.cachePackageName(info)
418                 if err != nil {
419                         return
420                 }
421
422                 if !callback.packageNameLoaded(pkg) {
423                         return
424                 }
425                 _, exports, err := r.loadExports(ctx, pkg, false)
426                 if err != nil {
427                         return
428                 }
429                 callback.exportsLoaded(pkg, exports)
430         }
431
432         // Start processing everything in the cache, and listen for the new stuff
433         // we discover in the walk below.
434         stop1 := r.moduleCacheCache.ScanAndListen(ctx, processDir)
435         defer stop1()
436         stop2 := r.otherCache.ScanAndListen(ctx, processDir)
437         defer stop2()
438
439         // We assume cached directories are fully cached, including all their
440         // children, and have not changed. We can skip them.
441         skip := func(root gopathwalk.Root, dir string) bool {
442                 info, ok := r.cacheLoad(dir)
443                 if !ok {
444                         return false
445                 }
446                 // This directory can be skipped as long as we have already scanned it.
447                 // Packages with errors will continue to have errors, so there is no need
448                 // to rescan them.
449                 packageScanned, _ := info.reachedStatus(directoryScanned)
450                 return packageScanned
451         }
452
453         // Add anything new to the cache, and process it if we're still listening.
454         add := func(root gopathwalk.Root, dir string) {
455                 r.cacheStore(r.scanDirForPackage(root, dir))
456         }
457
458         // r.roots and the callback are not necessarily safe to use in the
459         // goroutine below. Process them eagerly.
460         roots := filterRoots(r.roots, callback.rootFound)
461         // We can't cancel walks, because we need them to finish to have a usable
462         // cache. Instead, run them in a separate goroutine and detach.
463         scanDone := make(chan struct{})
464         go func() {
465                 select {
466                 case <-ctx.Done():
467                         return
468                 case <-r.scanSema:
469                 }
470                 defer func() { r.scanSema <- struct{}{} }()
471                 // We have the lock on r.scannedRoots, and no other scans can run.
472                 for _, root := range roots {
473                         if ctx.Err() != nil {
474                                 return
475                         }
476
477                         if r.scannedRoots[root] {
478                                 continue
479                         }
480                         gopathwalk.WalkSkip([]gopathwalk.Root{root}, add, skip, gopathwalk.Options{Logf: r.env.Logf, ModulesEnabled: true})
481                         r.scannedRoots[root] = true
482                 }
483                 close(scanDone)
484         }()
485         select {
486         case <-ctx.Done():
487         case <-scanDone:
488         }
489         return nil
490 }
491
492 func (r *ModuleResolver) scoreImportPath(ctx context.Context, path string) float64 {
493         if _, ok := stdlib[path]; ok {
494                 return MaxRelevance
495         }
496         mod, _ := r.findPackage(path)
497         return modRelevance(mod)
498 }
499
500 func modRelevance(mod *gocommand.ModuleJSON) float64 {
501         var relevance float64
502         switch {
503         case mod == nil: // out of scope
504                 return MaxRelevance - 4
505         case mod.Indirect:
506                 relevance = MaxRelevance - 3
507         case !mod.Main:
508                 relevance = MaxRelevance - 2
509         default:
510                 relevance = MaxRelevance - 1 // main module ties with stdlib
511         }
512
513         _, versionString, ok := module.SplitPathVersion(mod.Path)
514         if ok {
515                 index := strings.Index(versionString, "v")
516                 if index == -1 {
517                         return relevance
518                 }
519                 if versionNumber, err := strconv.ParseFloat(versionString[index+1:], 64); err == nil {
520                         relevance += versionNumber / 1000
521                 }
522         }
523
524         return relevance
525 }
526
527 // canonicalize gets the result of canonicalizing the packages using the results
528 // of initializing the resolver from 'go list -m'.
529 func (r *ModuleResolver) canonicalize(info directoryPackageInfo) (*pkg, error) {
530         // Packages in GOROOT are already canonical, regardless of the std/cmd modules.
531         if info.rootType == gopathwalk.RootGOROOT {
532                 return &pkg{
533                         importPathShort: info.nonCanonicalImportPath,
534                         dir:             info.dir,
535                         packageName:     path.Base(info.nonCanonicalImportPath),
536                         relevance:       MaxRelevance,
537                 }, nil
538         }
539
540         importPath := info.nonCanonicalImportPath
541         mod := r.findModuleByDir(info.dir)
542         // Check if the directory is underneath a module that's in scope.
543         if mod != nil {
544                 // It is. If dir is the target of a replace directive,
545                 // our guessed import path is wrong. Use the real one.
546                 if mod.Dir == info.dir {
547                         importPath = mod.Path
548                 } else {
549                         dirInMod := info.dir[len(mod.Dir)+len("/"):]
550                         importPath = path.Join(mod.Path, filepath.ToSlash(dirInMod))
551                 }
552         } else if !strings.HasPrefix(importPath, info.moduleName) {
553                 // The module's name doesn't match the package's import path. It
554                 // probably needs a replace directive we don't have.
555                 return nil, fmt.Errorf("package in %q is not valid without a replace statement", info.dir)
556         }
557
558         res := &pkg{
559                 importPathShort: importPath,
560                 dir:             info.dir,
561                 relevance:       modRelevance(mod),
562         }
563         // We may have discovered a package that has a different version
564         // in scope already. Canonicalize to that one if possible.
565         if _, canonicalDir := r.findPackage(importPath); canonicalDir != "" {
566                 res.dir = canonicalDir
567         }
568         return res, nil
569 }
570
571 func (r *ModuleResolver) loadExports(ctx context.Context, pkg *pkg, includeTest bool) (string, []string, error) {
572         if err := r.init(); err != nil {
573                 return "", nil, err
574         }
575         if info, ok := r.cacheLoad(pkg.dir); ok && !includeTest {
576                 return r.cacheExports(ctx, r.env, info)
577         }
578         return loadExportsFromFiles(ctx, r.env, pkg.dir, includeTest)
579 }
580
581 func (r *ModuleResolver) scanDirForPackage(root gopathwalk.Root, dir string) directoryPackageInfo {
582         subdir := ""
583         if dir != root.Path {
584                 subdir = dir[len(root.Path)+len("/"):]
585         }
586         importPath := filepath.ToSlash(subdir)
587         if strings.HasPrefix(importPath, "vendor/") {
588                 // Only enter vendor directories if they're explicitly requested as a root.
589                 return directoryPackageInfo{
590                         status: directoryScanned,
591                         err:    fmt.Errorf("unwanted vendor directory"),
592                 }
593         }
594         switch root.Type {
595         case gopathwalk.RootCurrentModule:
596                 importPath = path.Join(r.main.Path, filepath.ToSlash(subdir))
597         case gopathwalk.RootModuleCache:
598                 matches := modCacheRegexp.FindStringSubmatch(subdir)
599                 if len(matches) == 0 {
600                         return directoryPackageInfo{
601                                 status: directoryScanned,
602                                 err:    fmt.Errorf("invalid module cache path: %v", subdir),
603                         }
604                 }
605                 modPath, err := module.UnescapePath(filepath.ToSlash(matches[1]))
606                 if err != nil {
607                         if r.env.Logf != nil {
608                                 r.env.Logf("decoding module cache path %q: %v", subdir, err)
609                         }
610                         return directoryPackageInfo{
611                                 status: directoryScanned,
612                                 err:    fmt.Errorf("decoding module cache path %q: %v", subdir, err),
613                         }
614                 }
615                 importPath = path.Join(modPath, filepath.ToSlash(matches[3]))
616         }
617
618         modDir, modName := r.modInfo(dir)
619         result := directoryPackageInfo{
620                 status:                 directoryScanned,
621                 dir:                    dir,
622                 rootType:               root.Type,
623                 nonCanonicalImportPath: importPath,
624                 moduleDir:              modDir,
625                 moduleName:             modName,
626         }
627         if root.Type == gopathwalk.RootGOROOT {
628                 // stdlib packages are always in scope, despite the confusing go.mod
629                 return result
630         }
631         return result
632 }
633
634 // modCacheRegexp splits a path in a module cache into module, module version, and package.
635 var modCacheRegexp = regexp.MustCompile(`(.*)@([^/\\]*)(.*)`)
636
637 var (
638         slashSlash = []byte("//")
639         moduleStr  = []byte("module")
640 )
641
642 // modulePath returns the module path from the gomod file text.
643 // If it cannot find a module path, it returns an empty string.
644 // It is tolerant of unrelated problems in the go.mod file.
645 //
646 // Copied from cmd/go/internal/modfile.
647 func modulePath(mod []byte) string {
648         for len(mod) > 0 {
649                 line := mod
650                 mod = nil
651                 if i := bytes.IndexByte(line, '\n'); i >= 0 {
652                         line, mod = line[:i], line[i+1:]
653                 }
654                 if i := bytes.Index(line, slashSlash); i >= 0 {
655                         line = line[:i]
656                 }
657                 line = bytes.TrimSpace(line)
658                 if !bytes.HasPrefix(line, moduleStr) {
659                         continue
660                 }
661                 line = line[len(moduleStr):]
662                 n := len(line)
663                 line = bytes.TrimSpace(line)
664                 if len(line) == n || len(line) == 0 {
665                         continue
666                 }
667
668                 if line[0] == '"' || line[0] == '`' {
669                         p, err := strconv.Unquote(string(line))
670                         if err != nil {
671                                 return "" // malformed quoted string or multiline module path
672                         }
673                         return p
674                 }
675
676                 return string(line)
677         }
678         return "" // missing module path
679 }