| 1 |
|
| 2 |
|
| 3 |
|
| 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 |
|
| 30 |
var ErrNoModOnDisk = errors.New("go.mod file is not on disk") |
| 31 |
|
| 32 |
|
| 33 |
type TidiedModule struct { |
| 34 |
|
| 35 |
Diagnostics []*Diagnostic |
| 36 |
|
| 37 |
TidiedContent []byte |
| 38 |
} |
| 39 |
|
| 40 |
|
| 41 |
|
| 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 |
|
| 61 |
if !hit { |
| 62 |
|
| 63 |
|
| 64 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 121 |
|
| 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 |
|
| 130 |
|
| 131 |
return nil, err |
| 132 |
} |
| 133 |
|
| 134 |
|
| 135 |
|
| 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 |
|
| 148 |
|
| 149 |
|
| 150 |
func modTidyDiagnostics(ctx context.Context, snapshot *Snapshot, pm *ParsedModule, ideal *modfile.File) (diagnostics []*Diagnostic, err error) { |
| 151 |
|
| 152 |
|
| 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 |
|
| 173 |
|
| 174 |
srcDiag, err := directnessDiagnostic(pm.Mapper, req) |
| 175 |
if err != nil { |
| 176 |
|
| 177 |
|
| 178 |
|
| 179 |
event.Error(ctx, "computing directness diagnostic", err) |
| 180 |
continue |
| 181 |
} |
| 182 |
diagnostics = append(diagnostics, srcDiag) |
| 183 |
} |
| 184 |
|
| 185 |
|
| 186 |
|
| 187 |
|
| 188 |
|
| 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 |
|
| 198 |
|
| 199 |
|
| 200 |
|
| 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 |
|
| 225 |
|
| 226 |
metas, err := snapshot.WorkspaceMetadata(ctx) |
| 227 |
if err != nil { |
| 228 |
return nil, err |
| 229 |
} |
| 230 |
|
| 231 |
for _, mp := range metas { |
| 232 |
|
| 233 |
|
| 234 |
|
| 235 |
|
| 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 |
|
| 248 |
|
| 249 |
|
| 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 |
|
| 260 |
|
| 261 |
|
| 262 |
|
| 263 |
|
| 264 |
|
| 265 |
|
| 266 |
|
| 267 |
|
| 268 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 347 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 417 |
|
| 418 |
func switchDirectness(req *modfile.Require, m *protocol.Mapper) ([]protocol.TextEdit, error) { |
| 419 |
|
| 420 |
|
| 421 |
copied, err := modfile.Parse("", m.Content, nil) |
| 422 |
if err != nil { |
| 423 |
return nil, err |
| 424 |
} |
| 425 |
|
| 426 |
|
| 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 |
|
| 432 |
|
| 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 |
|
| 452 |
edits := diff.Bytes(m.Content, newContent) |
| 453 |
return protocol.EditsFromDiffEdits(m, edits) |
| 454 |
} |
| 455 |
|
| 456 |
|
| 457 |
|
| 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 |
|
| 477 |
|
| 478 |
|
| 479 |
|
| 480 |
|
| 481 |
|
| 482 |
|
| 483 |
|
| 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 { |
| 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 |
} |