Debian Codegraph @

internal/imports/source_modindex_test.go

raw symbols SCIP
1 // Copyright 2024 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 "context"
9 "sync"
10 "time"
11
12 "golang.org/x/tools/internal/modindex"
13 )
14
15 // This code is here rather than in the modindex package
16 // to avoid import loops
17
18 // TODO(adonovan): this code is only used by a test in this package.
19 // Can we delete it? Or is there a plan to call NewIndexSource from
20 // cmd/goimports?
21
22 // implements Source using modindex, so only for module cache.
23 //
24 // this is perhaps over-engineered. A new Index is read at first use.
25 // And then Update is called after every 15 minutes, and a new Index
26 // is read if the index changed. It is not clear the Mutex is needed.
27 type IndexSource struct {
28 modcachedir string
29 mu sync.Mutex
30 index *modindex.Index // (access via getIndex)
31 expires time.Time
32 }
33
34 // create a new Source. Called from NewView in cache/session.go.
35 func NewIndexSource(cachedir string) *IndexSource {
36 return &IndexSource{modcachedir: cachedir}
37 }
38
39 func (s *IndexSource) LoadPackageNames(ctx context.Context, srcDir string, paths []ImportPath) (map[ImportPath]PackageName, error) {
40 /// This is used by goimports to resolve the package names of imports of the
41 // current package, which is irrelevant for the module cache.
42 return nil, nil
43 }
44
45 func (s *IndexSource) ResolveReferences(ctx context.Context, filename string, missing References) ([]*Result, error) {
46 index, err := s.getIndex()
47 if err != nil {
48 return nil, err
49 }
50 var cs []modindex.Candidate
51 for pkg, nms := range missing {
52 for nm := range nms {
53 x := index.Lookup(pkg, nm, false)
54 cs = append(cs, x...)
55 }
56 }
57 found := make(map[string]*Result)
58 for _, c := range cs {
59 var x *Result
60 if x = found[c.ImportPath]; x == nil {
61 x = &Result{
62 Import: &ImportInfo{
63 ImportPath: c.ImportPath,
64 Name: "",
65 },
66 Package: &PackageInfo{
67 Name: c.PkgName,
68 Exports: make(map[string]bool),
69 },
70 }
71 found[c.ImportPath] = x
72 }
73 x.Package.Exports[c.Name] = true
74 }
75 var ans []*Result
76 for _, x := range found {
77 ans = append(ans, x)
78 }
79 return ans, nil
80 }
81
82 func (s *IndexSource) getIndex() (*modindex.Index, error) {
83 s.mu.Lock()
84 defer s.mu.Unlock()
85
86 // (s.index = nil => s.expires is zero,
87 // so the first condition is strictly redundant.
88 // But it makes the postcondition very clear.)
89 if s.index == nil || time.Now().After(s.expires) {
90 index, err := modindex.Update(s.modcachedir)
91 if err != nil {
92 return nil, err
93 }
94 s.index = index
95 s.expires = index.ValidAt.Add(15 * time.Minute) // (refresh period)
96 }
97 // Inv: s.index != nil
98
99 return s.index, nil
100 }