| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package server |
| 6 |
|
| 7 |
import ( |
| 8 |
"bytes" |
| 9 |
"context" |
| 10 |
"encoding/json" |
| 11 |
"errors" |
| 12 |
"fmt" |
| 13 |
"io" |
| 14 |
"log" |
| 15 |
"maps" |
| 16 |
"os" |
| 17 |
"path/filepath" |
| 18 |
"regexp" |
| 19 |
"runtime" |
| 20 |
"runtime/pprof" |
| 21 |
"slices" |
| 22 |
"sort" |
| 23 |
"strings" |
| 24 |
"sync" |
| 25 |
|
| 26 |
"github.com/fatih/gomodifytags/modifytags" |
| 27 |
"golang.org/x/mod/modfile" |
| 28 |
"golang.org/x/telemetry/counter" |
| 29 |
"golang.org/x/tools/go/ast/astutil" |
| 30 |
"golang.org/x/tools/gopls/internal/cache" |
| 31 |
"golang.org/x/tools/gopls/internal/cache/metadata" |
| 32 |
"golang.org/x/tools/gopls/internal/cache/parsego" |
| 33 |
"golang.org/x/tools/gopls/internal/debug" |
| 34 |
"golang.org/x/tools/gopls/internal/file" |
| 35 |
"golang.org/x/tools/gopls/internal/golang" |
| 36 |
"golang.org/x/tools/gopls/internal/progress" |
| 37 |
"golang.org/x/tools/gopls/internal/protocol" |
| 38 |
"golang.org/x/tools/gopls/internal/protocol/command" |
| 39 |
"golang.org/x/tools/gopls/internal/settings" |
| 40 |
"golang.org/x/tools/gopls/internal/util/bug" |
| 41 |
"golang.org/x/tools/gopls/internal/util/tokeninternal" |
| 42 |
"golang.org/x/tools/gopls/internal/vulncheck" |
| 43 |
"golang.org/x/tools/gopls/internal/vulncheck/scan" |
| 44 |
"golang.org/x/tools/internal/diff" |
| 45 |
"golang.org/x/tools/internal/event" |
| 46 |
"golang.org/x/tools/internal/gocommand" |
| 47 |
"golang.org/x/tools/internal/jsonrpc2" |
| 48 |
) |
| 49 |
|
| 50 |
func (s *server) ExecuteCommand(ctx context.Context, params *protocol.ExecuteCommandParams) (any, error) { |
| 51 |
ctx, done := event.Start(ctx, "server.ExecuteCommand") |
| 52 |
defer done() |
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
if s.Options().VerboseWorkDoneProgress { |
| 59 |
work := s.progress.Start(ctx, params.Command, "Verbose: running command...", nil, nil) |
| 60 |
defer work.End(ctx, "Done.") |
| 61 |
} |
| 62 |
|
| 63 |
if !slices.Contains(s.Options().SupportedCommands, params.Command) { |
| 64 |
return nil, fmt.Errorf("%s is not a supported command", params.Command) |
| 65 |
} |
| 66 |
|
| 67 |
if len(params.Arguments) > 0 { |
| 68 |
last := params.Arguments[len(params.Arguments)-1] |
| 69 |
var meta struct { |
| 70 |
Source string `json:"source"` |
| 71 |
} |
| 72 |
if err := json.Unmarshal(last, &meta); err == nil && meta.Source != "" { |
| 73 |
commandName := strings.TrimPrefix(params.Command, "gopls.") |
| 74 |
counterName := fmt.Sprintf("gopls/cmd/source:%s-%s", commandName, meta.Source) |
| 75 |
counter.New(counterName).Inc() |
| 76 |
params.Arguments = params.Arguments[:len(params.Arguments)-1] |
| 77 |
} |
| 78 |
} |
| 79 |
|
| 80 |
if len(params.FormAnswers) != 0 { |
| 81 |
commandName := strings.TrimPrefix(params.Command, "gopls.") |
| 82 |
counterName := fmt.Sprintf("gopls/interactive/command:%s", commandName) |
| 83 |
counter.New(counterName).Inc() |
| 84 |
} |
| 85 |
|
| 86 |
handler := &commandHandler{ |
| 87 |
s: s, |
| 88 |
params: params, |
| 89 |
} |
| 90 |
return command.Dispatch(ctx, params, handler) |
| 91 |
} |
| 92 |
|
| 93 |
type commandHandler struct { |
| 94 |
s *server |
| 95 |
params *protocol.ExecuteCommandParams |
| 96 |
} |
| 97 |
|
| 98 |
func (h *commandHandler) Modules(ctx context.Context, args command.ModulesArgs) (command.ModulesResult, error) { |
| 99 |
|
| 100 |
keepModule := func(goMod protocol.DocumentURI) bool { |
| 101 |
|
| 102 |
if !args.Dir.Encloses(goMod) { |
| 103 |
return false |
| 104 |
} |
| 105 |
|
| 106 |
|
| 107 |
rel, err := filepath.Rel(args.Dir.Path(), goMod.Path()) |
| 108 |
if err != nil { |
| 109 |
return false |
| 110 |
} |
| 111 |
|
| 112 |
assert(goMod.Base() == "go.mod", fmt.Sprintf("invalid go.mod path: want go.mod, got %q", goMod.Path())) |
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
nparts := strings.Count(rel, string(filepath.Separator)) |
| 117 |
return args.MaxDepth < 0 || nparts <= args.MaxDepth |
| 118 |
} |
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
|
| 125 |
|
| 126 |
|
| 127 |
|
| 128 |
|
| 129 |
var result command.ModulesResult |
| 130 |
seen := map[protocol.DocumentURI]bool{} |
| 131 |
for _, v := range h.s.session.Views() { |
| 132 |
s, release, err := v.Snapshot() |
| 133 |
if err != nil { |
| 134 |
return command.ModulesResult{}, err |
| 135 |
} |
| 136 |
defer release() |
| 137 |
|
| 138 |
for _, modFile := range v.ModFiles() { |
| 139 |
if !keepModule(modFile) { |
| 140 |
continue |
| 141 |
} |
| 142 |
|
| 143 |
|
| 144 |
if seen[modFile] { |
| 145 |
continue |
| 146 |
} |
| 147 |
seen[modFile] = true |
| 148 |
|
| 149 |
fh, err := s.ReadFile(ctx, modFile) |
| 150 |
if err != nil { |
| 151 |
return command.ModulesResult{}, err |
| 152 |
} |
| 153 |
mod, err := s.ParseMod(ctx, fh) |
| 154 |
if err != nil { |
| 155 |
return command.ModulesResult{}, err |
| 156 |
} |
| 157 |
if mod.File.Module == nil { |
| 158 |
continue |
| 159 |
} |
| 160 |
result.Modules = append(result.Modules, command.Module{ |
| 161 |
Path: mod.File.Module.Mod.Path, |
| 162 |
Version: mod.File.Module.Mod.Version, |
| 163 |
GoMod: mod.URI, |
| 164 |
}) |
| 165 |
} |
| 166 |
} |
| 167 |
return result, nil |
| 168 |
} |
| 169 |
|
| 170 |
func (h *commandHandler) Packages(ctx context.Context, args command.PackagesArgs) (command.PackagesResult, error) { |
| 171 |
|
| 172 |
dirs := make([]protocol.DocumentURI, len(args.Files)) |
| 173 |
for i, file := range args.Files { |
| 174 |
if filepath.Ext(file.Path()) == ".go" { |
| 175 |
dirs[i] = file.Dir() |
| 176 |
} else { |
| 177 |
dirs[i] = file |
| 178 |
} |
| 179 |
} |
| 180 |
|
| 181 |
keepPackage := func(pkg *metadata.Package) bool { |
| 182 |
for _, file := range pkg.GoFiles { |
| 183 |
for _, dir := range dirs { |
| 184 |
if file.Dir() == dir || args.Recursive && dir.Encloses(file) { |
| 185 |
return true |
| 186 |
} |
| 187 |
} |
| 188 |
} |
| 189 |
return false |
| 190 |
} |
| 191 |
|
| 192 |
result := command.PackagesResult{ |
| 193 |
Module: make(map[string]command.Module), |
| 194 |
} |
| 195 |
|
| 196 |
err := h.run(ctx, commandConfig{ |
| 197 |
progress: "Packages", |
| 198 |
}, func(ctx context.Context, _ commandDeps) error { |
| 199 |
for _, view := range h.s.session.Views() { |
| 200 |
snapshot, release, err := view.Snapshot() |
| 201 |
if err != nil { |
| 202 |
return err |
| 203 |
} |
| 204 |
defer release() |
| 205 |
|
| 206 |
metas, err := snapshot.WorkspaceMetadata(ctx) |
| 207 |
if err != nil { |
| 208 |
return err |
| 209 |
} |
| 210 |
|
| 211 |
|
| 212 |
metas = slices.DeleteFunc(metas, func(meta *metadata.Package) bool { |
| 213 |
return meta.IsIntermediateTestVariant() || |
| 214 |
!keepPackage(meta) |
| 215 |
}) |
| 216 |
|
| 217 |
start := len(result.Packages) |
| 218 |
for _, meta := range metas { |
| 219 |
var mod command.Module |
| 220 |
if meta.Module != nil { |
| 221 |
mod = command.Module{ |
| 222 |
Path: meta.Module.Path, |
| 223 |
Version: meta.Module.Version, |
| 224 |
GoMod: protocol.URIFromPath(meta.Module.GoMod), |
| 225 |
} |
| 226 |
result.Module[mod.Path] = mod |
| 227 |
} |
| 228 |
|
| 229 |
result.Packages = append(result.Packages, command.Package{ |
| 230 |
Path: string(meta.PkgPath), |
| 231 |
ForTest: string(meta.ForTest), |
| 232 |
ModulePath: mod.Path, |
| 233 |
}) |
| 234 |
} |
| 235 |
|
| 236 |
if args.Mode&command.NeedTests == 0 { |
| 237 |
continue |
| 238 |
} |
| 239 |
|
| 240 |
|
| 241 |
|
| 242 |
var ids []cache.PackageID |
| 243 |
for _, meta := range metas { |
| 244 |
ids = append(ids, meta.ID) |
| 245 |
} |
| 246 |
|
| 247 |
allTests, err := snapshot.Tests(ctx, ids...) |
| 248 |
if err != nil { |
| 249 |
return err |
| 250 |
} |
| 251 |
|
| 252 |
for i, tests := range allTests { |
| 253 |
pkg := &result.Packages[start+i] |
| 254 |
fileByPath := map[protocol.DocumentURI]*command.TestFile{} |
| 255 |
for _, test := range tests.All() { |
| 256 |
test := command.TestCase{ |
| 257 |
Name: test.Name, |
| 258 |
Loc: test.Location, |
| 259 |
} |
| 260 |
|
| 261 |
file, ok := fileByPath[test.Loc.URI] |
| 262 |
if !ok { |
| 263 |
f := command.TestFile{ |
| 264 |
URI: test.Loc.URI, |
| 265 |
} |
| 266 |
i := len(pkg.TestFiles) |
| 267 |
pkg.TestFiles = append(pkg.TestFiles, f) |
| 268 |
file = &pkg.TestFiles[i] |
| 269 |
fileByPath[test.Loc.URI] = file |
| 270 |
} |
| 271 |
file.Tests = append(file.Tests, test) |
| 272 |
} |
| 273 |
} |
| 274 |
} |
| 275 |
|
| 276 |
return nil |
| 277 |
}) |
| 278 |
return result, err |
| 279 |
} |
| 280 |
|
| 281 |
func (h *commandHandler) MaybePromptForTelemetry(ctx context.Context) error { |
| 282 |
|
| 283 |
|
| 284 |
if !h.s.options.TelemetryPrompt { |
| 285 |
go h.s.maybePromptForTelemetry(ctx, true) |
| 286 |
} |
| 287 |
return nil |
| 288 |
} |
| 289 |
|
| 290 |
func (*commandHandler) AddTelemetryCounters(_ context.Context, args command.AddTelemetryCountersArgs) error { |
| 291 |
if len(args.Names) != len(args.Values) { |
| 292 |
return fmt.Errorf("Names and Values must have the same length") |
| 293 |
} |
| 294 |
|
| 295 |
for i, n := range args.Names { |
| 296 |
v := args.Values[i] |
| 297 |
if n == "" || v < 0 { |
| 298 |
continue |
| 299 |
} |
| 300 |
counter.Add("fwd/"+n, v) |
| 301 |
} |
| 302 |
return nil |
| 303 |
} |
| 304 |
|
| 305 |
func (c *commandHandler) AddTest(ctx context.Context, loc protocol.Location) (*protocol.WorkspaceEdit, error) { |
| 306 |
var result *protocol.WorkspaceEdit |
| 307 |
err := c.run(ctx, commandConfig{ |
| 308 |
forURI: loc.URI, |
| 309 |
}, func(ctx context.Context, deps commandDeps) error { |
| 310 |
if deps.snapshot.FileKind(deps.fh) != file.Go { |
| 311 |
return fmt.Errorf("can't add test for non-Go file") |
| 312 |
} |
| 313 |
docedits, show, err := golang.AddTestForFunc(ctx, deps.snapshot, loc) |
| 314 |
if err != nil { |
| 315 |
return err |
| 316 |
} |
| 317 |
if err := applyChanges(ctx, c.s.client, docedits); err != nil { |
| 318 |
return err |
| 319 |
} |
| 320 |
|
| 321 |
if show != nil { |
| 322 |
showDocumentImpl(ctx, c.s.client, protocol.URI(show.URI), &show.Range, c.s.options) |
| 323 |
} |
| 324 |
return nil |
| 325 |
}) |
| 326 |
return result, err |
| 327 |
} |
| 328 |
|
| 329 |
func (c *commandHandler) LSP(ctx context.Context, param command.LSPArgs) (any, error) { |
| 330 |
response, valid, err := protocol.ServerDispatchCall(ctx, c.s, param.Method, param.Param) |
| 331 |
if !valid { |
| 332 |
return nil, fmt.Errorf("method %s does not exist", param.Method) |
| 333 |
} |
| 334 |
|
| 335 |
return response, err |
| 336 |
} |
| 337 |
|
| 338 |
|
| 339 |
type commandConfig struct { |
| 340 |
requireSave bool |
| 341 |
progress string |
| 342 |
progressStyle settings.WorkDoneProgressStyle |
| 343 |
forView string |
| 344 |
forURI protocol.DocumentURI |
| 345 |
} |
| 346 |
|
| 347 |
|
| 348 |
|
| 349 |
|
| 350 |
type commandDeps struct { |
| 351 |
snapshot *cache.Snapshot |
| 352 |
fh file.Handle |
| 353 |
work *progress.WorkDone |
| 354 |
} |
| 355 |
|
| 356 |
type commandFunc func(context.Context, commandDeps) error |
| 357 |
|
| 358 |
|
| 359 |
|
| 360 |
const ( |
| 361 |
CommandCanceled = "canceled" |
| 362 |
CommandFailed = "failed" |
| 363 |
CommandCompleted = "completed" |
| 364 |
) |
| 365 |
|
| 366 |
|
| 367 |
|
| 368 |
|
| 369 |
|
| 370 |
|
| 371 |
|
| 372 |
|
| 373 |
func (c *commandHandler) run(ctx context.Context, cfg commandConfig, run commandFunc) (err error) { |
| 374 |
if cfg.requireSave { |
| 375 |
var unsaved []string |
| 376 |
for _, overlay := range c.s.session.Overlays() { |
| 377 |
if !overlay.SameContentsOnDisk() { |
| 378 |
unsaved = append(unsaved, overlay.URI().Path()) |
| 379 |
} |
| 380 |
} |
| 381 |
if len(unsaved) > 0 { |
| 382 |
return fmt.Errorf("All files must be saved first (unsaved: %v).", unsaved) |
| 383 |
} |
| 384 |
} |
| 385 |
var deps commandDeps |
| 386 |
var release func() |
| 387 |
if cfg.forURI != "" && cfg.forView != "" { |
| 388 |
return bug.Errorf("internal error: forURI=%q, forView=%q", cfg.forURI, cfg.forView) |
| 389 |
} |
| 390 |
if cfg.forURI != "" { |
| 391 |
deps.fh, deps.snapshot, release, err = c.s.session.FileOf(ctx, cfg.forURI) |
| 392 |
if err != nil { |
| 393 |
return err |
| 394 |
} |
| 395 |
|
| 396 |
} else if cfg.forView != "" { |
| 397 |
view, err := c.s.session.View(cfg.forView) |
| 398 |
if err != nil { |
| 399 |
return err |
| 400 |
} |
| 401 |
deps.snapshot, release, err = view.Snapshot() |
| 402 |
if err != nil { |
| 403 |
return err |
| 404 |
} |
| 405 |
|
| 406 |
} else { |
| 407 |
release = func() {} |
| 408 |
} |
| 409 |
|
| 410 |
|
| 411 |
|
| 412 |
ctx, cancel := context.WithCancel(context.WithoutCancel(ctx)) |
| 413 |
if cfg.progress != "" { |
| 414 |
header := "" |
| 415 |
if _, ok := c.s.options.SupportedWorkDoneProgressFormats[cfg.progressStyle]; ok && cfg.progressStyle != "" { |
| 416 |
header = fmt.Sprintf("style: %s\n\n", cfg.progressStyle) |
| 417 |
} |
| 418 |
deps.work = c.s.progress.Start(ctx, cfg.progress, header+"Running...", c.params.WorkDoneToken, cancel) |
| 419 |
} |
| 420 |
runcmd := func() error { |
| 421 |
defer release() |
| 422 |
defer cancel() |
| 423 |
err := run(ctx, deps) |
| 424 |
if deps.work != nil { |
| 425 |
switch { |
| 426 |
case errors.Is(err, context.Canceled): |
| 427 |
deps.work.End(ctx, CommandCanceled) |
| 428 |
case err != nil: |
| 429 |
event.Error(ctx, "command error", err) |
| 430 |
deps.work.End(ctx, CommandFailed) |
| 431 |
default: |
| 432 |
deps.work.End(ctx, CommandCompleted) |
| 433 |
} |
| 434 |
} |
| 435 |
return err |
| 436 |
} |
| 437 |
|
| 438 |
|
| 439 |
|
| 440 |
|
| 441 |
|
| 442 |
if c.params.Command == "gopls.run_govulncheck" { |
| 443 |
if cfg.progress == "" { |
| 444 |
log.Fatalf("asynchronous command gopls.run_govulncheck does not enable progress reporting") |
| 445 |
} |
| 446 |
go func() { |
| 447 |
if err := runcmd(); err != nil { |
| 448 |
showMessage(ctx, c.s.client, protocol.Error, err.Error()) |
| 449 |
} |
| 450 |
}() |
| 451 |
return nil |
| 452 |
} |
| 453 |
|
| 454 |
return runcmd() |
| 455 |
} |
| 456 |
|
| 457 |
func (c *commandHandler) ApplyFix(ctx context.Context, args command.ApplyFixArgs) (*protocol.WorkspaceEdit, error) { |
| 458 |
var result *protocol.WorkspaceEdit |
| 459 |
err := c.run(ctx, commandConfig{ |
| 460 |
|
| 461 |
forURI: args.Location.URI, |
| 462 |
}, func(ctx context.Context, deps commandDeps) error { |
| 463 |
changes, err := golang.ApplyFix(ctx, args.Fix, deps.snapshot, deps.fh, args.Location.Range) |
| 464 |
if err != nil { |
| 465 |
return err |
| 466 |
} |
| 467 |
wsedit := protocol.NewWorkspaceEdit(changes...) |
| 468 |
if args.ResolveEdits { |
| 469 |
result = wsedit |
| 470 |
return nil |
| 471 |
} |
| 472 |
return applyChanges(ctx, c.s.client, changes) |
| 473 |
}) |
| 474 |
return result, err |
| 475 |
} |
| 476 |
|
| 477 |
func (c *commandHandler) RegenerateCgo(ctx context.Context, args command.URIArg) error { |
| 478 |
return c.run(ctx, commandConfig{ |
| 479 |
progress: "Regenerating Cgo", |
| 480 |
}, func(ctx context.Context, _ commandDeps) error { |
| 481 |
return c.modifyState(ctx, FromRegenerateCgo, func() (*cache.Snapshot, func(), error) { |
| 482 |
|
| 483 |
v, err := c.s.session.ResetView(ctx, args.URI) |
| 484 |
if err != nil { |
| 485 |
return nil, nil, err |
| 486 |
} |
| 487 |
return v.Snapshot() |
| 488 |
}) |
| 489 |
}) |
| 490 |
} |
| 491 |
|
| 492 |
|
| 493 |
|
| 494 |
|
| 495 |
func (c *commandHandler) modifyState(ctx context.Context, source ModificationSource, work func() (*cache.Snapshot, func(), error)) error { |
| 496 |
var wg sync.WaitGroup |
| 497 |
wg.Add(1) |
| 498 |
defer wg.Done() |
| 499 |
|
| 500 |
|
| 501 |
if c.s.Options().VerboseWorkDoneProgress { |
| 502 |
work := c.s.progress.Start(ctx, DiagnosticWorkTitle(source), "Calculating file diagnostics...", nil, nil) |
| 503 |
go func() { |
| 504 |
wg.Wait() |
| 505 |
work.End(ctx, "Done.") |
| 506 |
}() |
| 507 |
} |
| 508 |
snapshot, release, err := work() |
| 509 |
if err != nil { |
| 510 |
return err |
| 511 |
} |
| 512 |
wg.Go(func() { |
| 513 |
|
| 514 |
|
| 515 |
c.s.diagnoseSnapshot(snapshot.BackgroundContext(), snapshot, nil, 0) |
| 516 |
release() |
| 517 |
}) |
| 518 |
return nil |
| 519 |
} |
| 520 |
|
| 521 |
func (c *commandHandler) CheckUpgrades(ctx context.Context, args command.CheckUpgradesArgs) error { |
| 522 |
return c.run(ctx, commandConfig{ |
| 523 |
forURI: args.URI, |
| 524 |
progress: "Checking for upgrades", |
| 525 |
}, func(ctx context.Context, deps commandDeps) error { |
| 526 |
return c.modifyState(ctx, FromCheckUpgrades, func() (*cache.Snapshot, func(), error) { |
| 527 |
upgrades, err := c.s.getUpgrades(ctx, deps.snapshot, args.URI, args.Modules) |
| 528 |
if err != nil { |
| 529 |
return nil, nil, err |
| 530 |
} |
| 531 |
return c.s.session.InvalidateView(ctx, deps.snapshot.View(), cache.StateChange{ |
| 532 |
ModuleUpgrades: map[protocol.DocumentURI]map[string]string{args.URI: upgrades}, |
| 533 |
}) |
| 534 |
}) |
| 535 |
}) |
| 536 |
} |
| 537 |
|
| 538 |
func (c *commandHandler) AddDependency(ctx context.Context, args command.DependencyArgs) error { |
| 539 |
return c.GoGetModule(ctx, args) |
| 540 |
} |
| 541 |
|
| 542 |
func (c *commandHandler) UpgradeDependency(ctx context.Context, args command.DependencyArgs) error { |
| 543 |
return c.GoGetModule(ctx, args) |
| 544 |
} |
| 545 |
|
| 546 |
func (c *commandHandler) ResetGoModDiagnostics(ctx context.Context, args command.ResetGoModDiagnosticsArgs) error { |
| 547 |
return c.run(ctx, commandConfig{ |
| 548 |
forURI: args.URI, |
| 549 |
}, func(ctx context.Context, deps commandDeps) error { |
| 550 |
return c.modifyState(ctx, FromResetGoModDiagnostics, func() (*cache.Snapshot, func(), error) { |
| 551 |
return c.s.session.InvalidateView(ctx, deps.snapshot.View(), cache.StateChange{ |
| 552 |
ModuleUpgrades: map[protocol.DocumentURI]map[string]string{ |
| 553 |
deps.fh.URI(): nil, |
| 554 |
}, |
| 555 |
Vulns: map[protocol.DocumentURI]*vulncheck.Result{ |
| 556 |
deps.fh.URI(): nil, |
| 557 |
}, |
| 558 |
}) |
| 559 |
}) |
| 560 |
}) |
| 561 |
} |
| 562 |
|
| 563 |
func (c *commandHandler) GoGetModule(ctx context.Context, args command.DependencyArgs) error { |
| 564 |
return c.run(ctx, commandConfig{ |
| 565 |
progress: "Running go get", |
| 566 |
forURI: args.URI, |
| 567 |
}, func(ctx context.Context, deps commandDeps) error { |
| 568 |
return c.s.runGoModUpdateCommands(ctx, deps.snapshot, args.URI, func(invoke func(...string) (*bytes.Buffer, error)) error { |
| 569 |
return runGoGetModule(invoke, args.AddRequire, args.GoCmdArgs) |
| 570 |
}) |
| 571 |
}) |
| 572 |
} |
| 573 |
|
| 574 |
|
| 575 |
func (c *commandHandler) UpdateGoSum(ctx context.Context, args command.URIArgs) error { |
| 576 |
return c.run(ctx, commandConfig{ |
| 577 |
progress: "Updating go.sum", |
| 578 |
}, func(ctx context.Context, _ commandDeps) error { |
| 579 |
for _, uri := range args.URIs { |
| 580 |
fh, snapshot, release, err := c.s.session.FileOf(ctx, uri) |
| 581 |
if err != nil { |
| 582 |
return err |
| 583 |
} |
| 584 |
defer release() |
| 585 |
if err := c.s.runGoModUpdateCommands(ctx, snapshot, fh.URI(), func(invoke func(...string) (*bytes.Buffer, error)) error { |
| 586 |
_, err := invoke("list", "all") |
| 587 |
return err |
| 588 |
}); err != nil { |
| 589 |
return err |
| 590 |
} |
| 591 |
} |
| 592 |
return nil |
| 593 |
}) |
| 594 |
} |
| 595 |
|
| 596 |
func (c *commandHandler) Tidy(ctx context.Context, args command.URIArgs) error { |
| 597 |
return c.run(ctx, commandConfig{ |
| 598 |
progress: "Running go mod tidy", |
| 599 |
}, func(ctx context.Context, _ commandDeps) error { |
| 600 |
for _, uri := range args.URIs { |
| 601 |
fh, snapshot, release, err := c.s.session.FileOf(ctx, uri) |
| 602 |
if err != nil { |
| 603 |
return err |
| 604 |
} |
| 605 |
defer release() |
| 606 |
if err := c.s.runGoModUpdateCommands(ctx, snapshot, fh.URI(), func(invoke func(...string) (*bytes.Buffer, error)) error { |
| 607 |
_, err := invoke("mod", "tidy") |
| 608 |
return err |
| 609 |
}); err != nil { |
| 610 |
return err |
| 611 |
} |
| 612 |
} |
| 613 |
return nil |
| 614 |
}) |
| 615 |
} |
| 616 |
|
| 617 |
func (c *commandHandler) Vendor(ctx context.Context, args command.URIArg) error { |
| 618 |
return c.run(ctx, commandConfig{ |
| 619 |
requireSave: true, |
| 620 |
progress: "Running go mod vendor", |
| 621 |
forURI: args.URI, |
| 622 |
}, func(ctx context.Context, deps commandDeps) error { |
| 623 |
|
| 624 |
|
| 625 |
|
| 626 |
|
| 627 |
|
| 628 |
|
| 629 |
|
| 630 |
|
| 631 |
stderr := new(bytes.Buffer) |
| 632 |
inv, cleanupInvocation, err := deps.snapshot.GoCommandInvocation(cache.NetworkOK, args.URI.DirPath(), "mod", []string{"vendor"}) |
| 633 |
if err != nil { |
| 634 |
return err |
| 635 |
} |
| 636 |
defer cleanupInvocation() |
| 637 |
err = deps.snapshot.View().GoCommandRunner().RunPiped(ctx, *inv, &bytes.Buffer{}, stderr) |
| 638 |
if err != nil { |
| 639 |
return fmt.Errorf("running go mod vendor failed: %v\nstderr:\n%s", err, stderr.String()) |
| 640 |
} |
| 641 |
return nil |
| 642 |
}) |
| 643 |
} |
| 644 |
|
| 645 |
func (c *commandHandler) EditGoDirective(ctx context.Context, args command.EditGoDirectiveArgs) error { |
| 646 |
return c.run(ctx, commandConfig{ |
| 647 |
requireSave: true, |
| 648 |
forURI: args.URI, |
| 649 |
}, func(ctx context.Context, _ commandDeps) error { |
| 650 |
fh, snapshot, release, err := c.s.session.FileOf(ctx, args.URI) |
| 651 |
if err != nil { |
| 652 |
return err |
| 653 |
} |
| 654 |
defer release() |
| 655 |
if err := c.s.runGoModUpdateCommands(ctx, snapshot, fh.URI(), func(invoke func(...string) (*bytes.Buffer, error)) error { |
| 656 |
_, err := invoke("mod", "edit", "-go", args.Version) |
| 657 |
return err |
| 658 |
}); err != nil { |
| 659 |
return err |
| 660 |
} |
| 661 |
return nil |
| 662 |
}) |
| 663 |
} |
| 664 |
|
| 665 |
func (c *commandHandler) RemoveDependency(ctx context.Context, args command.RemoveDependencyArgs) error { |
| 666 |
return c.run(ctx, commandConfig{ |
| 667 |
progress: "Removing dependency", |
| 668 |
forURI: args.URI, |
| 669 |
}, func(ctx context.Context, deps commandDeps) error { |
| 670 |
|
| 671 |
|
| 672 |
|
| 673 |
|
| 674 |
if args.OnlyDiagnostic { |
| 675 |
return c.s.runGoModUpdateCommands(ctx, deps.snapshot, args.URI, func(invoke func(...string) (*bytes.Buffer, error)) error { |
| 676 |
if err := runGoGetModule(invoke, false, []string{args.ModulePath + "@none"}); err != nil { |
| 677 |
return err |
| 678 |
} |
| 679 |
_, err := invoke("mod", "tidy") |
| 680 |
return err |
| 681 |
}) |
| 682 |
} |
| 683 |
pm, err := deps.snapshot.ParseMod(ctx, deps.fh) |
| 684 |
if err != nil { |
| 685 |
return err |
| 686 |
} |
| 687 |
edits, err := dropDependency(pm, args.ModulePath) |
| 688 |
if err != nil { |
| 689 |
return err |
| 690 |
} |
| 691 |
return applyChanges(ctx, c.s.client, []protocol.DocumentChange{protocol.DocumentChangeEdit(deps.fh, edits)}) |
| 692 |
}) |
| 693 |
} |
| 694 |
|
| 695 |
|
| 696 |
|
| 697 |
func dropDependency(pm *cache.ParsedModule, modulePath string) ([]protocol.TextEdit, error) { |
| 698 |
|
| 699 |
|
| 700 |
copied, err := modfile.Parse("", pm.Mapper.Content, nil) |
| 701 |
if err != nil { |
| 702 |
return nil, err |
| 703 |
} |
| 704 |
if err := copied.DropRequire(modulePath); err != nil { |
| 705 |
return nil, err |
| 706 |
} |
| 707 |
copied.Cleanup() |
| 708 |
newContent, err := copied.Format() |
| 709 |
if err != nil { |
| 710 |
return nil, err |
| 711 |
} |
| 712 |
|
| 713 |
diff := diff.Bytes(pm.Mapper.Content, newContent) |
| 714 |
return protocol.EditsFromDiffEdits(pm.Mapper, diff) |
| 715 |
} |
| 716 |
|
| 717 |
func (c *commandHandler) Doc(ctx context.Context, args command.DocArgs) (protocol.URI, error) { |
| 718 |
if args.Location.URI == "" { |
| 719 |
return "", errors.New("missing location URI") |
| 720 |
} |
| 721 |
|
| 722 |
var result protocol.URI |
| 723 |
err := c.run(ctx, commandConfig{ |
| 724 |
progress: "", |
| 725 |
forURI: args.Location.URI, |
| 726 |
}, func(ctx context.Context, deps commandDeps) error { |
| 727 |
pkg, pgf, err := golang.NarrowestPackageForFile(ctx, deps.snapshot, args.Location.URI) |
| 728 |
if err != nil { |
| 729 |
return err |
| 730 |
} |
| 731 |
start, end, err := pgf.RangePos(args.Location.Range) |
| 732 |
if err != nil { |
| 733 |
return err |
| 734 |
} |
| 735 |
|
| 736 |
|
| 737 |
web, err := c.s.getWeb() |
| 738 |
if err != nil { |
| 739 |
return err |
| 740 |
} |
| 741 |
|
| 742 |
|
| 743 |
|
| 744 |
pkgpath, fragment, _ := golang.DocFragment(pkg, pgf, start, end) |
| 745 |
|
| 746 |
|
| 747 |
result = web.PkgURL(deps.snapshot.View().ID(), pkgpath, fragment) |
| 748 |
if args.ShowDocument { |
| 749 |
openClientBrowser(ctx, c.s.client, "Doc", result, c.s.Options()) |
| 750 |
} |
| 751 |
|
| 752 |
return nil |
| 753 |
}) |
| 754 |
return result, err |
| 755 |
} |
| 756 |
|
| 757 |
func (c *commandHandler) RunTests(ctx context.Context, args command.RunTestsArgs) error { |
| 758 |
return c.run(ctx, commandConfig{ |
| 759 |
progress: "Running go test", |
| 760 |
requireSave: true, |
| 761 |
forURI: args.URI, |
| 762 |
}, func(ctx context.Context, deps commandDeps) error { |
| 763 |
jsonrpc2.Async(ctx) |
| 764 |
return c.runTests(ctx, deps.snapshot, deps.work, args.URI, args.Tests, args.Benchmarks) |
| 765 |
}) |
| 766 |
} |
| 767 |
|
| 768 |
func (c *commandHandler) runTests(ctx context.Context, snapshot *cache.Snapshot, work *progress.WorkDone, uri protocol.DocumentURI, tests, benchmarks []string) error { |
| 769 |
|
| 770 |
meta, err := snapshot.NarrowestMetadataForFile(ctx, uri) |
| 771 |
if err != nil { |
| 772 |
return err |
| 773 |
} |
| 774 |
pkgPath := string(meta.ForTest) |
| 775 |
|
| 776 |
|
| 777 |
buf := &bytes.Buffer{} |
| 778 |
ew := progress.NewEventWriter(ctx, "test") |
| 779 |
out := io.MultiWriter(ew, progress.NewWorkDoneWriter(ctx, work), buf) |
| 780 |
|
| 781 |
|
| 782 |
var failedTests int |
| 783 |
for _, funcName := range tests { |
| 784 |
args := []string{pkgPath, "-v", "-count=1", fmt.Sprintf("-run=^%s$", regexp.QuoteMeta(funcName))} |
| 785 |
inv, cleanupInvocation, err := snapshot.GoCommandInvocation(cache.NoNetwork, uri.DirPath(), "test", args) |
| 786 |
if err != nil { |
| 787 |
return err |
| 788 |
} |
| 789 |
defer cleanupInvocation() |
| 790 |
if err := snapshot.View().GoCommandRunner().RunPiped(ctx, *inv, out, out); err != nil { |
| 791 |
if errors.Is(err, context.Canceled) { |
| 792 |
return err |
| 793 |
} |
| 794 |
failedTests++ |
| 795 |
} |
| 796 |
} |
| 797 |
|
| 798 |
|
| 799 |
var failedBenchmarks int |
| 800 |
for _, funcName := range benchmarks { |
| 801 |
inv, cleanupInvocation, err := snapshot.GoCommandInvocation(cache.NoNetwork, uri.DirPath(), "test", []string{ |
| 802 |
pkgPath, "-v", "-run=^$", fmt.Sprintf("-bench=^%s$", regexp.QuoteMeta(funcName)), |
| 803 |
}) |
| 804 |
if err != nil { |
| 805 |
return err |
| 806 |
} |
| 807 |
defer cleanupInvocation() |
| 808 |
if err := snapshot.View().GoCommandRunner().RunPiped(ctx, *inv, out, out); err != nil { |
| 809 |
if errors.Is(err, context.Canceled) { |
| 810 |
return err |
| 811 |
} |
| 812 |
failedBenchmarks++ |
| 813 |
} |
| 814 |
} |
| 815 |
|
| 816 |
var title string |
| 817 |
if len(tests) > 0 && len(benchmarks) > 0 { |
| 818 |
title = "tests and benchmarks" |
| 819 |
} else if len(tests) > 0 { |
| 820 |
title = "tests" |
| 821 |
} else if len(benchmarks) > 0 { |
| 822 |
title = "benchmarks" |
| 823 |
} else { |
| 824 |
return errors.New("No functions were provided") |
| 825 |
} |
| 826 |
message := fmt.Sprintf("all %s passed", title) |
| 827 |
if failedTests > 0 && failedBenchmarks > 0 { |
| 828 |
message = fmt.Sprintf("%d / %d tests failed and %d / %d benchmarks failed", failedTests, len(tests), failedBenchmarks, len(benchmarks)) |
| 829 |
} else if failedTests > 0 { |
| 830 |
message = fmt.Sprintf("%d / %d tests failed", failedTests, len(tests)) |
| 831 |
} else if failedBenchmarks > 0 { |
| 832 |
message = fmt.Sprintf("%d / %d benchmarks failed", failedBenchmarks, len(benchmarks)) |
| 833 |
} |
| 834 |
if failedTests > 0 || failedBenchmarks > 0 { |
| 835 |
message += "\n" + buf.String() |
| 836 |
} |
| 837 |
|
| 838 |
showMessage(ctx, c.s.client, protocol.Info, message) |
| 839 |
|
| 840 |
if failedTests > 0 || failedBenchmarks > 0 { |
| 841 |
return errors.New("gopls.test command failed") |
| 842 |
} |
| 843 |
return nil |
| 844 |
} |
| 845 |
|
| 846 |
func (c *commandHandler) Generate(ctx context.Context, args command.GenerateArgs) error { |
| 847 |
title := "Running go generate ." |
| 848 |
if args.Recursive { |
| 849 |
title = "Running go generate ./..." |
| 850 |
} |
| 851 |
return c.run(ctx, commandConfig{ |
| 852 |
requireSave: true, |
| 853 |
progress: title, |
| 854 |
forURI: args.Dir, |
| 855 |
}, func(ctx context.Context, deps commandDeps) error { |
| 856 |
er := progress.NewEventWriter(ctx, "generate") |
| 857 |
|
| 858 |
pattern := "." |
| 859 |
if args.Recursive { |
| 860 |
pattern = "./..." |
| 861 |
} |
| 862 |
inv, cleanupInvocation, err := deps.snapshot.GoCommandInvocation(cache.NetworkOK, args.Dir.Path(), "generate", []string{"-x", pattern}) |
| 863 |
if err != nil { |
| 864 |
return err |
| 865 |
} |
| 866 |
defer cleanupInvocation() |
| 867 |
stderr := io.MultiWriter(er, progress.NewWorkDoneWriter(ctx, deps.work)) |
| 868 |
if err := deps.snapshot.View().GoCommandRunner().RunPiped(ctx, *inv, er, stderr); err != nil { |
| 869 |
return err |
| 870 |
} |
| 871 |
return nil |
| 872 |
}) |
| 873 |
} |
| 874 |
|
| 875 |
func (c *commandHandler) GoGetPackage(ctx context.Context, args command.GoGetPackageArgs) error { |
| 876 |
return c.run(ctx, commandConfig{ |
| 877 |
forURI: args.URI, |
| 878 |
progress: "Running go get", |
| 879 |
}, func(ctx context.Context, deps commandDeps) error { |
| 880 |
snapshot := deps.snapshot |
| 881 |
modURI := snapshot.GoModForFile(args.URI) |
| 882 |
if modURI == "" { |
| 883 |
return fmt.Errorf("no go.mod file found for %s", args.URI) |
| 884 |
} |
| 885 |
tempDir, cleanupModDir, err := cache.TempModDir(ctx, snapshot, modURI) |
| 886 |
if err != nil { |
| 887 |
return fmt.Errorf("creating a temp go.mod: %v", err) |
| 888 |
} |
| 889 |
defer cleanupModDir() |
| 890 |
|
| 891 |
inv, cleanupInvocation, err := snapshot.GoCommandInvocation(cache.NetworkOK, modURI.DirPath(), "list", |
| 892 |
[]string{"-f", "{{.Module.Path}}@{{.Module.Version}}", "-mod=mod", "-modfile=" + filepath.Join(tempDir, "go.mod"), args.Pkg}, |
| 893 |
"GOWORK=off", |
| 894 |
) |
| 895 |
if err != nil { |
| 896 |
return err |
| 897 |
} |
| 898 |
defer cleanupInvocation() |
| 899 |
stdout, err := snapshot.View().GoCommandRunner().Run(ctx, *inv) |
| 900 |
if err != nil { |
| 901 |
return err |
| 902 |
} |
| 903 |
ver := strings.TrimSpace(stdout.String()) |
| 904 |
return c.s.runGoModUpdateCommands(ctx, snapshot, args.URI, func(invoke func(...string) (*bytes.Buffer, error)) error { |
| 905 |
if args.AddRequire { |
| 906 |
if err := addModuleRequire(invoke, []string{ver}); err != nil { |
| 907 |
return err |
| 908 |
} |
| 909 |
} |
| 910 |
_, err := invoke(append([]string{"get", "-d"}, args.Pkg)...) |
| 911 |
return err |
| 912 |
}) |
| 913 |
}) |
| 914 |
} |
| 915 |
|
| 916 |
func (s *server) runGoModUpdateCommands(ctx context.Context, snapshot *cache.Snapshot, uri protocol.DocumentURI, run func(invoke func(...string) (*bytes.Buffer, error)) error) error { |
| 917 |
|
| 918 |
modURI := snapshot.GoModForFile(uri) |
| 919 |
if modURI == "" { |
| 920 |
return fmt.Errorf("no go.mod file found for %s", uri.Path()) |
| 921 |
} |
| 922 |
newModBytes, newSumBytes, err := snapshot.RunGoModUpdateCommands(ctx, modURI, run) |
| 923 |
if err != nil { |
| 924 |
return err |
| 925 |
} |
| 926 |
sumURI := protocol.URIFromPath(strings.TrimSuffix(modURI.Path(), ".mod") + ".sum") |
| 927 |
|
| 928 |
modChange, err := computeEditChange(ctx, snapshot, modURI, newModBytes) |
| 929 |
if err != nil { |
| 930 |
return err |
| 931 |
} |
| 932 |
sumChange, err := computeEditChange(ctx, snapshot, sumURI, newSumBytes) |
| 933 |
if err != nil { |
| 934 |
return err |
| 935 |
} |
| 936 |
|
| 937 |
var changes []protocol.DocumentChange |
| 938 |
if modChange.Valid() { |
| 939 |
changes = append(changes, modChange) |
| 940 |
} |
| 941 |
if sumChange.Valid() { |
| 942 |
changes = append(changes, sumChange) |
| 943 |
} |
| 944 |
return applyChanges(ctx, s.client, changes) |
| 945 |
} |
| 946 |
|
| 947 |
|
| 948 |
|
| 949 |
|
| 950 |
|
| 951 |
|
| 952 |
|
| 953 |
|
| 954 |
|
| 955 |
|
| 956 |
func computeEditChange(ctx context.Context, snapshot *cache.Snapshot, uri protocol.DocumentURI, newContent []byte) (protocol.DocumentChange, error) { |
| 957 |
fh, err := snapshot.ReadFile(ctx, uri) |
| 958 |
if err != nil { |
| 959 |
return protocol.DocumentChange{}, err |
| 960 |
} |
| 961 |
oldContent, err := fh.Content() |
| 962 |
if err != nil && !os.IsNotExist(err) { |
| 963 |
return protocol.DocumentChange{}, err |
| 964 |
} |
| 965 |
|
| 966 |
if bytes.Equal(oldContent, newContent) { |
| 967 |
return protocol.DocumentChange{}, nil |
| 968 |
} |
| 969 |
|
| 970 |
|
| 971 |
|
| 972 |
|
| 973 |
if !snapshot.IsOpen(uri) { |
| 974 |
err := os.WriteFile(uri.Path(), newContent, 0666) |
| 975 |
return protocol.DocumentChange{}, err |
| 976 |
} |
| 977 |
|
| 978 |
m := protocol.NewMapper(fh.URI(), oldContent) |
| 979 |
diff := diff.Bytes(oldContent, newContent) |
| 980 |
textedits, err := protocol.EditsFromDiffEdits(m, diff) |
| 981 |
if err != nil { |
| 982 |
return protocol.DocumentChange{}, err |
| 983 |
} |
| 984 |
return protocol.DocumentChangeEdit(fh, textedits), nil |
| 985 |
} |
| 986 |
|
| 987 |
func applyChanges(ctx context.Context, cli protocol.Client, changes []protocol.DocumentChange) error { |
| 988 |
if len(changes) == 0 { |
| 989 |
return nil |
| 990 |
} |
| 991 |
response, err := cli.ApplyEdit(ctx, &protocol.ApplyWorkspaceEditParams{ |
| 992 |
Edit: *protocol.NewWorkspaceEdit(changes...), |
| 993 |
}) |
| 994 |
if err != nil { |
| 995 |
return err |
| 996 |
} |
| 997 |
if !response.Applied { |
| 998 |
return fmt.Errorf("edits not applied because of %s", response.FailureReason) |
| 999 |
} |
| 1000 |
return nil |
| 1001 |
} |
| 1002 |
|
| 1003 |
func runGoGetModule(invoke func(...string) (*bytes.Buffer, error), addRequire bool, args []string) error { |
| 1004 |
if addRequire { |
| 1005 |
if err := addModuleRequire(invoke, args); err != nil { |
| 1006 |
return err |
| 1007 |
} |
| 1008 |
} |
| 1009 |
_, err := invoke(append([]string{"get", "-d"}, args...)...) |
| 1010 |
return err |
| 1011 |
} |
| 1012 |
|
| 1013 |
func addModuleRequire(invoke func(...string) (*bytes.Buffer, error), args []string) error { |
| 1014 |
|
| 1015 |
|
| 1016 |
|
| 1017 |
|
| 1018 |
_, err := invoke(append([]string{"mod", "edit", "-require"}, args...)...) |
| 1019 |
return err |
| 1020 |
} |
| 1021 |
|
| 1022 |
|
| 1023 |
func (s *server) getUpgrades(ctx context.Context, snapshot *cache.Snapshot, uri protocol.DocumentURI, modules []string) (map[string]string, error) { |
| 1024 |
args := append([]string{"-mod=readonly", "-m", "-u", "-json"}, modules...) |
| 1025 |
inv, cleanup, err := snapshot.GoCommandInvocation(cache.NetworkOK, uri.DirPath(), "list", args) |
| 1026 |
if err != nil { |
| 1027 |
return nil, err |
| 1028 |
} |
| 1029 |
defer cleanup() |
| 1030 |
stdout, err := snapshot.View().GoCommandRunner().Run(ctx, *inv) |
| 1031 |
if err != nil { |
| 1032 |
return nil, err |
| 1033 |
} |
| 1034 |
|
| 1035 |
upgrades := map[string]string{} |
| 1036 |
for dec := json.NewDecoder(stdout); dec.More(); { |
| 1037 |
mod := &gocommand.ModuleJSON{} |
| 1038 |
if err := dec.Decode(mod); err != nil { |
| 1039 |
return nil, err |
| 1040 |
} |
| 1041 |
if mod.Update == nil { |
| 1042 |
continue |
| 1043 |
} |
| 1044 |
upgrades[mod.Path] = mod.Update.Version |
| 1045 |
} |
| 1046 |
return upgrades, nil |
| 1047 |
} |
| 1048 |
|
| 1049 |
func (c *commandHandler) GCDetails(ctx context.Context, uri protocol.DocumentURI) error { |
| 1050 |
return c.run(ctx, commandConfig{ |
| 1051 |
forURI: uri, |
| 1052 |
}, func(ctx context.Context, deps commandDeps) error { |
| 1053 |
return c.modifyState(ctx, FromToggleCompilerOptDetails, func() (*cache.Snapshot, func(), error) { |
| 1054 |
|
| 1055 |
meta, err := deps.snapshot.NarrowestMetadataForFile(ctx, deps.fh.URI()) |
| 1056 |
if err != nil { |
| 1057 |
return nil, nil, err |
| 1058 |
} |
| 1059 |
if len(meta.CompiledGoFiles) == 0 { |
| 1060 |
return nil, nil, fmt.Errorf("package %q does not compile file %q", meta.ID, deps.fh.URI()) |
| 1061 |
} |
| 1062 |
dir := meta.CompiledGoFiles[0].Dir() |
| 1063 |
|
| 1064 |
want := !deps.snapshot.WantCompilerOptDetails(dir) |
| 1065 |
return c.s.session.InvalidateView(ctx, deps.snapshot.View(), cache.StateChange{ |
| 1066 |
CompilerOptDetails: map[protocol.DocumentURI]bool{dir: want}, |
| 1067 |
}) |
| 1068 |
}) |
| 1069 |
}) |
| 1070 |
} |
| 1071 |
|
| 1072 |
func (c *commandHandler) ListKnownPackages(ctx context.Context, args command.URIArg) (command.ListKnownPackagesResult, error) { |
| 1073 |
var result command.ListKnownPackagesResult |
| 1074 |
err := c.run(ctx, commandConfig{ |
| 1075 |
progress: "Listing packages", |
| 1076 |
forURI: args.URI, |
| 1077 |
}, func(ctx context.Context, deps commandDeps) error { |
| 1078 |
pkgs, err := golang.KnownPackagePaths(ctx, deps.snapshot, deps.fh) |
| 1079 |
for _, pkg := range pkgs { |
| 1080 |
result.Packages = append(result.Packages, string(pkg)) |
| 1081 |
} |
| 1082 |
return err |
| 1083 |
}) |
| 1084 |
return result, err |
| 1085 |
} |
| 1086 |
|
| 1087 |
func (c *commandHandler) ListImports(ctx context.Context, args command.URIArg) (command.ListImportsResult, error) { |
| 1088 |
var result command.ListImportsResult |
| 1089 |
err := c.run(ctx, commandConfig{ |
| 1090 |
forURI: args.URI, |
| 1091 |
}, func(ctx context.Context, deps commandDeps) error { |
| 1092 |
fh, err := deps.snapshot.ReadFile(ctx, args.URI) |
| 1093 |
if err != nil { |
| 1094 |
return err |
| 1095 |
} |
| 1096 |
pgf, err := deps.snapshot.ParseGo(ctx, fh, parsego.Header) |
| 1097 |
if err != nil { |
| 1098 |
return err |
| 1099 |
} |
| 1100 |
fset := tokeninternal.FileSetFor(pgf.Tok) |
| 1101 |
for _, group := range astutil.Imports(fset, pgf.File) { |
| 1102 |
for _, imp := range group { |
| 1103 |
if imp.Path == nil { |
| 1104 |
continue |
| 1105 |
} |
| 1106 |
var name string |
| 1107 |
if imp.Name != nil { |
| 1108 |
name = imp.Name.Name |
| 1109 |
} |
| 1110 |
result.Imports = append(result.Imports, command.FileImport{ |
| 1111 |
Path: string(metadata.UnquoteImportPath(imp)), |
| 1112 |
Name: name, |
| 1113 |
}) |
| 1114 |
} |
| 1115 |
} |
| 1116 |
meta, err := deps.snapshot.NarrowestMetadataForFile(ctx, args.URI) |
| 1117 |
if err != nil { |
| 1118 |
return err |
| 1119 |
} |
| 1120 |
for pkgPath := range meta.DepsByPkgPath { |
| 1121 |
result.PackageImports = append(result.PackageImports, |
| 1122 |
command.PackageImport{Path: string(pkgPath)}) |
| 1123 |
} |
| 1124 |
sort.Slice(result.PackageImports, func(i, j int) bool { |
| 1125 |
return result.PackageImports[i].Path < result.PackageImports[j].Path |
| 1126 |
}) |
| 1127 |
return nil |
| 1128 |
}) |
| 1129 |
return result, err |
| 1130 |
} |
| 1131 |
|
| 1132 |
func (c *commandHandler) AddImport(ctx context.Context, args command.AddImportArgs) error { |
| 1133 |
return c.run(ctx, commandConfig{ |
| 1134 |
progress: "Adding import", |
| 1135 |
forURI: args.URI, |
| 1136 |
}, func(ctx context.Context, deps commandDeps) error { |
| 1137 |
edits, err := golang.AddImport(ctx, deps.snapshot, deps.fh, args.ImportPath) |
| 1138 |
if err != nil { |
| 1139 |
return fmt.Errorf("could not add import: %v", err) |
| 1140 |
} |
| 1141 |
return applyChanges(ctx, c.s.client, []protocol.DocumentChange{protocol.DocumentChangeEdit(deps.fh, edits)}) |
| 1142 |
}) |
| 1143 |
} |
| 1144 |
|
| 1145 |
func (c *commandHandler) ExtractToNewFile(ctx context.Context, args protocol.Location) error { |
| 1146 |
return c.run(ctx, commandConfig{ |
| 1147 |
progress: "Extract to a new file", |
| 1148 |
forURI: args.URI, |
| 1149 |
}, func(ctx context.Context, deps commandDeps) error { |
| 1150 |
changes, err := golang.ExtractToNewFile(ctx, deps.snapshot, deps.fh, args.Range) |
| 1151 |
if err != nil { |
| 1152 |
return err |
| 1153 |
} |
| 1154 |
return applyChanges(ctx, c.s.client, changes) |
| 1155 |
}) |
| 1156 |
} |
| 1157 |
|
| 1158 |
func (c *commandHandler) StartDebugging(ctx context.Context, args command.DebuggingArgs) (result command.DebuggingResult, _ error) { |
| 1159 |
addr := args.Addr |
| 1160 |
if addr == "" { |
| 1161 |
addr = "localhost:0" |
| 1162 |
} |
| 1163 |
di := debug.GetInstance(ctx) |
| 1164 |
if di == nil { |
| 1165 |
return result, errors.New("internal error: server has no debugging instance") |
| 1166 |
} |
| 1167 |
listenedAddr, err := di.Serve(ctx, addr) |
| 1168 |
if err != nil { |
| 1169 |
return result, fmt.Errorf("starting debug server: %w", err) |
| 1170 |
} |
| 1171 |
result.URLs = []string{"http://" + listenedAddr} |
| 1172 |
openClientBrowser(ctx, c.s.client, "Debug", result.URLs[0], c.s.Options()) |
| 1173 |
return result, nil |
| 1174 |
} |
| 1175 |
|
| 1176 |
func (c *commandHandler) StartProfile(ctx context.Context, args command.StartProfileArgs) (result command.StartProfileResult, _ error) { |
| 1177 |
file, err := os.CreateTemp("", "gopls-profile-*") |
| 1178 |
if err != nil { |
| 1179 |
return result, fmt.Errorf("creating temp profile file: %v", err) |
| 1180 |
} |
| 1181 |
|
| 1182 |
c.s.ongoingProfileMu.Lock() |
| 1183 |
defer c.s.ongoingProfileMu.Unlock() |
| 1184 |
|
| 1185 |
if c.s.ongoingProfile != nil { |
| 1186 |
file.Close() |
| 1187 |
return result, fmt.Errorf("profile already started (for %q)", c.s.ongoingProfile.Name()) |
| 1188 |
} |
| 1189 |
|
| 1190 |
if err := pprof.StartCPUProfile(file); err != nil { |
| 1191 |
file.Close() |
| 1192 |
return result, fmt.Errorf("starting profile: %v", err) |
| 1193 |
} |
| 1194 |
|
| 1195 |
c.s.ongoingProfile = file |
| 1196 |
return result, nil |
| 1197 |
} |
| 1198 |
|
| 1199 |
func (c *commandHandler) StopProfile(ctx context.Context, args command.StopProfileArgs) (result command.StopProfileResult, _ error) { |
| 1200 |
c.s.ongoingProfileMu.Lock() |
| 1201 |
defer c.s.ongoingProfileMu.Unlock() |
| 1202 |
|
| 1203 |
prof := c.s.ongoingProfile |
| 1204 |
c.s.ongoingProfile = nil |
| 1205 |
|
| 1206 |
if prof == nil { |
| 1207 |
return result, fmt.Errorf("no ongoing profile") |
| 1208 |
} |
| 1209 |
|
| 1210 |
pprof.StopCPUProfile() |
| 1211 |
if err := prof.Close(); err != nil { |
| 1212 |
return result, fmt.Errorf("closing profile file: %v", err) |
| 1213 |
} |
| 1214 |
result.File = prof.Name() |
| 1215 |
return result, nil |
| 1216 |
} |
| 1217 |
|
| 1218 |
func (c *commandHandler) FetchVulncheckResult(ctx context.Context, arg command.URIArg) (map[protocol.DocumentURI]*vulncheck.Result, error) { |
| 1219 |
ret := map[protocol.DocumentURI]*vulncheck.Result{} |
| 1220 |
err := c.run(ctx, commandConfig{forURI: arg.URI}, func(ctx context.Context, deps commandDeps) error { |
| 1221 |
if deps.snapshot.Options().Vulncheck == settings.ModeVulncheckImports { |
| 1222 |
for _, modfile := range deps.snapshot.View().ModFiles() { |
| 1223 |
res, err := deps.snapshot.ModVuln(ctx, modfile) |
| 1224 |
if err != nil { |
| 1225 |
return err |
| 1226 |
} |
| 1227 |
ret[modfile] = res |
| 1228 |
} |
| 1229 |
} |
| 1230 |
|
| 1231 |
maps.Copy(ret, deps.snapshot.Vulnerabilities()) |
| 1232 |
return nil |
| 1233 |
}) |
| 1234 |
return ret, err |
| 1235 |
} |
| 1236 |
|
| 1237 |
const GoVulncheckCommandTitle = "govulncheck" |
| 1238 |
|
| 1239 |
func (c *commandHandler) Vulncheck(ctx context.Context, args command.VulncheckArgs) (command.VulncheckResult, error) { |
| 1240 |
if args.URI == "" { |
| 1241 |
return command.VulncheckResult{}, errors.New("VulncheckArgs is missing URI field") |
| 1242 |
} |
| 1243 |
|
| 1244 |
var commandResult command.VulncheckResult |
| 1245 |
err := c.run(ctx, commandConfig{ |
| 1246 |
progress: GoVulncheckCommandTitle, |
| 1247 |
progressStyle: settings.WorkDoneProgressStyleLog, |
| 1248 |
requireSave: true, |
| 1249 |
forURI: args.URI, |
| 1250 |
}, func(ctx context.Context, deps commandDeps) error { |
| 1251 |
jsonrpc2.Async(ctx) |
| 1252 |
|
| 1253 |
workDoneWriter := progress.NewWorkDoneWriter(ctx, deps.work) |
| 1254 |
result, err := c.s.runVulncheck(ctx, deps.snapshot, args.URI, args.Pattern, workDoneWriter) |
| 1255 |
if err != nil { |
| 1256 |
return err |
| 1257 |
} |
| 1258 |
commandResult.Result = result |
| 1259 |
commandResult.Token = deps.work.Token() |
| 1260 |
|
| 1261 |
affecting := make(map[string]bool, len(result.Entries)) |
| 1262 |
for _, finding := range result.Findings { |
| 1263 |
if len(finding.Trace) > 1 { |
| 1264 |
affecting[finding.OSV] = true |
| 1265 |
} |
| 1266 |
} |
| 1267 |
if len(affecting) == 0 { |
| 1268 |
showMessage(ctx, c.s.client, protocol.Info, "No vulnerabilities found") |
| 1269 |
return nil |
| 1270 |
} |
| 1271 |
affectingOSVs := make([]string, 0, len(affecting)) |
| 1272 |
for id := range affecting { |
| 1273 |
affectingOSVs = append(affectingOSVs, id) |
| 1274 |
} |
| 1275 |
sort.Strings(affectingOSVs) |
| 1276 |
|
| 1277 |
showMessage(ctx, c.s.client, protocol.Warning, fmt.Sprintf("Found %v", strings.Join(affectingOSVs, ", "))) |
| 1278 |
return nil |
| 1279 |
}) |
| 1280 |
if err != nil { |
| 1281 |
return command.VulncheckResult{}, err |
| 1282 |
} |
| 1283 |
return commandResult, nil |
| 1284 |
} |
| 1285 |
|
| 1286 |
|
| 1287 |
|
| 1288 |
|
| 1289 |
|
| 1290 |
|
| 1291 |
|
| 1292 |
|
| 1293 |
|
| 1294 |
func (c *commandHandler) RunGovulncheck(ctx context.Context, args command.VulncheckArgs) (command.RunVulncheckResult, error) { |
| 1295 |
|
| 1296 |
if !c.s.runGovulncheckInProgress.CompareAndSwap(false, true) { |
| 1297 |
c.s.client.ShowMessage(ctx, &protocol.ShowMessageParams{ |
| 1298 |
Type: protocol.Info, |
| 1299 |
Message: "A govulncheck scan is already in progress.", |
| 1300 |
}) |
| 1301 |
return command.RunVulncheckResult{}, nil |
| 1302 |
} |
| 1303 |
|
| 1304 |
defer c.s.runGovulncheckInProgress.Store(false) |
| 1305 |
|
| 1306 |
if args.URI == "" { |
| 1307 |
return command.RunVulncheckResult{}, errors.New("VulncheckArgs is missing URI field") |
| 1308 |
} |
| 1309 |
|
| 1310 |
|
| 1311 |
|
| 1312 |
|
| 1313 |
|
| 1314 |
|
| 1315 |
tokenChan := make(chan protocol.ProgressToken, 1) |
| 1316 |
err := c.run(ctx, commandConfig{ |
| 1317 |
progress: GoVulncheckCommandTitle, |
| 1318 |
requireSave: true, |
| 1319 |
forURI: args.URI, |
| 1320 |
}, func(ctx context.Context, deps commandDeps) error { |
| 1321 |
tokenChan <- deps.work.Token() |
| 1322 |
|
| 1323 |
workDoneWriter := progress.NewWorkDoneWriter(ctx, deps.work) |
| 1324 |
result, err := c.s.runVulncheck(ctx, deps.snapshot, args.URI, args.Pattern, workDoneWriter) |
| 1325 |
if err != nil { |
| 1326 |
return err |
| 1327 |
} |
| 1328 |
|
| 1329 |
affecting := make(map[string]bool, len(result.Entries)) |
| 1330 |
for _, finding := range result.Findings { |
| 1331 |
if len(finding.Trace) > 1 { |
| 1332 |
affecting[finding.OSV] = true |
| 1333 |
} |
| 1334 |
} |
| 1335 |
if len(affecting) == 0 { |
| 1336 |
showMessage(ctx, c.s.client, protocol.Info, "No vulnerabilities found") |
| 1337 |
return nil |
| 1338 |
} |
| 1339 |
affectingOSVs := make([]string, 0, len(affecting)) |
| 1340 |
for id := range affecting { |
| 1341 |
affectingOSVs = append(affectingOSVs, id) |
| 1342 |
} |
| 1343 |
sort.Strings(affectingOSVs) |
| 1344 |
|
| 1345 |
showMessage(ctx, c.s.client, protocol.Warning, fmt.Sprintf("Found %v", strings.Join(affectingOSVs, ", "))) |
| 1346 |
return nil |
| 1347 |
}) |
| 1348 |
if err != nil { |
| 1349 |
return command.RunVulncheckResult{}, err |
| 1350 |
} |
| 1351 |
select { |
| 1352 |
case <-ctx.Done(): |
| 1353 |
return command.RunVulncheckResult{}, ctx.Err() |
| 1354 |
case token := <-tokenChan: |
| 1355 |
return command.RunVulncheckResult{Token: token}, nil |
| 1356 |
} |
| 1357 |
} |
| 1358 |
|
| 1359 |
|
| 1360 |
func (s *server) runVulncheck(ctx context.Context, snapshot *cache.Snapshot, uri protocol.DocumentURI, pattern string, out io.Writer) (*vulncheck.Result, error) { |
| 1361 |
dir := uri.DirPath() |
| 1362 |
result, err := scan.RunGovulncheck(ctx, pattern, snapshot, dir, out) |
| 1363 |
if err != nil { |
| 1364 |
return nil, err |
| 1365 |
} |
| 1366 |
|
| 1367 |
|
| 1368 |
newSnapshot, release, err := s.session.InvalidateView(ctx, snapshot.View(), cache.StateChange{ |
| 1369 |
Vulns: map[protocol.DocumentURI]*vulncheck.Result{uri: result}, |
| 1370 |
}) |
| 1371 |
if err != nil { |
| 1372 |
return nil, err |
| 1373 |
} |
| 1374 |
defer release() |
| 1375 |
|
| 1376 |
|
| 1377 |
|
| 1378 |
s.diagnoseSnapshot(newSnapshot.BackgroundContext(), newSnapshot, nil, 0) |
| 1379 |
|
| 1380 |
return result, nil |
| 1381 |
} |
| 1382 |
|
| 1383 |
|
| 1384 |
|
| 1385 |
func (c *commandHandler) MemStats(ctx context.Context) (command.MemStatsResult, error) { |
| 1386 |
|
| 1387 |
runtime.GC() |
| 1388 |
runtime.GC() |
| 1389 |
runtime.GC() |
| 1390 |
var m runtime.MemStats |
| 1391 |
runtime.ReadMemStats(&m) |
| 1392 |
return command.MemStatsResult{ |
| 1393 |
HeapAlloc: m.HeapAlloc, |
| 1394 |
HeapInUse: m.HeapInuse, |
| 1395 |
TotalAlloc: m.TotalAlloc, |
| 1396 |
}, nil |
| 1397 |
} |
| 1398 |
|
| 1399 |
|
| 1400 |
|
| 1401 |
func (c *commandHandler) WorkspaceStats(ctx context.Context) (command.WorkspaceStatsResult, error) { |
| 1402 |
var res command.WorkspaceStatsResult |
| 1403 |
res.Files = c.s.session.Cache().FileStats() |
| 1404 |
|
| 1405 |
for _, view := range c.s.session.Views() { |
| 1406 |
vs, err := collectViewStats(ctx, view) |
| 1407 |
if err != nil { |
| 1408 |
return res, err |
| 1409 |
} |
| 1410 |
res.Views = append(res.Views, vs) |
| 1411 |
} |
| 1412 |
return res, nil |
| 1413 |
} |
| 1414 |
|
| 1415 |
func collectViewStats(ctx context.Context, view *cache.View) (command.ViewStats, error) { |
| 1416 |
s, release, err := view.Snapshot() |
| 1417 |
if err != nil { |
| 1418 |
return command.ViewStats{}, err |
| 1419 |
} |
| 1420 |
defer release() |
| 1421 |
|
| 1422 |
allMD, err := s.AllMetadata(ctx) |
| 1423 |
if err != nil { |
| 1424 |
return command.ViewStats{}, err |
| 1425 |
} |
| 1426 |
allPackages := collectPackageStats(allMD) |
| 1427 |
|
| 1428 |
wsMD, err := s.WorkspaceMetadata(ctx) |
| 1429 |
if err != nil { |
| 1430 |
return command.ViewStats{}, err |
| 1431 |
} |
| 1432 |
workspacePackages := collectPackageStats(wsMD) |
| 1433 |
|
| 1434 |
var ids []golang.PackageID |
| 1435 |
for _, mp := range wsMD { |
| 1436 |
ids = append(ids, mp.ID) |
| 1437 |
} |
| 1438 |
|
| 1439 |
diags, err := s.PackageDiagnostics(ctx, ids...) |
| 1440 |
if err != nil { |
| 1441 |
return command.ViewStats{}, err |
| 1442 |
} |
| 1443 |
|
| 1444 |
ndiags := 0 |
| 1445 |
for _, d := range diags { |
| 1446 |
ndiags += len(d) |
| 1447 |
} |
| 1448 |
|
| 1449 |
return command.ViewStats{ |
| 1450 |
GoCommandVersion: view.GoVersionString(), |
| 1451 |
AllPackages: allPackages, |
| 1452 |
WorkspacePackages: workspacePackages, |
| 1453 |
Diagnostics: ndiags, |
| 1454 |
}, nil |
| 1455 |
} |
| 1456 |
|
| 1457 |
func collectPackageStats(mps []*metadata.Package) command.PackageStats { |
| 1458 |
var stats command.PackageStats |
| 1459 |
stats.Packages = len(mps) |
| 1460 |
modules := make(map[string]bool) |
| 1461 |
|
| 1462 |
for _, mp := range mps { |
| 1463 |
n := len(mp.CompiledGoFiles) |
| 1464 |
stats.CompiledGoFiles += n |
| 1465 |
if n > stats.LargestPackage { |
| 1466 |
stats.LargestPackage = n |
| 1467 |
} |
| 1468 |
if mp.Module != nil { |
| 1469 |
modules[mp.Module.Path] = true |
| 1470 |
} |
| 1471 |
} |
| 1472 |
stats.Modules = len(modules) |
| 1473 |
|
| 1474 |
return stats |
| 1475 |
} |
| 1476 |
|
| 1477 |
|
| 1478 |
|
| 1479 |
|
| 1480 |
|
| 1481 |
|
| 1482 |
|
| 1483 |
|
| 1484 |
|
| 1485 |
|
| 1486 |
|
| 1487 |
|
| 1488 |
|
| 1489 |
|
| 1490 |
|
| 1491 |
|
| 1492 |
|
| 1493 |
|
| 1494 |
|
| 1495 |
|
| 1496 |
|
| 1497 |
|
| 1498 |
|
| 1499 |
|
| 1500 |
|
| 1501 |
|
| 1502 |
func (c *commandHandler) RunGoWorkCommand(ctx context.Context, args command.RunGoWorkArgs) error { |
| 1503 |
return c.run(ctx, commandConfig{ |
| 1504 |
progress: "Running go work command", |
| 1505 |
forView: args.ViewID, |
| 1506 |
}, func(ctx context.Context, deps commandDeps) (runErr error) { |
| 1507 |
snapshot := deps.snapshot |
| 1508 |
view := snapshot.View() |
| 1509 |
viewDir := snapshot.Folder().Path() |
| 1510 |
|
| 1511 |
if view.Type() != cache.GoWorkView && view.GoWork() != "" { |
| 1512 |
|
| 1513 |
|
| 1514 |
return fmt.Errorf("cannot modify go.work files when GOWORK=off") |
| 1515 |
} |
| 1516 |
|
| 1517 |
var gowork string |
| 1518 |
|
| 1519 |
|
| 1520 |
if view.GoWork() != "" { |
| 1521 |
gowork = view.GoWork().Path() |
| 1522 |
fh, err := snapshot.ReadFile(ctx, view.GoWork()) |
| 1523 |
if err != nil { |
| 1524 |
return err |
| 1525 |
} |
| 1526 |
if !fh.SameContentsOnDisk() { |
| 1527 |
return fmt.Errorf("must save workspace file %s before running go work commands", view.GoWork()) |
| 1528 |
} |
| 1529 |
} else { |
| 1530 |
if !args.InitFirst { |
| 1531 |
|
| 1532 |
|
| 1533 |
return bug.Errorf("internal error: cannot run go work command: required go.work file not found") |
| 1534 |
} |
| 1535 |
gowork = filepath.Join(viewDir, "go.work") |
| 1536 |
if err := c.invokeGoWork(ctx, viewDir, gowork, []string{"init"}); err != nil { |
| 1537 |
return fmt.Errorf("running `go work init`: %v", err) |
| 1538 |
} |
| 1539 |
} |
| 1540 |
|
| 1541 |
return c.invokeGoWork(ctx, viewDir, gowork, args.Args) |
| 1542 |
}) |
| 1543 |
} |
| 1544 |
|
| 1545 |
func (c *commandHandler) invokeGoWork(ctx context.Context, viewDir, gowork string, args []string) error { |
| 1546 |
inv := gocommand.Invocation{ |
| 1547 |
Verb: "work", |
| 1548 |
Args: args, |
| 1549 |
WorkingDir: viewDir, |
| 1550 |
Env: append(os.Environ(), fmt.Sprintf("GOWORK=%s", gowork)), |
| 1551 |
} |
| 1552 |
if _, err := c.s.session.GoCommandRunner().Run(ctx, inv); err != nil { |
| 1553 |
return fmt.Errorf("running go work command: %v", err) |
| 1554 |
} |
| 1555 |
return nil |
| 1556 |
} |
| 1557 |
|
| 1558 |
|
| 1559 |
|
| 1560 |
|
| 1561 |
|
| 1562 |
func showMessage(ctx context.Context, cli protocol.Client, typ protocol.MessageType, message string) bool { |
| 1563 |
err := cli.ShowMessage(ctx, &protocol.ShowMessageParams{ |
| 1564 |
Type: typ, |
| 1565 |
Message: message, |
| 1566 |
}) |
| 1567 |
if err != nil { |
| 1568 |
event.Error(ctx, "client.showMessage: %v", err) |
| 1569 |
return false |
| 1570 |
} |
| 1571 |
return true |
| 1572 |
} |
| 1573 |
|
| 1574 |
|
| 1575 |
|
| 1576 |
|
| 1577 |
|
| 1578 |
|
| 1579 |
func openClientBrowser(ctx context.Context, cli protocol.Client, title string, url protocol.URI, opts *settings.Options) { |
| 1580 |
if opts.ShowDocumentSupported { |
| 1581 |
showDocumentImpl(ctx, cli, url, nil, opts) |
| 1582 |
} else { |
| 1583 |
params := &protocol.ShowMessageParams{ |
| 1584 |
Type: protocol.Info, |
| 1585 |
Message: fmt.Sprintf("%s: open your browser to %s", title, url), |
| 1586 |
} |
| 1587 |
if err := cli.ShowMessage(ctx, params); err != nil { |
| 1588 |
event.Error(ctx, "failed to show browser url", err) |
| 1589 |
} |
| 1590 |
} |
| 1591 |
} |
| 1592 |
|
| 1593 |
|
| 1594 |
|
| 1595 |
|
| 1596 |
|
| 1597 |
|
| 1598 |
func openClientEditor(ctx context.Context, cli protocol.Client, loc protocol.Location, opts *settings.Options) { |
| 1599 |
if !opts.ShowDocumentSupported { |
| 1600 |
return |
| 1601 |
} |
| 1602 |
showDocumentImpl(ctx, cli, protocol.URI(loc.URI), &loc.Range, opts) |
| 1603 |
} |
| 1604 |
|
| 1605 |
func showDocumentImpl(ctx context.Context, cli protocol.Client, url protocol.URI, rangeOpt *protocol.Range, opts *settings.Options) { |
| 1606 |
if !opts.ShowDocumentSupported { |
| 1607 |
return |
| 1608 |
} |
| 1609 |
|
| 1610 |
|
| 1611 |
|
| 1612 |
|
| 1613 |
|
| 1614 |
|
| 1615 |
|
| 1616 |
|
| 1617 |
|
| 1618 |
|
| 1619 |
|
| 1620 |
|
| 1621 |
|
| 1622 |
|
| 1623 |
|
| 1624 |
|
| 1625 |
|
| 1626 |
|
| 1627 |
res, err := cli.ShowDocument(ctx, &protocol.ShowDocumentParams{ |
| 1628 |
URI: url, |
| 1629 |
External: rangeOpt == nil, |
| 1630 |
TakeFocus: true, |
| 1631 |
Selection: rangeOpt, |
| 1632 |
}) |
| 1633 |
if err != nil { |
| 1634 |
event.Error(ctx, "client.showDocument: %v", err) |
| 1635 |
} else if res != nil && !res.Success { |
| 1636 |
event.Log(ctx, fmt.Sprintf("client declined to open document %v", url)) |
| 1637 |
} |
| 1638 |
} |
| 1639 |
|
| 1640 |
func (c *commandHandler) ChangeSignature(ctx context.Context, args command.ChangeSignatureArgs) (*protocol.WorkspaceEdit, error) { |
| 1641 |
countChangeSignature.Inc() |
| 1642 |
var result *protocol.WorkspaceEdit |
| 1643 |
err := c.run(ctx, commandConfig{ |
| 1644 |
forURI: args.Location.URI, |
| 1645 |
}, func(ctx context.Context, deps commandDeps) error { |
| 1646 |
pkg, pgf, err := golang.NarrowestPackageForFile(ctx, deps.snapshot, args.Location.URI) |
| 1647 |
if err != nil { |
| 1648 |
return err |
| 1649 |
} |
| 1650 |
|
| 1651 |
|
| 1652 |
var perm []int |
| 1653 |
for _, newParam := range args.NewParams { |
| 1654 |
if newParam.NewField != "" { |
| 1655 |
return fmt.Errorf("adding new parameters is currently unsupported") |
| 1656 |
} |
| 1657 |
perm = append(perm, newParam.OldIndex) |
| 1658 |
} |
| 1659 |
|
| 1660 |
docedits, err := golang.ChangeSignature(ctx, deps.snapshot, pkg, pgf, args.Location.Range, perm) |
| 1661 |
if err != nil { |
| 1662 |
return err |
| 1663 |
} |
| 1664 |
wsedit := protocol.NewWorkspaceEdit(docedits...) |
| 1665 |
if args.ResolveEdits { |
| 1666 |
result = wsedit |
| 1667 |
return nil |
| 1668 |
} |
| 1669 |
return applyChanges(ctx, c.s.client, docedits) |
| 1670 |
}) |
| 1671 |
return result, err |
| 1672 |
} |
| 1673 |
|
| 1674 |
func (c *commandHandler) DiagnoseFiles(ctx context.Context, args command.DiagnoseFilesArgs) error { |
| 1675 |
return c.run(ctx, commandConfig{ |
| 1676 |
progress: "Diagnose files", |
| 1677 |
}, func(ctx context.Context, _ commandDeps) error { |
| 1678 |
|
| 1679 |
|
| 1680 |
|
| 1681 |
|
| 1682 |
|
| 1683 |
ctx, done := event.Start(ctx, "commandHandler.DiagnoseFiles") |
| 1684 |
defer done() |
| 1685 |
|
| 1686 |
snapshots := make(map[*cache.Snapshot]bool) |
| 1687 |
for _, uri := range args.Files { |
| 1688 |
fh, snapshot, release, err := c.s.session.FileOf(ctx, uri) |
| 1689 |
if err != nil { |
| 1690 |
return err |
| 1691 |
} |
| 1692 |
if snapshots[snapshot] || snapshot.FileKind(fh) != file.Go { |
| 1693 |
release() |
| 1694 |
continue |
| 1695 |
} |
| 1696 |
defer release() |
| 1697 |
snapshots[snapshot] = true |
| 1698 |
} |
| 1699 |
|
| 1700 |
var wg sync.WaitGroup |
| 1701 |
for snapshot := range snapshots { |
| 1702 |
wg.Go(func() { |
| 1703 |
|
| 1704 |
|
| 1705 |
|
| 1706 |
|
| 1707 |
c.s.diagnoseSnapshot(ctx, snapshot, nil, 0) |
| 1708 |
}) |
| 1709 |
} |
| 1710 |
wg.Wait() |
| 1711 |
|
| 1712 |
return nil |
| 1713 |
}) |
| 1714 |
} |
| 1715 |
|
| 1716 |
func (c *commandHandler) Views(ctx context.Context) ([]command.View, error) { |
| 1717 |
var summaries []command.View |
| 1718 |
for _, view := range c.s.session.Views() { |
| 1719 |
summaries = append(summaries, command.View{ |
| 1720 |
ID: view.ID(), |
| 1721 |
Type: view.Type().String(), |
| 1722 |
Root: view.Root(), |
| 1723 |
Folder: view.Folder().Dir, |
| 1724 |
EnvOverlay: view.EnvOverlay(), |
| 1725 |
}) |
| 1726 |
} |
| 1727 |
return summaries, nil |
| 1728 |
} |
| 1729 |
|
| 1730 |
func (c *commandHandler) FreeSymbols(ctx context.Context, viewID string, loc protocol.Location) error { |
| 1731 |
web, err := c.s.getWeb() |
| 1732 |
if err != nil { |
| 1733 |
return err |
| 1734 |
} |
| 1735 |
url := web.freesymbolsURL(viewID, loc) |
| 1736 |
openClientBrowser(ctx, c.s.client, "Free symbols", url, c.s.Options()) |
| 1737 |
return nil |
| 1738 |
} |
| 1739 |
|
| 1740 |
func (c *commandHandler) SplitPackage(ctx context.Context, viewID, packageID string) error { |
| 1741 |
web, err := c.s.getWeb() |
| 1742 |
if err != nil { |
| 1743 |
return err |
| 1744 |
} |
| 1745 |
url := web.splitpkgURL(viewID, packageID) |
| 1746 |
openClientBrowser(ctx, c.s.client, "SplitPackage", url, c.s.Options()) |
| 1747 |
return nil |
| 1748 |
} |
| 1749 |
|
| 1750 |
func (c *commandHandler) Assembly(ctx context.Context, viewID, packageID, symbol string) error { |
| 1751 |
web, err := c.s.getWeb() |
| 1752 |
if err != nil { |
| 1753 |
return err |
| 1754 |
} |
| 1755 |
url := web.assemblyURL(viewID, packageID, symbol) |
| 1756 |
openClientBrowser(ctx, c.s.client, "Assembly", url, c.s.Options()) |
| 1757 |
return nil |
| 1758 |
} |
| 1759 |
|
| 1760 |
func (c *commandHandler) ClientOpenURL(ctx context.Context, url string) error { |
| 1761 |
|
| 1762 |
|
| 1763 |
openClientBrowser(ctx, c.s.client, "Gopls", url, c.s.Options()) |
| 1764 |
return nil |
| 1765 |
} |
| 1766 |
|
| 1767 |
func (c *commandHandler) ScanImports(ctx context.Context) error { |
| 1768 |
for _, v := range c.s.session.Views() { |
| 1769 |
v.ScanImports() |
| 1770 |
} |
| 1771 |
return nil |
| 1772 |
} |
| 1773 |
|
| 1774 |
func (c *commandHandler) PackageSymbols(ctx context.Context, args command.PackageSymbolsArgs) (command.PackageSymbolsResult, error) { |
| 1775 |
var result command.PackageSymbolsResult |
| 1776 |
err := c.run(ctx, commandConfig{ |
| 1777 |
forURI: args.URI, |
| 1778 |
}, func(ctx context.Context, deps commandDeps) error { |
| 1779 |
if deps.snapshot.FileKind(deps.fh) != file.Go { |
| 1780 |
|
| 1781 |
return nil |
| 1782 |
} |
| 1783 |
res, err := golang.PackageSymbols(ctx, deps.snapshot, args.URI) |
| 1784 |
if err != nil { |
| 1785 |
return err |
| 1786 |
} |
| 1787 |
result = res |
| 1788 |
return nil |
| 1789 |
}) |
| 1790 |
|
| 1791 |
|
| 1792 |
sort.SliceStable(result.Symbols, func(i, j int) bool { |
| 1793 |
iv, jv := result.Symbols[i], result.Symbols[j] |
| 1794 |
if iv.Name == jv.Name { |
| 1795 |
return iv.Range.Start.Line < jv.Range.Start.Line |
| 1796 |
} |
| 1797 |
return iv.Name < jv.Name |
| 1798 |
}) |
| 1799 |
|
| 1800 |
return result, err |
| 1801 |
} |
| 1802 |
|
| 1803 |
|
| 1804 |
|
| 1805 |
func optionsStringToMap(options string) (map[string][]string, error) { |
| 1806 |
optionsMap := make(map[string][]string) |
| 1807 |
for item := range strings.SplitSeq(options, ",") { |
| 1808 |
key, option, found := strings.Cut(item, "=") |
| 1809 |
if !found { |
| 1810 |
return nil, fmt.Errorf("invalid option %q", item) |
| 1811 |
} |
| 1812 |
optionsMap[key] = append(optionsMap[key], option) |
| 1813 |
} |
| 1814 |
return optionsMap, nil |
| 1815 |
} |
| 1816 |
|
| 1817 |
func (c *commandHandler) ImplementInterface(ctx context.Context, args command.ImplementInterfaceArgs, params *protocol.InteractiveParams) error { |
| 1818 |
return c.run(ctx, commandConfig{ |
| 1819 |
progress: "Implement interface X", |
| 1820 |
forURI: args.Location.URI, |
| 1821 |
}, func(ctx context.Context, deps commandDeps) error { |
| 1822 |
iface, err := golang.FormAnswer[string](params, "interface") |
| 1823 |
if err != nil { |
| 1824 |
return err |
| 1825 |
} |
| 1826 |
|
| 1827 |
edits, err := golang.ImplementInterface(ctx, deps.snapshot, args.Location, iface) |
| 1828 |
if err != nil { |
| 1829 |
return err |
| 1830 |
} |
| 1831 |
return applyChanges(ctx, c.s.client, edits) |
| 1832 |
}) |
| 1833 |
} |
| 1834 |
|
| 1835 |
func (c *commandHandler) ModifyTags(ctx context.Context, args command.ModifyTagsArgs, params *protocol.InteractiveParams) error { |
| 1836 |
return c.run(ctx, commandConfig{ |
| 1837 |
progress: "Modifying tags", |
| 1838 |
forURI: args.URI, |
| 1839 |
}, func(ctx context.Context, deps commandDeps) error { |
| 1840 |
if len(params.FormAnswers) > 0 { |
| 1841 |
switch args.Modification { |
| 1842 |
case "add": |
| 1843 |
tags, err := golang.FormAnswer[string](params, "tags") |
| 1844 |
if err != nil { |
| 1845 |
return err |
| 1846 |
} |
| 1847 |
args.Add, err = golang.SanitizeTags(tags) |
| 1848 |
if err != nil { |
| 1849 |
return err |
| 1850 |
} |
| 1851 |
args.Transform, err = golang.FormAnswer[string](params, "transform") |
| 1852 |
if err != nil { |
| 1853 |
return err |
| 1854 |
} |
| 1855 |
case "remove": |
| 1856 |
tags, err := golang.FormAnswer[string](params, "tags") |
| 1857 |
if err != nil { |
| 1858 |
return err |
| 1859 |
} |
| 1860 |
args.Remove, err = golang.SanitizeTags(tags) |
| 1861 |
if err != nil { |
| 1862 |
return err |
| 1863 |
} |
| 1864 |
default: |
| 1865 |
return fmt.Errorf("unsupported modify tags operation: %s", args.Modification) |
| 1866 |
} |
| 1867 |
} |
| 1868 |
|
| 1869 |
m := &modifytags.Modification{ |
| 1870 |
Clear: args.Clear, |
| 1871 |
ClearOptions: args.ClearOptions, |
| 1872 |
ValueFormat: args.ValueFormat, |
| 1873 |
Overwrite: args.Overwrite, |
| 1874 |
} |
| 1875 |
|
| 1876 |
transform, err := parseTransform(args.Transform) |
| 1877 |
if err != nil { |
| 1878 |
return err |
| 1879 |
} |
| 1880 |
m.Transform = transform |
| 1881 |
|
| 1882 |
|
| 1883 |
|
| 1884 |
if args.Add != "" { |
| 1885 |
countAddStructTags.Inc() |
| 1886 |
m.Add = strings.Split(args.Add, ",") |
| 1887 |
} else if args.Clear { |
| 1888 |
countRemoveStructTags.Inc() |
| 1889 |
} |
| 1890 |
if args.AddOptions != "" { |
| 1891 |
if options, err := optionsStringToMap(args.AddOptions); err != nil { |
| 1892 |
return err |
| 1893 |
} else { |
| 1894 |
m.AddOptions = options |
| 1895 |
} |
| 1896 |
} |
| 1897 |
if args.Remove != "" { |
| 1898 |
m.Remove = strings.Split(args.Remove, ",") |
| 1899 |
} |
| 1900 |
if args.RemoveOptions != "" { |
| 1901 |
if options, err := optionsStringToMap(args.RemoveOptions); err != nil { |
| 1902 |
return err |
| 1903 |
} else { |
| 1904 |
m.RemoveOptions = options |
| 1905 |
} |
| 1906 |
} |
| 1907 |
fh, err := deps.snapshot.ReadFile(ctx, args.URI) |
| 1908 |
if err != nil { |
| 1909 |
return err |
| 1910 |
} |
| 1911 |
changes, err := golang.ModifyTags(ctx, deps.snapshot, fh, args, m) |
| 1912 |
if err != nil { |
| 1913 |
return err |
| 1914 |
} |
| 1915 |
return applyChanges(ctx, c.s.client, changes) |
| 1916 |
}) |
| 1917 |
} |
| 1918 |
|
| 1919 |
func parseTransform(input string) (modifytags.Transform, error) { |
| 1920 |
switch input { |
| 1921 |
case "camelcase": |
| 1922 |
return modifytags.CamelCase, nil |
| 1923 |
case "lispcase": |
| 1924 |
return modifytags.LispCase, nil |
| 1925 |
case "pascalcase": |
| 1926 |
return modifytags.PascalCase, nil |
| 1927 |
case "titlecase": |
| 1928 |
return modifytags.TitleCase, nil |
| 1929 |
case "keep": |
| 1930 |
return modifytags.Keep, nil |
| 1931 |
case "": |
| 1932 |
fallthrough |
| 1933 |
case "snakecase": |
| 1934 |
return modifytags.SnakeCase, nil |
| 1935 |
default: |
| 1936 |
return modifytags.SnakeCase, fmt.Errorf("invalid Transform value") |
| 1937 |
} |
| 1938 |
} |
| 1939 |
|
| 1940 |
func (c *commandHandler) MoveType(ctx context.Context, args command.MoveTypeArgs) error { |
| 1941 |
err := c.run(ctx, commandConfig{ |
| 1942 |
forURI: args.Location.URI, |
| 1943 |
}, func(ctx context.Context, deps commandDeps) error { |
| 1944 |
changes, err := golang.MoveType(ctx, deps.fh, deps.snapshot, args.Location, "newpkg/new.go") |
| 1945 |
if err != nil { |
| 1946 |
return err |
| 1947 |
} |
| 1948 |
return applyChanges(ctx, c.s.client, changes) |
| 1949 |
}) |
| 1950 |
return err |
| 1951 |
} |