| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package server |
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
import ( |
| 11 |
"context" |
| 12 |
"encoding/json" |
| 13 |
"errors" |
| 14 |
"fmt" |
| 15 |
"go/build" |
| 16 |
"os" |
| 17 |
"path" |
| 18 |
"path/filepath" |
| 19 |
"slices" |
| 20 |
"sort" |
| 21 |
"strings" |
| 22 |
"sync" |
| 23 |
|
| 24 |
"golang.org/x/telemetry/counter" |
| 25 |
"golang.org/x/tools/gopls/internal/cache" |
| 26 |
"golang.org/x/tools/gopls/internal/debug" |
| 27 |
debuglog "golang.org/x/tools/gopls/internal/debug/log" |
| 28 |
"golang.org/x/tools/gopls/internal/file" |
| 29 |
"golang.org/x/tools/gopls/internal/filecache" |
| 30 |
"golang.org/x/tools/gopls/internal/filewatcher" |
| 31 |
"golang.org/x/tools/gopls/internal/protocol" |
| 32 |
"golang.org/x/tools/gopls/internal/protocol/semtok" |
| 33 |
"golang.org/x/tools/gopls/internal/settings" |
| 34 |
"golang.org/x/tools/gopls/internal/telemetry" |
| 35 |
"golang.org/x/tools/gopls/internal/util/bug" |
| 36 |
"golang.org/x/tools/gopls/internal/util/goversion" |
| 37 |
"golang.org/x/tools/gopls/internal/util/moremaps" |
| 38 |
"golang.org/x/tools/gopls/internal/util/moreslices" |
| 39 |
"golang.org/x/tools/internal/event" |
| 40 |
"golang.org/x/tools/internal/jsonrpc2" |
| 41 |
) |
| 42 |
|
| 43 |
func (s *server) Initialize(ctx context.Context, params *protocol.ParamInitialize) (*protocol.InitializeResult, error) { |
| 44 |
ctx, done := event.Start(ctx, "server.Initialize") |
| 45 |
defer done() |
| 46 |
|
| 47 |
var clientName string |
| 48 |
if params != nil && params.ClientInfo != nil { |
| 49 |
clientName = params.ClientInfo.Name |
| 50 |
} |
| 51 |
recordClientInfo(clientName) |
| 52 |
|
| 53 |
s.stateMu.Lock() |
| 54 |
if s.state >= serverInitializing { |
| 55 |
defer s.stateMu.Unlock() |
| 56 |
return nil, fmt.Errorf("%w: initialize called while server in %v state", jsonrpc2.ErrInvalidRequest, s.state) |
| 57 |
} |
| 58 |
s.state = serverInitializing |
| 59 |
s.stateMu.Unlock() |
| 60 |
|
| 61 |
s.progress.SetSupportsWorkDoneProgress(params.Capabilities.Window.WorkDoneProgress) |
| 62 |
|
| 63 |
options := s.Options().Clone() |
| 64 |
|
| 65 |
defer func() { s.SetOptions(options) }() |
| 66 |
|
| 67 |
|
| 68 |
{ |
| 69 |
res, errs := options.Set(params.InitializationOptions) |
| 70 |
s.handleOptionResult(ctx, res, errs) |
| 71 |
} |
| 72 |
options.ForClientCapabilities(params.ClientInfo, params.Capabilities) |
| 73 |
|
| 74 |
if options.MaxFileCacheBytes > 0 { |
| 75 |
filecache.SetBudget(options.MaxFileCacheBytes) |
| 76 |
} |
| 77 |
|
| 78 |
if options.ShowBugReports { |
| 79 |
|
| 80 |
bug.Handle(func(b bug.Bug) { |
| 81 |
msg := &protocol.ShowMessageParams{ |
| 82 |
Type: protocol.Error, |
| 83 |
Message: fmt.Sprintf("A bug occurred on the server: %s\nLocation:%s", b.Description, b.Key), |
| 84 |
} |
| 85 |
go s.eventuallyShowMessage(context.Background(), msg) |
| 86 |
}) |
| 87 |
} |
| 88 |
|
| 89 |
folders := params.WorkspaceFolders |
| 90 |
if len(folders) == 0 { |
| 91 |
if params.RootURI != "" { |
| 92 |
folders = []protocol.WorkspaceFolder{{ |
| 93 |
URI: string(params.RootURI), |
| 94 |
Name: path.Base(params.RootURI.Path()), |
| 95 |
}} |
| 96 |
} |
| 97 |
} |
| 98 |
s.pendingFolders = append(s.pendingFolders, folders...) |
| 99 |
|
| 100 |
var codeActionProvider any = true |
| 101 |
if ca := params.Capabilities.TextDocument.CodeAction; len(ca.CodeActionLiteralSupport.CodeActionKind.ValueSet) > 0 { |
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
codeActionProvider = &protocol.CodeActionOptions{ |
| 107 |
CodeActionKinds: s.getSupportedCodeActions(), |
| 108 |
ResolveProvider: true, |
| 109 |
} |
| 110 |
} |
| 111 |
|
| 112 |
var diagnosticProvider *protocol.Or_ServerCapabilities_diagnosticProvider |
| 113 |
if options.PullDiagnostics { |
| 114 |
diagnosticProvider = &protocol.Or_ServerCapabilities_diagnosticProvider{ |
| 115 |
Value: protocol.DiagnosticOptions{ |
| 116 |
InterFileDependencies: true, |
| 117 |
WorkspaceDiagnostics: false, |
| 118 |
}, |
| 119 |
} |
| 120 |
} |
| 121 |
|
| 122 |
var renameOpts any = true |
| 123 |
if r := params.Capabilities.TextDocument.Rename; r != nil && r.PrepareSupport { |
| 124 |
renameOpts = protocol.RenameOptions{ |
| 125 |
PrepareProvider: r.PrepareSupport, |
| 126 |
} |
| 127 |
} |
| 128 |
|
| 129 |
var semanticTokenProvider any |
| 130 |
if options.SemanticTokens || options.ConfigurationSupported { |
| 131 |
|
| 132 |
|
| 133 |
|
| 134 |
|
| 135 |
|
| 136 |
|
| 137 |
|
| 138 |
|
| 139 |
|
| 140 |
|
| 141 |
|
| 142 |
|
| 143 |
|
| 144 |
|
| 145 |
|
| 146 |
|
| 147 |
|
| 148 |
|
| 149 |
|
| 150 |
|
| 151 |
|
| 152 |
|
| 153 |
|
| 154 |
|
| 155 |
|
| 156 |
|
| 157 |
|
| 158 |
|
| 159 |
|
| 160 |
|
| 161 |
|
| 162 |
|
| 163 |
|
| 164 |
|
| 165 |
|
| 166 |
|
| 167 |
|
| 168 |
|
| 169 |
|
| 170 |
|
| 171 |
|
| 172 |
|
| 173 |
|
| 174 |
|
| 175 |
|
| 176 |
|
| 177 |
semanticTokenProvider = protocol.SemanticTokensOptions{ |
| 178 |
Range: &protocol.Or_SemanticTokensOptions_range{Value: true}, |
| 179 |
Full: &protocol.Or_SemanticTokensOptions_full{Value: true}, |
| 180 |
Legend: protocol.SemanticTokensLegend{ |
| 181 |
TokenTypes: moreslices.ConvertStrings[string](semtok.Types), |
| 182 |
TokenModifiers: moreslices.ConvertStrings[string](semtok.Modifiers), |
| 183 |
}, |
| 184 |
} |
| 185 |
|
| 186 |
|
| 187 |
|
| 188 |
|
| 189 |
|
| 190 |
|
| 191 |
} |
| 192 |
|
| 193 |
versionInfo := debug.VersionInfo() |
| 194 |
|
| 195 |
goplsVersion, err := json.Marshal(versionInfo) |
| 196 |
if err != nil { |
| 197 |
return nil, err |
| 198 |
} |
| 199 |
|
| 200 |
return &protocol.InitializeResult{ |
| 201 |
Capabilities: protocol.ServerCapabilities{ |
| 202 |
CallHierarchyProvider: &protocol.Or_ServerCapabilities_callHierarchyProvider{Value: true}, |
| 203 |
CodeActionProvider: codeActionProvider, |
| 204 |
CodeLensProvider: &protocol.CodeLensOptions{}, |
| 205 |
CompletionProvider: &protocol.CompletionOptions{ |
| 206 |
TriggerCharacters: []string{"."}, |
| 207 |
}, |
| 208 |
DefinitionProvider: &protocol.Or_ServerCapabilities_definitionProvider{Value: true}, |
| 209 |
TypeDefinitionProvider: &protocol.Or_ServerCapabilities_typeDefinitionProvider{Value: true}, |
| 210 |
ImplementationProvider: &protocol.Or_ServerCapabilities_implementationProvider{Value: true}, |
| 211 |
DocumentFormattingProvider: &protocol.Or_ServerCapabilities_documentFormattingProvider{Value: true}, |
| 212 |
DocumentSymbolProvider: &protocol.Or_ServerCapabilities_documentSymbolProvider{Value: true}, |
| 213 |
WorkspaceSymbolProvider: &protocol.Or_ServerCapabilities_workspaceSymbolProvider{Value: true}, |
| 214 |
ExecuteCommandProvider: &protocol.ExecuteCommandOptions{ |
| 215 |
Commands: protocol.NonNilSlice(options.SupportedCommands), |
| 216 |
}, |
| 217 |
FoldingRangeProvider: &protocol.Or_ServerCapabilities_foldingRangeProvider{Value: true}, |
| 218 |
HoverProvider: &protocol.Or_ServerCapabilities_hoverProvider{Value: true}, |
| 219 |
DocumentHighlightProvider: &protocol.Or_ServerCapabilities_documentHighlightProvider{Value: true}, |
| 220 |
DocumentLinkProvider: &protocol.DocumentLinkOptions{}, |
| 221 |
InlayHintProvider: protocol.InlayHintOptions{}, |
| 222 |
DiagnosticProvider: diagnosticProvider, |
| 223 |
ReferencesProvider: &protocol.Or_ServerCapabilities_referencesProvider{Value: true}, |
| 224 |
RenameProvider: renameOpts, |
| 225 |
SelectionRangeProvider: &protocol.Or_ServerCapabilities_selectionRangeProvider{Value: true}, |
| 226 |
SemanticTokensProvider: semanticTokenProvider, |
| 227 |
SignatureHelpProvider: &protocol.SignatureHelpOptions{ |
| 228 |
TriggerCharacters: []string{"(", ","}, |
| 229 |
|
| 230 |
|
| 231 |
RetriggerCharacters: []string{")"}, |
| 232 |
}, |
| 233 |
TextDocumentSync: &protocol.TextDocumentSyncOptions{ |
| 234 |
Change: protocol.Incremental, |
| 235 |
OpenClose: true, |
| 236 |
Save: &protocol.SaveOptions{ |
| 237 |
IncludeText: false, |
| 238 |
}, |
| 239 |
}, |
| 240 |
TypeHierarchyProvider: &protocol.Or_ServerCapabilities_typeHierarchyProvider{Value: true}, |
| 241 |
Workspace: &protocol.WorkspaceOptions{ |
| 242 |
WorkspaceFolders: &protocol.WorkspaceFolders5Gn{ |
| 243 |
Supported: true, |
| 244 |
ChangeNotifications: "workspace/didChangeWorkspaceFolders", |
| 245 |
}, |
| 246 |
FileOperations: &protocol.FileOperationOptions{ |
| 247 |
DidCreate: &protocol.FileOperationRegistrationOptions{ |
| 248 |
Filters: []protocol.FileOperationFilter{{ |
| 249 |
Scheme: "file", |
| 250 |
|
| 251 |
Pattern: protocol.FileOperationPattern{Glob: "**/*.go"}, |
| 252 |
}}, |
| 253 |
}, |
| 254 |
}, |
| 255 |
}, |
| 256 |
Experimental: map[string]any{ |
| 257 |
|
| 258 |
|
| 259 |
|
| 260 |
|
| 261 |
|
| 262 |
|
| 263 |
|
| 264 |
|
| 265 |
|
| 266 |
|
| 267 |
|
| 268 |
"interactiveResolveProvider": protocol.InteractiveResolveOptions{ |
| 269 |
Kinds: []string{"command"}, |
| 270 |
}, |
| 271 |
}, |
| 272 |
}, |
| 273 |
ServerInfo: &protocol.ServerInfo{ |
| 274 |
Name: "gopls", |
| 275 |
Version: string(goplsVersion), |
| 276 |
}, |
| 277 |
}, nil |
| 278 |
} |
| 279 |
|
| 280 |
func (s *server) Initialized(ctx context.Context, params *protocol.InitializedParams) error { |
| 281 |
ctx, done := event.Start(ctx, "server.Initialized") |
| 282 |
defer done() |
| 283 |
|
| 284 |
s.stateMu.Lock() |
| 285 |
if s.state >= serverInitialized { |
| 286 |
defer s.stateMu.Unlock() |
| 287 |
return fmt.Errorf("%w: initialized called while server in %v state", jsonrpc2.ErrInvalidRequest, s.state) |
| 288 |
} |
| 289 |
s.state = serverInitialized |
| 290 |
s.stateMu.Unlock() |
| 291 |
|
| 292 |
for _, not := range s.notifications { |
| 293 |
s.client.ShowMessage(ctx, not) |
| 294 |
} |
| 295 |
s.notifications = nil |
| 296 |
|
| 297 |
s.addFolders(ctx, s.pendingFolders) |
| 298 |
|
| 299 |
s.pendingFolders = nil |
| 300 |
s.checkViewGoVersions() |
| 301 |
|
| 302 |
var registrations []protocol.Registration |
| 303 |
options := s.Options() |
| 304 |
if options.ConfigurationSupported && options.DynamicConfigurationSupported { |
| 305 |
|
| 306 |
|
| 307 |
|
| 308 |
registrations = append(registrations, protocol.Registration{ |
| 309 |
ID: "workspace/didChangeConfiguration", |
| 310 |
Method: "workspace/didChangeConfiguration", |
| 311 |
}) |
| 312 |
} |
| 313 |
if len(registrations) > 0 { |
| 314 |
if err := s.client.RegisterCapability(ctx, &protocol.RegistrationParams{ |
| 315 |
Registrations: registrations, |
| 316 |
}); err != nil { |
| 317 |
return err |
| 318 |
} |
| 319 |
} |
| 320 |
|
| 321 |
|
| 322 |
|
| 323 |
go s.maybePromptForTelemetry(ctx, options.TelemetryPrompt) |
| 324 |
|
| 325 |
return nil |
| 326 |
} |
| 327 |
|
| 328 |
|
| 329 |
|
| 330 |
|
| 331 |
|
| 332 |
func (s *server) checkViewGoVersions() { |
| 333 |
oldestVersion, fromBuild := go1Point(), true |
| 334 |
for _, view := range s.session.Views() { |
| 335 |
viewVersion := view.GoVersion() |
| 336 |
if oldestVersion == -1 || viewVersion < oldestVersion { |
| 337 |
oldestVersion, fromBuild = viewVersion, false |
| 338 |
} |
| 339 |
if viewVersion >= 0 { |
| 340 |
counter.Inc(fmt.Sprintf("gopls/goversion:1.%d", viewVersion)) |
| 341 |
} |
| 342 |
} |
| 343 |
|
| 344 |
if msg, isError := goversion.Message(oldestVersion, fromBuild); msg != "" { |
| 345 |
mType := protocol.Warning |
| 346 |
if isError { |
| 347 |
mType = protocol.Error |
| 348 |
} |
| 349 |
s.eventuallyShowMessage(context.Background(), &protocol.ShowMessageParams{ |
| 350 |
Type: mType, |
| 351 |
Message: msg, |
| 352 |
}) |
| 353 |
} |
| 354 |
} |
| 355 |
|
| 356 |
|
| 357 |
|
| 358 |
|
| 359 |
|
| 360 |
func go1Point() int { |
| 361 |
for _, tag := range slices.Backward(build.Default.ReleaseTags) { |
| 362 |
var version int |
| 363 |
if _, err := fmt.Sscanf(tag, "go1.%d", &version); err != nil { |
| 364 |
continue |
| 365 |
} |
| 366 |
return version |
| 367 |
} |
| 368 |
return -1 |
| 369 |
} |
| 370 |
|
| 371 |
|
| 372 |
|
| 373 |
|
| 374 |
|
| 375 |
func (s *server) addFolders(ctx context.Context, folders []protocol.WorkspaceFolder) { |
| 376 |
originalViews := len(s.session.Views()) |
| 377 |
viewErrors := make(map[protocol.URI]error) |
| 378 |
|
| 379 |
|
| 380 |
|
| 381 |
|
| 382 |
|
| 383 |
|
| 384 |
|
| 385 |
|
| 386 |
var filtered []protocol.WorkspaceFolder |
| 387 |
for _, f := range folders { |
| 388 |
uri, err := protocol.ParseDocumentURI(f.URI) |
| 389 |
if err != nil { |
| 390 |
debuglog.Warning.Logf(ctx, "skip adding virtual folder %q - invalid folder URI: %v", f.Name, err) |
| 391 |
continue |
| 392 |
} |
| 393 |
if s.session.HasView(uri) { |
| 394 |
debuglog.Warning.Logf(ctx, "skip adding the already added folder %q - its view has been created before", f.Name) |
| 395 |
continue |
| 396 |
} |
| 397 |
filtered = append(filtered, f) |
| 398 |
} |
| 399 |
folders = filtered |
| 400 |
|
| 401 |
var ndiagnose sync.WaitGroup |
| 402 |
if s.Options().VerboseWorkDoneProgress { |
| 403 |
work := s.progress.Start(ctx, DiagnosticWorkTitle(FromInitialWorkspaceLoad), "Calculating diagnostics for initial workspace load...", nil, nil) |
| 404 |
defer func() { |
| 405 |
go func() { |
| 406 |
ndiagnose.Wait() |
| 407 |
work.End(ctx, "Done.") |
| 408 |
}() |
| 409 |
}() |
| 410 |
} |
| 411 |
|
| 412 |
var nsnapshots sync.WaitGroup |
| 413 |
for _, folder := range folders { |
| 414 |
uri, err := protocol.ParseDocumentURI(folder.URI) |
| 415 |
if err != nil { |
| 416 |
viewErrors[folder.URI] = fmt.Errorf("invalid folder URI: %v", err) |
| 417 |
continue |
| 418 |
} |
| 419 |
work := s.progress.Start(ctx, "Setting up workspace", "Loading packages...", nil, nil) |
| 420 |
snapshot, release, err := s.addView(ctx, folder.Name, uri) |
| 421 |
if err != nil { |
| 422 |
if err == cache.ErrViewExists { |
| 423 |
continue |
| 424 |
} |
| 425 |
viewErrors[folder.URI] = err |
| 426 |
work.End(ctx, fmt.Sprintf("Error loading packages: %s", err)) |
| 427 |
continue |
| 428 |
} |
| 429 |
|
| 430 |
|
| 431 |
|
| 432 |
initialized := make(chan struct{}) |
| 433 |
nsnapshots.Add(1) |
| 434 |
go func() { |
| 435 |
snapshot.AwaitInitialized(ctx) |
| 436 |
work.End(ctx, "Finished loading packages.") |
| 437 |
nsnapshots.Done() |
| 438 |
close(initialized) |
| 439 |
}() |
| 440 |
|
| 441 |
|
| 442 |
ndiagnose.Go(func() { |
| 443 |
s.diagnoseSnapshot(snapshot.BackgroundContext(), snapshot, nil, 0) |
| 444 |
<-initialized |
| 445 |
release() |
| 446 |
}) |
| 447 |
} |
| 448 |
|
| 449 |
|
| 450 |
|
| 451 |
nsnapshots.Wait() |
| 452 |
|
| 453 |
|
| 454 |
if err := s.updateWatchedDirectories(ctx); err != nil { |
| 455 |
event.Error(ctx, "failed to register for file watching notifications", err) |
| 456 |
} |
| 457 |
|
| 458 |
|
| 459 |
if len(viewErrors) > 0 { |
| 460 |
var errMsg strings.Builder |
| 461 |
fmt.Fprintf(&errMsg, "Error loading workspace folders (expected %v, got %v)\n", len(folders), len(s.session.Views())-originalViews) |
| 462 |
for uri, err := range viewErrors { |
| 463 |
fmt.Fprintf(&errMsg, "failed to load view for %s: %v\n", uri, err) |
| 464 |
} |
| 465 |
showMessage(ctx, s.client, protocol.Error, errMsg.String()) |
| 466 |
} |
| 467 |
} |
| 468 |
|
| 469 |
|
| 470 |
|
| 471 |
|
| 472 |
func (s *server) updateWatchedDirectories(ctx context.Context) error { |
| 473 |
patterns := s.session.FileWatchingGlobPatterns(ctx) |
| 474 |
|
| 475 |
|
| 476 |
|
| 477 |
|
| 478 |
|
| 479 |
|
| 480 |
|
| 481 |
|
| 482 |
|
| 483 |
if err := s.updateServerSideWatcher(ctx, patterns); err != nil { |
| 484 |
return fmt.Errorf("failed to update server-side file watcher: %w", err) |
| 485 |
} |
| 486 |
|
| 487 |
s.watchedGlobPatternsMu.Lock() |
| 488 |
defer s.watchedGlobPatternsMu.Unlock() |
| 489 |
|
| 490 |
|
| 491 |
if moremaps.SameKeys(s.watchedGlobPatterns, patterns) { |
| 492 |
return nil |
| 493 |
} |
| 494 |
|
| 495 |
|
| 496 |
|
| 497 |
|
| 498 |
|
| 499 |
|
| 500 |
prevID := s.watchRegistrationCount - 1 |
| 501 |
if err := s.registerWatchedDirectoriesLocked(ctx, patterns); err != nil { |
| 502 |
return err |
| 503 |
} |
| 504 |
if prevID >= 0 { |
| 505 |
return s.client.UnregisterCapability(ctx, &protocol.UnregistrationParams{ |
| 506 |
Unregisterations: []protocol.Unregistration{{ |
| 507 |
ID: watchedFilesCapabilityID(prevID), |
| 508 |
Method: "workspace/didChangeWatchedFiles", |
| 509 |
}}, |
| 510 |
}) |
| 511 |
} |
| 512 |
return nil |
| 513 |
} |
| 514 |
|
| 515 |
|
| 516 |
|
| 517 |
|
| 518 |
func (s *server) updateServerSideWatcher(ctx context.Context, patterns map[protocol.RelativePattern]unit) error { |
| 519 |
wantMode := s.Options().FileWatcher |
| 520 |
s.fileWatcherMu.Lock() |
| 521 |
defer s.fileWatcherMu.Unlock() |
| 522 |
|
| 523 |
|
| 524 |
if s.fileWatcher != nil && s.fileWatcher.Mode() != wantMode { |
| 525 |
if err := s.fileWatcher.Close(); err != nil { |
| 526 |
event.Error(ctx, "failed to close the file watcher", err) |
| 527 |
} |
| 528 |
s.fileWatcher = nil |
| 529 |
} |
| 530 |
|
| 531 |
if wantMode == settings.FileWatcherOff { |
| 532 |
return nil |
| 533 |
} |
| 534 |
|
| 535 |
|
| 536 |
if s.fileWatcher == nil { |
| 537 |
|
| 538 |
watcherCtx := context.WithoutCancel(ctx) |
| 539 |
onChange := func(events []protocol.FileEvent) { |
| 540 |
modifications := make([]file.Modification, len(events)) |
| 541 |
for i, e := range events { |
| 542 |
modifications[i] = file.Modification{ |
| 543 |
URI: e.URI, |
| 544 |
Action: changeTypeToFileAction(e.Type), |
| 545 |
OnDisk: true, |
| 546 |
} |
| 547 |
} |
| 548 |
if err := s.didModifyFiles(watcherCtx, FromDidChangeWatchedFiles, modifications...); err != nil { |
| 549 |
event.Error(watcherCtx, "failed to process file changes", err) |
| 550 |
} |
| 551 |
} |
| 552 |
onErr := func(err error) { |
| 553 |
event.Error(watcherCtx, "file watcher error", err) |
| 554 |
} |
| 555 |
|
| 556 |
w, err := filewatcher.New(wantMode, nil, onChange, onErr) |
| 557 |
if err != nil { |
| 558 |
return err |
| 559 |
} |
| 560 |
s.fileWatcher = w |
| 561 |
} |
| 562 |
|
| 563 |
|
| 564 |
dirs := make(map[string]struct{}) |
| 565 |
for pattern := range patterns { |
| 566 |
if pattern.BaseURI != "" { |
| 567 |
dirs[pattern.BaseURI.Path()] = struct{}{} |
| 568 |
} |
| 569 |
} |
| 570 |
for dir := range dirs { |
| 571 |
if err := s.fileWatcher.WatchDir(dir); err != nil { |
| 572 |
|
| 573 |
event.Log(ctx, fmt.Sprintf("failed to watch directory %s: %v", dir, err)) |
| 574 |
} |
| 575 |
} |
| 576 |
return nil |
| 577 |
} |
| 578 |
|
| 579 |
func watchedFilesCapabilityID(id int) string { |
| 580 |
return fmt.Sprintf("workspace/didChangeWatchedFiles-%d", id) |
| 581 |
} |
| 582 |
|
| 583 |
|
| 584 |
|
| 585 |
|
| 586 |
func (s *server) registerWatchedDirectoriesLocked(ctx context.Context, patterns map[protocol.RelativePattern]unit) error { |
| 587 |
if !s.Options().DynamicWatchedFilesSupported { |
| 588 |
return nil |
| 589 |
} |
| 590 |
|
| 591 |
supportsRelativePatterns := s.Options().RelativePatternsSupported |
| 592 |
|
| 593 |
s.watchedGlobPatterns = patterns |
| 594 |
watchers := make([]protocol.FileSystemWatcher, 0, len(patterns)) |
| 595 |
val := protocol.WatchChange | protocol.WatchDelete | protocol.WatchCreate |
| 596 |
for pattern := range patterns { |
| 597 |
var value any |
| 598 |
if supportsRelativePatterns && pattern.BaseURI != "" { |
| 599 |
value = pattern |
| 600 |
} else { |
| 601 |
p := pattern.Pattern |
| 602 |
if pattern.BaseURI != "" { |
| 603 |
p = path.Join(filepath.ToSlash(pattern.BaseURI.Path()), p) |
| 604 |
} |
| 605 |
value = p |
| 606 |
} |
| 607 |
watchers = append(watchers, protocol.FileSystemWatcher{ |
| 608 |
GlobPattern: protocol.GlobPattern{Value: value}, |
| 609 |
Kind: &val, |
| 610 |
}) |
| 611 |
} |
| 612 |
|
| 613 |
if err := s.client.RegisterCapability(ctx, &protocol.RegistrationParams{ |
| 614 |
Registrations: []protocol.Registration{{ |
| 615 |
ID: watchedFilesCapabilityID(s.watchRegistrationCount), |
| 616 |
Method: "workspace/didChangeWatchedFiles", |
| 617 |
RegisterOptions: protocol.DidChangeWatchedFilesRegistrationOptions{ |
| 618 |
Watchers: watchers, |
| 619 |
}, |
| 620 |
}}, |
| 621 |
}); err != nil { |
| 622 |
return err |
| 623 |
} |
| 624 |
s.watchRegistrationCount++ |
| 625 |
return nil |
| 626 |
} |
| 627 |
|
| 628 |
|
| 629 |
|
| 630 |
|
| 631 |
func (s *server) Options() *settings.Options { |
| 632 |
s.optionsMu.Lock() |
| 633 |
defer s.optionsMu.Unlock() |
| 634 |
return s.options |
| 635 |
} |
| 636 |
|
| 637 |
|
| 638 |
|
| 639 |
|
| 640 |
func (s *server) SetOptions(opts *settings.Options) { |
| 641 |
s.optionsMu.Lock() |
| 642 |
defer s.optionsMu.Unlock() |
| 643 |
s.options = opts |
| 644 |
} |
| 645 |
|
| 646 |
func (s *server) newFolder(ctx context.Context, folder protocol.DocumentURI, name string, opts *settings.Options) (*cache.Folder, error) { |
| 647 |
env, err := cache.FetchGoEnv(ctx, folder, opts) |
| 648 |
if err != nil { |
| 649 |
return nil, err |
| 650 |
} |
| 651 |
|
| 652 |
|
| 653 |
switch { |
| 654 |
case env.GOTOOLCHAIN == "auto" || strings.Contains(env.GOTOOLCHAIN, "+auto"): |
| 655 |
counter.Inc("gopls/gotoolchain:auto") |
| 656 |
case env.GOTOOLCHAIN == "path" || strings.Contains(env.GOTOOLCHAIN, "+path"): |
| 657 |
counter.Inc("gopls/gotoolchain:path") |
| 658 |
case env.GOTOOLCHAIN == "local": |
| 659 |
counter.Inc("gopls/gotoolchain:local") |
| 660 |
default: |
| 661 |
counter.Inc("gopls/gotoolchain:other") |
| 662 |
} |
| 663 |
|
| 664 |
|
| 665 |
|
| 666 |
|
| 667 |
|
| 668 |
|
| 669 |
|
| 670 |
|
| 671 |
if env.EffectiveGOPACKAGESDRIVER != "" { |
| 672 |
counter.Inc("gopls/gopackagesdriver") |
| 673 |
} |
| 674 |
|
| 675 |
return &cache.Folder{ |
| 676 |
Dir: folder, |
| 677 |
Name: name, |
| 678 |
Options: opts, |
| 679 |
Env: *env, |
| 680 |
}, nil |
| 681 |
} |
| 682 |
|
| 683 |
|
| 684 |
|
| 685 |
|
| 686 |
|
| 687 |
func (s *server) fetchFolderOptions(ctx context.Context, folder protocol.DocumentURI) (*settings.Options, error) { |
| 688 |
opts := s.Options() |
| 689 |
if !opts.ConfigurationSupported { |
| 690 |
return opts, nil |
| 691 |
} |
| 692 |
var scopeURI *string |
| 693 |
if folder != "" { |
| 694 |
scope := string(folder) |
| 695 |
scopeURI = &scope |
| 696 |
} |
| 697 |
configs, err := s.client.Configuration(ctx, &protocol.ParamConfiguration{ |
| 698 |
Items: []protocol.ConfigurationItem{{ |
| 699 |
ScopeURI: scopeURI, |
| 700 |
Section: "gopls", |
| 701 |
}}, |
| 702 |
}, |
| 703 |
) |
| 704 |
if err != nil { |
| 705 |
return nil, fmt.Errorf("failed to get workspace configuration from client (%s): %v", folder, err) |
| 706 |
} |
| 707 |
|
| 708 |
opts = opts.Clone() |
| 709 |
for _, config := range configs { |
| 710 |
res, errs := opts.Set(config) |
| 711 |
s.handleOptionResult(ctx, res, errs) |
| 712 |
} |
| 713 |
return opts, nil |
| 714 |
} |
| 715 |
|
| 716 |
func (s *server) eventuallyShowMessage(ctx context.Context, msg *protocol.ShowMessageParams) { |
| 717 |
s.stateMu.Lock() |
| 718 |
defer s.stateMu.Unlock() |
| 719 |
if s.state == serverInitialized { |
| 720 |
_ = s.client.ShowMessage(ctx, msg) |
| 721 |
} |
| 722 |
s.notifications = append(s.notifications, msg) |
| 723 |
} |
| 724 |
|
| 725 |
func (s *server) handleOptionResult(ctx context.Context, applied []telemetry.CounterPath, optionErrors []error) { |
| 726 |
for _, path := range applied { |
| 727 |
path = append(settings.CounterPath{"gopls", "setting"}, path...) |
| 728 |
counter.Inc(path.FullName()) |
| 729 |
} |
| 730 |
|
| 731 |
var warnings, errs []string |
| 732 |
for _, err := range optionErrors { |
| 733 |
if err == nil { |
| 734 |
panic("nil error passed to handleOptionErrors") |
| 735 |
} |
| 736 |
if errors.Is(err, new(settings.SoftError)) { |
| 737 |
warnings = append(warnings, err.Error()) |
| 738 |
} else { |
| 739 |
errs = append(errs, err.Error()) |
| 740 |
} |
| 741 |
} |
| 742 |
|
| 743 |
|
| 744 |
|
| 745 |
|
| 746 |
|
| 747 |
|
| 748 |
|
| 749 |
var msgs []string |
| 750 |
msgType := protocol.Warning |
| 751 |
if len(errs) > 0 { |
| 752 |
msgType = protocol.Error |
| 753 |
sort.Strings(errs) |
| 754 |
msgs = append(msgs, errs...) |
| 755 |
} |
| 756 |
if len(warnings) > 0 { |
| 757 |
sort.Strings(warnings) |
| 758 |
msgs = append(msgs, warnings...) |
| 759 |
} |
| 760 |
|
| 761 |
if len(msgs) > 0 { |
| 762 |
|
| 763 |
combined := "Invalid settings: " + strings.Join(msgs, "; ") |
| 764 |
params := &protocol.ShowMessageParams{ |
| 765 |
Type: msgType, |
| 766 |
Message: combined, |
| 767 |
} |
| 768 |
s.eventuallyShowMessage(ctx, params) |
| 769 |
} |
| 770 |
} |
| 771 |
|
| 772 |
|
| 773 |
|
| 774 |
func (s *server) Shutdown(ctx context.Context) error { |
| 775 |
ctx, done := event.Start(ctx, "server.Shutdown") |
| 776 |
defer done() |
| 777 |
|
| 778 |
s.stateMu.Lock() |
| 779 |
defer s.stateMu.Unlock() |
| 780 |
if s.state < serverInitialized { |
| 781 |
event.Log(ctx, "server shutdown without initialization") |
| 782 |
} |
| 783 |
if s.state != serverShutDown { |
| 784 |
|
| 785 |
if s.web != nil { |
| 786 |
s.web.server.Shutdown(ctx) |
| 787 |
} |
| 788 |
|
| 789 |
|
| 790 |
s.session.Shutdown(ctx) |
| 791 |
s.state = serverShutDown |
| 792 |
} |
| 793 |
return nil |
| 794 |
} |
| 795 |
|
| 796 |
func (s *server) Exit(ctx context.Context) error { |
| 797 |
ctx, done := event.Start(ctx, "server.Exit") |
| 798 |
defer done() |
| 799 |
|
| 800 |
s.stateMu.Lock() |
| 801 |
defer s.stateMu.Unlock() |
| 802 |
|
| 803 |
s.client.Close() |
| 804 |
|
| 805 |
if s.state != serverShutDown { |
| 806 |
|
| 807 |
os.Exit(1) |
| 808 |
} |
| 809 |
|
| 810 |
|
| 811 |
return nil |
| 812 |
} |
| 813 |
|
| 814 |
|
| 815 |
func recordClientInfo(clientName string) { |
| 816 |
|
| 817 |
|
| 818 |
for _, cli := range [...]struct { |
| 819 |
clientNamePrefix, telemetryKey string |
| 820 |
}{ |
| 821 |
{"Visual Studio Code - Insiders", "gopls/client:vscode-insiders"}, |
| 822 |
{"Visual Studio Code", "gopls/client:vscode"}, |
| 823 |
|
| 824 |
{"VSCodium", "gopls/client:vscodium"}, |
| 825 |
|
| 826 |
|
| 827 |
{"code-server", "gopls/client:code-server"}, |
| 828 |
|
| 829 |
|
| 830 |
{"Eglot", "gopls/client:eglot"}, |
| 831 |
|
| 832 |
|
| 833 |
{"govim", "gopls/client:govim"}, |
| 834 |
|
| 835 |
|
| 836 |
{"helix", "gopls/client:helix"}, |
| 837 |
|
| 838 |
|
| 839 |
|
| 840 |
{"Neovim", "gopls/client:neovim"}, |
| 841 |
|
| 842 |
|
| 843 |
{"coc.nvim", "gopls/client:coc.nvim"}, |
| 844 |
|
| 845 |
|
| 846 |
{"Sublime Text LSP", "gopls/client:sublimetext"}, |
| 847 |
|
| 848 |
{"Cursor", "gopls/client:cursor"}, |
| 849 |
|
| 850 |
|
| 851 |
{"Zed", "gopls/client:zed"}, |
| 852 |
|
| 853 |
|
| 854 |
{"Claude Code", "gopls/client:claude"}, |
| 855 |
|
| 856 |
|
| 857 |
{"Antigravity", "gopls/client:antigravity"}, |
| 858 |
{"Jetski", "gopls/client:antigravity"}, |
| 859 |
{"Windsurf", "gopls/client:windsurf"}, |
| 860 |
} { |
| 861 |
if strings.HasPrefix(clientName, cli.clientNamePrefix) { |
| 862 |
counter.Inc(cli.telemetryKey) |
| 863 |
return |
| 864 |
} |
| 865 |
} |
| 866 |
|
| 867 |
|
| 868 |
|
| 869 |
|
| 870 |
if clientName != "" { |
| 871 |
counter.New(fmt.Sprintf("gopls/client-other:%s", clientName)).Inc() |
| 872 |
} |
| 873 |
counter.Inc("gopls/client:other") |
| 874 |
} |