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