Debian Codegraph @

gopls/internal/cache/mod_tidy.go

raw symbols SCIP
1 // Copyright 2020 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 cache
6
7 import (
8 "context"
9 "errors"
10 "fmt"
11 "go/ast"
12 "go/token"
13 "os"
14 "path/filepath"
15 "strconv"
16 "strings"
17
18 "golang.org/x/mod/modfile"
19 "golang.org/x/tools/gopls/internal/cache/parsego"
20 "golang.org/x/tools/gopls/internal/file"
21 "golang.org/x/tools/gopls/internal/label"
22 "golang.org/x/tools/gopls/internal/protocol"
23 "golang.org/x/tools/gopls/internal/protocol/command"
24 "golang.org/x/tools/gopls/internal/util/memoize"
25 "golang.org/x/tools/internal/diff"
26 "golang.org/x/tools/internal/event"
27 )
28
29 // This error is sought by mod diagnostics.
30 var ErrNoModOnDisk = errors.New("go.mod file is not on disk")
31
32 // A TidiedModule contains the results of running `go mod tidy` on a module.
33 type TidiedModule struct {
34 // Diagnostics representing changes made by `go mod tidy`.
35 Diagnostics []*Diagnostic
36 // The bytes of the go.mod file after it was tidied.
37 TidiedContent []byte
38 }
39
40 // ModTidy returns the go.mod file that would be obtained by running
41 // "go mod tidy". Concurrent requests are combined into a single command.
42 func (s *Snapshot) ModTidy(ctx context.Context, pm *ParsedModule) (*TidiedModule, error) {
43 ctx, done := event.Start(ctx, "cache.snapshot.ModTidy")
44 defer done()
45
46 uri := pm.URI
47 if pm.File == nil {
48 return nil, fmt.Errorf("cannot tidy unparsable go.mod file: %v", uri)
49 }
50
51 s.mu.Lock()
52 entry, hit := s.modTidyHandles.Get(uri)
53 s.mu.Unlock()
54
55 type modTidyResult struct {
56 tidied *TidiedModule
57 err error
58 }
59
60 // Cache miss?
61 if !hit {
62 // If the file handle is an overlay, it may not be written to disk.
63 // The go.mod file has to be on disk for `go mod tidy` to work.
64 // TODO(rfindley): is this still true with Go 1.16 overlay support?
65 fh, err := s.ReadFile(ctx, pm.URI)
66 if err != nil {
67 return nil, err
68 }
69 if _, ok := fh.(*overlay); ok {
70 if info, _ := os.Stat(uri.Path()); info == nil {
71 return nil, ErrNoModOnDisk
72 }
73 }
74
75 if err := s.awaitLoaded(ctx); err != nil {
76 return nil, err
77 }
78
79 handle := memoize.NewPromise("modTidy", func(ctx context.Context, arg any) any {
80 tidied, err := modTidyImpl(ctx, arg.(*Snapshot), pm)
81 return modTidyResult{tidied, err}
82 })
83
84 entry = handle
85 s.mu.Lock()
86 s.modTidyHandles.Set(uri, entry, nil)
87 s.mu.Unlock()
88 }
89
90 // Await result.
91 v, err := s.awaitPromise(ctx, entry)
92 if err != nil {
93 return nil, err
94 }
95 res := v.(modTidyResult)
96 return res.tidied, res.err
97 }
98
99 // modTidyImpl runs "go mod tidy" on a go.mod file.
100 func modTidyImpl(ctx context.Context, snapshot *Snapshot, pm *ParsedModule) (*TidiedModule, error) {
101 ctx, done := event.Start(ctx, "cache.ModTidy", label.URI.Of(pm.URI))
102 defer done()
103
104 tempDir, cleanup, err := TempModDir(ctx, snapshot, pm.URI)
105 if err != nil {
106 return nil, err
107 }
108 defer cleanup()
109
110 args := []string{"tidy", "-modfile=" + filepath.Join(tempDir, "go.mod")}
111 inv, cleanupInvocation, err := snapshot.GoCommandInvocation(NoNetwork, pm.URI.DirPath(), "mod", args, "GOWORK=off")
112 if err != nil {
113 return nil, err
114 }
115 defer cleanupInvocation()
116 if _, err := snapshot.view.gocmdRunner.Run(ctx, *inv); err != nil {
117 return nil, err
118 }
119
120 // Go directly to disk to get the temporary mod file,
121 // since it is always on disk.
122 tempMod := filepath.Join(tempDir, "go.mod")
123 tempContents, err := os.ReadFile(tempMod)
124 if err != nil {
125 return nil, err
126 }
127 ideal, err := modfile.Parse(tempMod, tempContents, nil)
128 if err != nil {
129 // We do not need to worry about the temporary file's parse errors
130 // since it has been "tidied".
131 return nil, err
132 }
133
134 // Compare the original and tidied go.mod files to compute errors and
135 // suggested fixes.
136 diagnostics, err := modTidyDiagnostics(ctx, snapshot, pm, ideal)
137 if err != nil {
138 return nil, err
139 }
140
141 return &TidiedModule{
142 Diagnostics: diagnostics,
143 TidiedContent: tempContents,
144 }, nil
145 }
146
147 // modTidyDiagnostics computes the differences between the original and tidied
148 // go.mod files to produce diagnostic and suggested fixes. Some diagnostics
149 // may appear on the Go files that import packages from missing modules.
150 func modTidyDiagnostics(ctx context.Context, snapshot *Snapshot, pm *ParsedModule, ideal *modfile.File) (diagnostics []*Diagnostic, err error) {
151 // First, determine which modules are unused and which are missing from the
152 // original go.mod file.
153 var (
154 unused = make(map[string]*modfile.Require, len(pm.File.Require))
155 missing = make(map[string]*modfile.Require, len(ideal.Require))
156 wrongDirectness = make(map[string]*modfile.Require, len(pm.File.Require))
157 )
158 for _, req := range pm.File.Require {
159 unused[req.Mod.Path] = req
160 }
161 for _, req := range ideal.Require {
162 origReq := unused[req.Mod.Path]
163 if origReq == nil {
164 missing[req.Mod.Path] = req
165 continue
166 } else if origReq.Indirect != req.Indirect {
167 wrongDirectness[req.Mod.Path] = origReq
168 }
169 delete(unused, req.Mod.Path)
170 }
171 for _, req := range wrongDirectness {
172 // Handle dependencies that are incorrectly labeled indirect and
173 // vice versa.
174 srcDiag, err := directnessDiagnostic(pm.Mapper, req)
175 if err != nil {
176 // We're probably in a bad state if we can't compute a
177 // directnessDiagnostic, but try to keep going so as to not suppress
178 // other, valid diagnostics.
179 event.Error(ctx, "computing directness diagnostic", err)
180 continue
181 }
182 diagnostics = append(diagnostics, srcDiag)
183 }
184 // Next, compute any diagnostics for modules that are missing from the
185 // go.mod file. The fixes will be for the go.mod file, but the
186 // diagnostics should also appear in both the go.mod file and the import
187 // statements in the Go files in which the dependencies are used.
188 // Finally, add errors for any unused dependencies.
189 if len(missing) > 0 {
190 missingModuleDiagnostics, err := missingModuleDiagnostics(ctx, snapshot, pm, ideal, missing)
191 if err != nil {
192 return nil, err
193 }
194 diagnostics = append(diagnostics, missingModuleDiagnostics...)
195 }
196
197 // Opt: if this is the only diagnostic, we can avoid textual edits and just
198 // run the Go command.
199 //
200 // See also the documentation for command.RemoveDependencyArgs.OnlyDiagnostic.
201 onlyDiagnostic := len(diagnostics) == 0 && len(unused) == 1
202 for _, req := range unused {
203 srcErr, err := unusedDiagnostic(pm.Mapper, req, onlyDiagnostic)
204 if err != nil {
205 return nil, err
206 }
207 diagnostics = append(diagnostics, srcErr)
208 }
209 return diagnostics, nil
210 }
211
212 func missingModuleDiagnostics(ctx context.Context, snapshot *Snapshot, pm *ParsedModule, ideal *modfile.File, missing map[string]*modfile.Require) ([]*Diagnostic, error) {
213 missingModuleFixes := map[*modfile.Require][]SuggestedFix{}
214 var diagnostics []*Diagnostic
215 for _, req := range missing {
216 srcDiag, err := missingModuleDiagnostic(pm, req)
217 if err != nil {
218 return nil, err
219 }
220 missingModuleFixes[req] = srcDiag.SuggestedFixes
221 diagnostics = append(diagnostics, srcDiag)
222 }
223
224 // Add diagnostics for missing modules anywhere they are imported in the
225 // workspace.
226 metas, err := snapshot.WorkspaceMetadata(ctx)
227 if err != nil {
228 return nil, err
229 }
230 // TODO(adonovan): opt: opportunities for parallelism abound.
231 for _, mp := range metas {
232 // Read both lists of files of this package.
233 //
234 // Parallelism is not necessary here as the files will have already been
235 // pre-read at load time.
236 goFiles, err := readFiles(ctx, snapshot, mp.GoFiles)
237 if err != nil {
238 return nil, err
239 }
240 compiledGoFiles, err := readFiles(ctx, snapshot, mp.CompiledGoFiles)
241 if err != nil {
242 return nil, err
243 }
244
245 missingImports := map[string]*modfile.Require{}
246
247 // If -mod=readonly is not set we may have successfully imported
248 // packages from missing modules. Otherwise they'll be in
249 // MissingDependencies. Combine both.
250 imps, err := parseImports(ctx, snapshot, goFiles)
251 if err != nil {
252 return nil, err
253 }
254 for imp := range imps {
255 if req, ok := missing[imp]; ok {
256 missingImports[imp] = req
257 break
258 }
259 // If the import is a package of the dependency, then add the
260 // package to the map, this will eliminate the need to do this
261 // prefix package search on each import for each file.
262 // Example:
263 //
264 // import (
265 // "golang.org/x/tools/internal/expect"
266 // "golang.org/x/tools/go/packages"
267 // )
268 // They both are related to the same module: "golang.org/x/tools".
269 var match string
270 for _, req := range ideal.Require {
271 if strings.HasPrefix(imp, req.Mod.Path) && len(req.Mod.Path) > len(match) {
272 match = req.Mod.Path
273 }
274 }
275 if req, ok := missing[match]; ok {
276 missingImports[imp] = req
277 }
278 }
279 // None of this package's imports are from missing modules.
280 if len(missingImports) == 0 {
281 continue
282 }
283 for _, goFile := range compiledGoFiles {
284 pgf, err := snapshot.ParseGo(ctx, goFile, parsego.Header)
285 if err != nil {
286 continue
287 }
288 file, m := pgf.File, pgf.Mapper
289 if file == nil || m == nil {
290 continue
291 }
292 imports := make(map[string]*ast.ImportSpec)
293 for _, imp := range file.Imports {
294 if imp.Path == nil {
295 continue
296 }
297 if target, err := strconv.Unquote(imp.Path.Value); err == nil {
298 imports[target] = imp
299 }
300 }
301 if len(imports) == 0 {
302 continue
303 }
304 for importPath, req := range missingImports {
305 imp, ok := imports[importPath]
306 if !ok {
307 continue
308 }
309 fixes, ok := missingModuleFixes[req]
310 if !ok {
311 return nil, fmt.Errorf("no missing module fix for %q (%q)", importPath, req.Mod.Path)
312 }
313 srcErr, err := missingModuleForImport(pgf, imp, req, fixes)
314 if err != nil {
315 return nil, err
316 }
317 diagnostics = append(diagnostics, srcErr)
318 }
319 }
320 }
321 return diagnostics, nil
322 }
323
324 // unusedDiagnostic returns a Diagnostic for an unused require.
325 func unusedDiagnostic(m *protocol.Mapper, req *modfile.Require, onlyDiagnostic bool) (*Diagnostic, error) {
326 rng, err := m.OffsetRange(req.Syntax.Start.Byte, req.Syntax.End.Byte)
327 if err != nil {
328 return nil, err
329 }
330 title := fmt.Sprintf("Remove dependency: %s", req.Mod.Path)
331 cmd := command.NewRemoveDependencyCommand(title, command.RemoveDependencyArgs{
332 URI: m.URI,
333 OnlyDiagnostic: onlyDiagnostic,
334 ModulePath: req.Mod.Path,
335 })
336 return &Diagnostic{
337 URI: m.URI,
338 Range: rng,
339 Severity: protocol.SeverityWarning,
340 Source: ModTidyError,
341 Message: fmt.Sprintf("%s is not used in this module", req.Mod.Path),
342 SuggestedFixes: []SuggestedFix{SuggestedFixFromCommand(cmd, protocol.QuickFix)},
343 }, nil
344 }
345
346 // directnessDiagnostic extracts errors when a dependency is labeled indirect when
347 // it should be direct and vice versa.
348 func directnessDiagnostic(m *protocol.Mapper, req *modfile.Require) (*Diagnostic, error) {
349 rng, err := m.OffsetRange(req.Syntax.Start.Byte, req.Syntax.End.Byte)
350 if err != nil {
351 return nil, err
352 }
353 direction := "indirect"
354 if req.Indirect {
355 direction = "direct"
356
357 // If the dependency should be direct, just highlight the // indirect.
358 if comments := req.Syntax.Comment(); comments != nil && len(comments.Suffix) > 0 {
359 end := comments.Suffix[0].Start
360 end.LineRune += len(comments.Suffix[0].Token)
361 end.Byte += len(comments.Suffix[0].Token)
362 rng, err = m.OffsetRange(comments.Suffix[0].Start.Byte, end.Byte)
363 if err != nil {
364 return nil, err
365 }
366 }
367 }
368 // If the dependency should be indirect, add the // indirect.
369 edits, err := switchDirectness(req, m)
370 if err != nil {
371 return nil, err
372 }
373 return &Diagnostic{
374 URI: m.URI,
375 Range: rng,
376 Severity: protocol.SeverityWarning,
377 Source: ModTidyError,
378 Message: fmt.Sprintf("%s should be %s", req.Mod.Path, direction),
379 SuggestedFixes: []SuggestedFix{{
380 Title: fmt.Sprintf("Change %s to %s", req.Mod.Path, direction),
381 Edits: map[protocol.DocumentURI][]protocol.TextEdit{
382 m.URI: edits,
383 },
384 ActionKind: protocol.QuickFix,
385 }},
386 }, nil
387 }
388
389 func missingModuleDiagnostic(pm *ParsedModule, req *modfile.Require) (*Diagnostic, error) {
390 var rng protocol.Range
391 // Default to the start of the file if there is no module declaration.
392 if pm.File != nil && pm.File.Module != nil && pm.File.Module.Syntax != nil {
393 start, end := pm.File.Module.Syntax.Span()
394 var err error
395 rng, err = pm.Mapper.OffsetRange(start.Byte, end.Byte)
396 if err != nil {
397 return nil, err
398 }
399 }
400 title := fmt.Sprintf("Add %s to your go.mod file", req.Mod.Path)
401 cmd := command.NewAddDependencyCommand(title, command.DependencyArgs{
402 URI: pm.Mapper.URI,
403 AddRequire: !req.Indirect,
404 GoCmdArgs: []string{req.Mod.Path + "@" + req.Mod.Version},
405 })
406 return &Diagnostic{
407 URI: pm.Mapper.URI,
408 Range: rng,
409 Severity: protocol.SeverityError,
410 Source: ModTidyError,
411 Message: fmt.Sprintf("%s is not in your go.mod file", req.Mod.Path),
412 SuggestedFixes: []SuggestedFix{SuggestedFixFromCommand(cmd, protocol.QuickFix)},
413 }, nil
414 }
415
416 // switchDirectness gets the edits needed to change an indirect dependency to
417 // direct and vice versa.
418 func switchDirectness(req *modfile.Require, m *protocol.Mapper) ([]protocol.TextEdit, error) {
419 // We need a private copy of the parsed go.mod file, since we're going to
420 // modify it.
421 copied, err := modfile.Parse("", m.Content, nil)
422 if err != nil {
423 return nil, err
424 }
425 // Change the directness in the matching require statement. To avoid
426 // reordering the require statements, rewrite all of them.
427 var requires []*modfile.Require
428 seenVersions := make(map[string]string)
429 for _, r := range copied.Require {
430 if seen := seenVersions[r.Mod.Path]; seen != "" && seen != r.Mod.Version {
431 // Avoid a panic in SetRequire below, which panics on conflicting
432 // versions.
433 return nil, fmt.Errorf("%q has conflicting versions: %q and %q", r.Mod.Path, seen, r.Mod.Version)
434 }
435 seenVersions[r.Mod.Path] = r.Mod.Version
436 if r.Mod.Path == req.Mod.Path {
437 requires = append(requires, &modfile.Require{
438 Mod: r.Mod,
439 Syntax: r.Syntax,
440 Indirect: !r.Indirect,
441 })
442 continue
443 }
444 requires = append(requires, r)
445 }
446 copied.SetRequire(requires)
447 newContent, err := copied.Format()
448 if err != nil {
449 return nil, err
450 }
451 // Calculate the edits to be made due to the change.
452 edits := diff.Bytes(m.Content, newContent)
453 return protocol.EditsFromDiffEdits(m, edits)
454 }
455
456 // missingModuleForImport creates an error for a given import path that comes
457 // from a missing module.
458 func missingModuleForImport(pgf *parsego.File, imp *ast.ImportSpec, req *modfile.Require, fixes []SuggestedFix) (*Diagnostic, error) {
459 if req.Syntax == nil {
460 return nil, fmt.Errorf("no syntax for %v", req)
461 }
462 rng, err := pgf.NodeRange(imp.Path)
463 if err != nil {
464 return nil, err
465 }
466 return &Diagnostic{
467 URI: pgf.URI,
468 Range: rng,
469 Severity: protocol.SeverityError,
470 Source: ModTidyError,
471 Message: fmt.Sprintf("%s is not in your go.mod file", req.Mod.Path),
472 SuggestedFixes: fixes,
473 }, nil
474 }
475
476 // parseImports parses the headers of the specified files and returns
477 // the set of strings that appear in import declarations within
478 // GoFiles. Errors are ignored.
479 //
480 // (We can't simply use Metadata.Imports because it is based on
481 // CompiledGoFiles, after cgo processing.)
482 //
483 // TODO(rfindley): this should key off ImportPath.
484 func parseImports(ctx context.Context, s *Snapshot, files []file.Handle) (map[string]bool, error) {
485 pgfs, err := s.view.parseCache.parseFiles(ctx, token.NewFileSet(), parsego.Header, false, files...)
486 if err != nil { // e.g. context cancellation
487 return nil, err
488 }
489
490 seen := make(map[string]bool)
491 for _, pgf := range pgfs {
492 for _, spec := range pgf.File.Imports {
493 path, _ := strconv.Unquote(spec.Path.Value)
494 seen[path] = true
495 }
496 }
497 return seen, nil
498 }