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