| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
package cmd |
| 9 |
|
| 10 |
import ( |
| 11 |
"context" |
| 12 |
"flag" |
| 13 |
"fmt" |
| 14 |
"log" |
| 15 |
"os" |
| 16 |
"path/filepath" |
| 17 |
"reflect" |
| 18 |
"sort" |
| 19 |
"strings" |
| 20 |
"sync" |
| 21 |
"text/tabwriter" |
| 22 |
"time" |
| 23 |
|
| 24 |
"golang.org/x/tools/gopls/internal/cache" |
| 25 |
"golang.org/x/tools/gopls/internal/debug" |
| 26 |
"golang.org/x/tools/gopls/internal/filecache" |
| 27 |
"golang.org/x/tools/gopls/internal/lsprpc" |
| 28 |
"golang.org/x/tools/gopls/internal/protocol" |
| 29 |
"golang.org/x/tools/gopls/internal/protocol/command" |
| 30 |
"golang.org/x/tools/gopls/internal/protocol/semtok" |
| 31 |
"golang.org/x/tools/gopls/internal/server" |
| 32 |
"golang.org/x/tools/gopls/internal/settings" |
| 33 |
"golang.org/x/tools/gopls/internal/tool" |
| 34 |
"golang.org/x/tools/gopls/internal/util/browser" |
| 35 |
"golang.org/x/tools/gopls/internal/util/bug" |
| 36 |
"golang.org/x/tools/gopls/internal/util/moreslices" |
| 37 |
"golang.org/x/tools/internal/diff" |
| 38 |
"golang.org/x/tools/internal/jsonrpc2" |
| 39 |
) |
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
type Application struct { |
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
tool.Profile |
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
Serve Serve |
| 53 |
|
| 54 |
|
| 55 |
options func(*settings.Options) |
| 56 |
|
| 57 |
|
| 58 |
Remote string `flag:"remote" help:"forward all commands to a remote lsp specified by this flag. With no special prefix, this is assumed to be a TCP address. If prefixed by 'unix;', the subsequent address is assumed to be a unix domain socket. If 'auto', or prefixed by 'auto;', the remote address is automatically resolved based on the executing environment."` |
| 59 |
|
| 60 |
|
| 61 |
Verbose bool `flag:"v,verbose" help:"verbose output"` |
| 62 |
|
| 63 |
|
| 64 |
VeryVerbose bool `flag:"vv,veryverbose" help:"very verbose output"` |
| 65 |
|
| 66 |
|
| 67 |
OTel string `flag:"otel" help:"export telemetry to specified OpenTelemetry collector address (e.g. http://localhost:4318)"` |
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
PrepareOptions func(*settings.Options) |
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
editFlags *EditFlags |
| 77 |
} |
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
type EditFlags struct { |
| 88 |
Write bool `flag:"w,write" help:"write edited content to source files"` |
| 89 |
Preserve bool `flag:"preserve" help:"with -write, make copies of original files"` |
| 90 |
Diff bool `flag:"d,diff" help:"display diffs instead of edited file content"` |
| 91 |
List bool `flag:"l,list" help:"display names of edited files"` |
| 92 |
} |
| 93 |
|
| 94 |
func (app *Application) verbose() bool { |
| 95 |
return app.Verbose || app.VeryVerbose |
| 96 |
} |
| 97 |
|
| 98 |
|
| 99 |
func New() *Application { |
| 100 |
app := &Application{ |
| 101 |
Serve: Serve{ |
| 102 |
RemoteListenTimeout: 1 * time.Minute, |
| 103 |
}, |
| 104 |
} |
| 105 |
app.Serve.app = app |
| 106 |
return app |
| 107 |
} |
| 108 |
|
| 109 |
|
| 110 |
func (app *Application) Name() string { return "gopls" } |
| 111 |
|
| 112 |
|
| 113 |
func (app *Application) Usage() string { return "" } |
| 114 |
|
| 115 |
|
| 116 |
func (app *Application) ShortHelp() string { |
| 117 |
return "" |
| 118 |
} |
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
func (app *Application) DetailedHelp(f *flag.FlagSet) { |
| 123 |
w := tabwriter.NewWriter(f.Output(), 0, 0, 2, ' ', 0) |
| 124 |
defer w.Flush() |
| 125 |
|
| 126 |
fmt.Fprint(w, ` |
| 127 |
gopls is a Go language server. |
| 128 |
|
| 129 |
It is typically used with an editor to provide language features. When no |
| 130 |
command is specified, gopls will default to the 'serve' command. The language |
| 131 |
features can also be accessed via the gopls command-line interface. |
| 132 |
|
| 133 |
For documentation of all its features, see: |
| 134 |
|
| 135 |
https://github.com/golang/tools/blob/master/gopls/doc/features |
| 136 |
|
| 137 |
Usage: |
| 138 |
gopls help [<subject>] |
| 139 |
|
| 140 |
Command: |
| 141 |
`) |
| 142 |
fmt.Fprint(w, "\nMain\t\n") |
| 143 |
for _, c := range app.mainCommands() { |
| 144 |
fmt.Fprintf(w, " %s\t%s\n", c.Name(), c.ShortHelp()) |
| 145 |
} |
| 146 |
fmt.Fprint(w, "\t\nFeatures\t\n") |
| 147 |
for _, c := range app.featureCommands() { |
| 148 |
fmt.Fprintf(w, " %s\t%s\n", c.Name(), c.ShortHelp()) |
| 149 |
} |
| 150 |
if app.verbose() { |
| 151 |
fmt.Fprint(w, "\t\nInternal Use Only\t\n") |
| 152 |
for _, c := range app.internalCommands() { |
| 153 |
fmt.Fprintf(w, " %s\t%s\n", c.Name(), c.ShortHelp()) |
| 154 |
} |
| 155 |
} |
| 156 |
fmt.Fprint(w, "\nflags:\n") |
| 157 |
printFlagDefaults(f) |
| 158 |
} |
| 159 |
|
| 160 |
|
| 161 |
func printFlagDefaults(s *flag.FlagSet) { |
| 162 |
var flags [][]*flag.Flag |
| 163 |
seen := map[flag.Value]int{} |
| 164 |
s.VisitAll(func(f *flag.Flag) { |
| 165 |
if i, ok := seen[f.Value]; !ok { |
| 166 |
seen[f.Value] = len(flags) |
| 167 |
flags = append(flags, []*flag.Flag{f}) |
| 168 |
} else { |
| 169 |
flags[i] = append(flags[i], f) |
| 170 |
} |
| 171 |
}) |
| 172 |
for _, entry := range flags { |
| 173 |
sort.SliceStable(entry, func(i, j int) bool { |
| 174 |
return len(entry[i].Name) < len(entry[j].Name) |
| 175 |
}) |
| 176 |
var b strings.Builder |
| 177 |
for i, f := range entry { |
| 178 |
switch i { |
| 179 |
case 0: |
| 180 |
b.WriteString(" -") |
| 181 |
default: |
| 182 |
b.WriteString(",-") |
| 183 |
} |
| 184 |
b.WriteString(f.Name) |
| 185 |
} |
| 186 |
|
| 187 |
f := entry[0] |
| 188 |
name, usage := flag.UnquoteUsage(f) |
| 189 |
if len(name) > 0 { |
| 190 |
b.WriteString("=") |
| 191 |
b.WriteString(name) |
| 192 |
} |
| 193 |
|
| 194 |
|
| 195 |
if b.Len() <= 4 { |
| 196 |
b.WriteString("\t") |
| 197 |
} else { |
| 198 |
|
| 199 |
|
| 200 |
b.WriteString("\n \t") |
| 201 |
} |
| 202 |
b.WriteString(strings.ReplaceAll(usage, "\n", "\n \t")) |
| 203 |
if !isZeroValue(f, f.DefValue) { |
| 204 |
if reflect.TypeOf(f.Value).Elem().Name() == "stringValue" { |
| 205 |
fmt.Fprintf(&b, " (default %q)", f.DefValue) |
| 206 |
} else { |
| 207 |
fmt.Fprintf(&b, " (default %v)", f.DefValue) |
| 208 |
} |
| 209 |
} |
| 210 |
fmt.Fprint(s.Output(), b.String(), "\n") |
| 211 |
} |
| 212 |
} |
| 213 |
|
| 214 |
|
| 215 |
func isZeroValue(f *flag.Flag, value string) bool { |
| 216 |
|
| 217 |
|
| 218 |
|
| 219 |
typ := reflect.TypeOf(f.Value) |
| 220 |
var z reflect.Value |
| 221 |
if typ.Kind() == reflect.Pointer { |
| 222 |
z = reflect.New(typ.Elem()) |
| 223 |
} else { |
| 224 |
z = reflect.Zero(typ) |
| 225 |
} |
| 226 |
return value == z.Interface().(flag.Value).String() |
| 227 |
} |
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
|
| 232 |
|
| 233 |
func (app *Application) Run(ctx context.Context, args ...string) error { |
| 234 |
|
| 235 |
|
| 236 |
|
| 237 |
filecache.Start() |
| 238 |
|
| 239 |
ctx = debug.WithInstance(ctx, app.OTel) |
| 240 |
if len(args) == 0 { |
| 241 |
s := flag.NewFlagSet(app.Name(), flag.ExitOnError) |
| 242 |
return tool.Run(ctx, s, &app.Serve, args) |
| 243 |
} |
| 244 |
command, args := args[0], args[1:] |
| 245 |
for _, c := range app.Commands() { |
| 246 |
if c.Name() == command { |
| 247 |
s := flag.NewFlagSet(app.Name(), flag.ExitOnError) |
| 248 |
return tool.Run(ctx, s, c, args) |
| 249 |
} |
| 250 |
} |
| 251 |
return tool.CommandLineErrorf("Unknown command %v", command) |
| 252 |
} |
| 253 |
|
| 254 |
|
| 255 |
|
| 256 |
|
| 257 |
func (app *Application) Commands() []tool.Application { |
| 258 |
var commands []tool.Application |
| 259 |
commands = append(commands, app.mainCommands()...) |
| 260 |
commands = append(commands, app.featureCommands()...) |
| 261 |
commands = append(commands, app.internalCommands()...) |
| 262 |
return commands |
| 263 |
} |
| 264 |
|
| 265 |
func (app *Application) mainCommands() []tool.Application { |
| 266 |
return []tool.Application{ |
| 267 |
&app.Serve, |
| 268 |
&version{app: app}, |
| 269 |
&help{app: app}, |
| 270 |
&apiJSON{app: app}, |
| 271 |
&licenses{app: app}, |
| 272 |
} |
| 273 |
} |
| 274 |
|
| 275 |
func (app *Application) internalCommands() []tool.Application { |
| 276 |
return []tool.Application{ |
| 277 |
&vulncheck{app: app}, |
| 278 |
} |
| 279 |
} |
| 280 |
|
| 281 |
func (app *Application) featureCommands() []tool.Application { |
| 282 |
return []tool.Application{ |
| 283 |
&callHierarchy{app: app}, |
| 284 |
&check{app: app, Severity: "warning"}, |
| 285 |
&codeaction{app: app}, |
| 286 |
&codelens{app: app}, |
| 287 |
&definition{app: app}, |
| 288 |
&execute{app: app}, |
| 289 |
&fix{app: app}, |
| 290 |
&foldingRanges{app: app}, |
| 291 |
&format{app: app}, |
| 292 |
&headlessMCP{app: app}, |
| 293 |
&highlight{app: app}, |
| 294 |
&implementation{app: app}, |
| 295 |
&imports{app: app}, |
| 296 |
newRemote(app, ""), |
| 297 |
newRemote(app, "inspect"), |
| 298 |
&links{app: app}, |
| 299 |
&prepareRename{app: app}, |
| 300 |
&references{app: app}, |
| 301 |
&rename{app: app}, |
| 302 |
&semanticToken{app: app}, |
| 303 |
&signature{app: app}, |
| 304 |
&stats{app: app}, |
| 305 |
&symbols{app: app}, |
| 306 |
|
| 307 |
&workspaceSymbol{app: app}, |
| 308 |
} |
| 309 |
} |
| 310 |
|
| 311 |
|
| 312 |
func (app *Application) connect(ctx context.Context) (*client, *cache.Session, error) { |
| 313 |
root, err := os.Getwd() |
| 314 |
if err != nil { |
| 315 |
return nil, nil, fmt.Errorf("finding workdir: %v", err) |
| 316 |
} |
| 317 |
options := settings.DefaultOptions(app.options) |
| 318 |
client := newClient(app) |
| 319 |
var ( |
| 320 |
svr protocol.Server |
| 321 |
sess *cache.Session |
| 322 |
) |
| 323 |
if app.Remote == "" { |
| 324 |
|
| 325 |
sess = cache.NewSession(ctx, cache.New(nil)) |
| 326 |
svr = server.New(sess, client, options) |
| 327 |
ctx = protocol.WithClient(ctx, client) |
| 328 |
} else { |
| 329 |
|
| 330 |
netConn, err := lsprpc.ConnectToRemote(ctx, app.Remote) |
| 331 |
if err != nil { |
| 332 |
return nil, nil, err |
| 333 |
} |
| 334 |
stream := jsonrpc2.NewHeaderStream(netConn) |
| 335 |
jsonConn := jsonrpc2.NewConn(stream) |
| 336 |
svr = protocol.ServerDispatcher(jsonConn) |
| 337 |
ctx = protocol.WithClient(ctx, client) |
| 338 |
jsonConn.Go(ctx, |
| 339 |
protocol.Handlers( |
| 340 |
protocol.ClientHandler(client, jsonrpc2.MethodNotFound))) |
| 341 |
} |
| 342 |
if err := client.initialize(ctx, svr, initParams(root, options)); err != nil { |
| 343 |
return nil, nil, err |
| 344 |
} |
| 345 |
return client, sess, nil |
| 346 |
} |
| 347 |
|
| 348 |
func initParams(rootDir string, opts *settings.Options) *protocol.ParamInitialize { |
| 349 |
params := &protocol.ParamInitialize{} |
| 350 |
params.RootURI = protocol.URIFromPath(rootDir) |
| 351 |
params.Capabilities.Workspace.Configuration = true |
| 352 |
|
| 353 |
|
| 354 |
|
| 355 |
params.Capabilities.TextDocument.Hover = &protocol.HoverClientCapabilities{ |
| 356 |
ContentFormat: []protocol.MarkupKind{opts.PreferredContentFormat}, |
| 357 |
} |
| 358 |
params.Capabilities.TextDocument.DocumentSymbol.HierarchicalDocumentSymbolSupport = opts.HierarchicalDocumentSymbolSupport |
| 359 |
params.Capabilities.TextDocument.SemanticTokens = protocol.SemanticTokensClientCapabilities{} |
| 360 |
params.Capabilities.TextDocument.SemanticTokens.Formats = []protocol.TokenFormat{"relative"} |
| 361 |
params.Capabilities.TextDocument.SemanticTokens.Requests.Range = &protocol.Or_ClientSemanticTokensRequestOptions_range{Value: true} |
| 362 |
|
| 363 |
params.Capabilities.TextDocument.SemanticTokens.Requests.Full = &protocol.Or_ClientSemanticTokensRequestOptions_full{Value: true} |
| 364 |
params.Capabilities.TextDocument.SemanticTokens.TokenTypes = moreslices.ConvertStrings[string](semtok.Types) |
| 365 |
params.Capabilities.TextDocument.SemanticTokens.TokenModifiers = moreslices.ConvertStrings[string](semtok.Modifiers) |
| 366 |
params.Capabilities.TextDocument.CodeAction = protocol.CodeActionClientCapabilities{ |
| 367 |
CodeActionLiteralSupport: protocol.ClientCodeActionLiteralOptions{ |
| 368 |
CodeActionKind: protocol.ClientCodeActionKindOptions{ |
| 369 |
ValueSet: []protocol.CodeActionKind{protocol.Empty}, |
| 370 |
}, |
| 371 |
}, |
| 372 |
} |
| 373 |
params.Capabilities.Window.WorkDoneProgress = true |
| 374 |
params.Capabilities.Workspace.FileOperations = &protocol.FileOperationClientCapabilities{ |
| 375 |
DidCreate: true, |
| 376 |
} |
| 377 |
params.InitializationOptions = map[string]any{ |
| 378 |
"symbolMatcher": string(opts.SymbolMatcher), |
| 379 |
} |
| 380 |
return params |
| 381 |
} |
| 382 |
|
| 383 |
|
| 384 |
func (cli *client) initialize(ctx context.Context, server protocol.Server, params *protocol.ParamInitialize) error { |
| 385 |
result, err := server.Initialize(ctx, params) |
| 386 |
if err != nil { |
| 387 |
return err |
| 388 |
} |
| 389 |
if err := server.Initialized(ctx, &protocol.InitializedParams{}); err != nil { |
| 390 |
return err |
| 391 |
} |
| 392 |
cli.server = server |
| 393 |
cli.initializeResult = result |
| 394 |
return nil |
| 395 |
} |
| 396 |
|
| 397 |
|
| 398 |
|
| 399 |
|
| 400 |
|
| 401 |
|
| 402 |
|
| 403 |
type client struct { |
| 404 |
app *Application |
| 405 |
|
| 406 |
server protocol.Server |
| 407 |
initializeResult *protocol.InitializeResult |
| 408 |
|
| 409 |
progressMu sync.Mutex |
| 410 |
iwlToken protocol.ProgressToken |
| 411 |
iwlDone chan struct{} |
| 412 |
|
| 413 |
filesMu sync.Mutex |
| 414 |
files map[protocol.DocumentURI]*cmdFile |
| 415 |
} |
| 416 |
|
| 417 |
|
| 418 |
type cmdFile struct { |
| 419 |
uri protocol.DocumentURI |
| 420 |
mapper *protocol.Mapper |
| 421 |
err error |
| 422 |
diagnosticsMu sync.Mutex |
| 423 |
diagnostics []protocol.Diagnostic |
| 424 |
} |
| 425 |
|
| 426 |
func newClient(app *Application) *client { |
| 427 |
return &client{ |
| 428 |
app: app, |
| 429 |
files: make(map[protocol.DocumentURI]*cmdFile), |
| 430 |
iwlDone: make(chan struct{}), |
| 431 |
} |
| 432 |
} |
| 433 |
|
| 434 |
func (cli *client) TextDocumentContentRefresh(context.Context, *protocol.TextDocumentContentRefreshParams) error { |
| 435 |
return nil |
| 436 |
} |
| 437 |
|
| 438 |
func (cli *client) CodeLensRefresh(context.Context) error { return nil } |
| 439 |
|
| 440 |
func (cli *client) FoldingRangeRefresh(context.Context) error { return nil } |
| 441 |
|
| 442 |
func (cli *client) LogTrace(context.Context, *protocol.LogTraceParams) error { return nil } |
| 443 |
|
| 444 |
func (cli *client) ShowMessage(ctx context.Context, p *protocol.ShowMessageParams) error { |
| 445 |
fmt.Fprintf(os.Stderr, "%s: %s\n", p.Type, p.Message) |
| 446 |
return nil |
| 447 |
} |
| 448 |
|
| 449 |
func (cli *client) ShowMessageRequest(ctx context.Context, p *protocol.ShowMessageRequestParams) (*protocol.MessageActionItem, error) { |
| 450 |
return nil, nil |
| 451 |
} |
| 452 |
|
| 453 |
func (cli *client) LogMessage(ctx context.Context, p *protocol.LogMessageParams) error { |
| 454 |
|
| 455 |
|
| 456 |
|
| 457 |
switch p.Type { |
| 458 |
case protocol.Error: |
| 459 |
log.Print("Error:", p.Message) |
| 460 |
case protocol.Warning: |
| 461 |
log.Print("Warning:", p.Message) |
| 462 |
case protocol.Info: |
| 463 |
if cli.app.verbose() { |
| 464 |
log.Print("Info:", p.Message) |
| 465 |
} |
| 466 |
case protocol.Log: |
| 467 |
if cli.app.verbose() { |
| 468 |
log.Print("Log:", p.Message) |
| 469 |
} |
| 470 |
default: |
| 471 |
if cli.app.verbose() { |
| 472 |
log.Print(p.Message) |
| 473 |
} |
| 474 |
} |
| 475 |
return nil |
| 476 |
} |
| 477 |
|
| 478 |
func (cli *client) Event(ctx context.Context, t *any) error { return nil } |
| 479 |
|
| 480 |
func (cli *client) RegisterCapability(ctx context.Context, p *protocol.RegistrationParams) error { |
| 481 |
return nil |
| 482 |
} |
| 483 |
|
| 484 |
func (cli *client) UnregisterCapability(ctx context.Context, p *protocol.UnregistrationParams) error { |
| 485 |
return nil |
| 486 |
} |
| 487 |
|
| 488 |
func (cli *client) WorkspaceFolders(ctx context.Context) ([]protocol.WorkspaceFolder, error) { |
| 489 |
return nil, nil |
| 490 |
} |
| 491 |
|
| 492 |
func (cli *client) Configuration(ctx context.Context, p *protocol.ParamConfiguration) ([]any, error) { |
| 493 |
results := make([]any, len(p.Items)) |
| 494 |
for i, item := range p.Items { |
| 495 |
if item.Section != "gopls" { |
| 496 |
continue |
| 497 |
} |
| 498 |
m := map[string]any{ |
| 499 |
"analyses": map[string]any{ |
| 500 |
"fillreturns": true, |
| 501 |
"nonewvars": true, |
| 502 |
"noresultvalues": true, |
| 503 |
"undeclaredname": true, |
| 504 |
}, |
| 505 |
} |
| 506 |
if cli.app.VeryVerbose { |
| 507 |
m["verboseOutput"] = true |
| 508 |
} |
| 509 |
results[i] = m |
| 510 |
} |
| 511 |
return results, nil |
| 512 |
} |
| 513 |
|
| 514 |
func (cli *client) ApplyEdit(ctx context.Context, p *protocol.ApplyWorkspaceEditParams) (*protocol.ApplyWorkspaceEditResult, error) { |
| 515 |
if err := cli.applyWorkspaceEdit(&p.Edit); err != nil { |
| 516 |
return &protocol.ApplyWorkspaceEditResult{FailureReason: err.Error()}, nil |
| 517 |
} |
| 518 |
return &protocol.ApplyWorkspaceEditResult{Applied: true}, nil |
| 519 |
} |
| 520 |
|
| 521 |
|
| 522 |
|
| 523 |
|
| 524 |
|
| 525 |
|
| 526 |
|
| 527 |
|
| 528 |
func (cli *client) applyWorkspaceEdit(wsedit *protocol.WorkspaceEdit) error { |
| 529 |
|
| 530 |
create := func(uri protocol.DocumentURI, content []byte) error { |
| 531 |
edits := []diff.Edit{{Start: 0, End: 0, New: string(content)}} |
| 532 |
return updateFile(uri.Path(), nil, content, edits, cli.app.editFlags) |
| 533 |
} |
| 534 |
|
| 535 |
delete := func(uri protocol.DocumentURI, content []byte) error { |
| 536 |
edits := []diff.Edit{{Start: 0, End: len(content), New: ""}} |
| 537 |
return updateFile(uri.Path(), content, nil, edits, cli.app.editFlags) |
| 538 |
} |
| 539 |
|
| 540 |
for _, c := range wsedit.DocumentChanges { |
| 541 |
switch { |
| 542 |
case c.TextDocumentEdit != nil: |
| 543 |
f := cli.getFile(c.TextDocumentEdit.TextDocument.URI) |
| 544 |
if f.err != nil { |
| 545 |
return f.err |
| 546 |
} |
| 547 |
|
| 548 |
edits := protocol.AsTextEdits(c.TextDocumentEdit.Edits) |
| 549 |
if err := applyTextEdits(f.mapper, edits, cli.app.editFlags); err != nil { |
| 550 |
return err |
| 551 |
} |
| 552 |
|
| 553 |
case c.CreateFile != nil: |
| 554 |
if err := create(c.CreateFile.URI, []byte{}); err != nil { |
| 555 |
return err |
| 556 |
} |
| 557 |
|
| 558 |
case c.RenameFile != nil: |
| 559 |
|
| 560 |
f := cli.getFile(c.RenameFile.OldURI) |
| 561 |
if f.err != nil { |
| 562 |
return f.err |
| 563 |
} |
| 564 |
if err := create(c.RenameFile.NewURI, f.mapper.Content); err != nil { |
| 565 |
return err |
| 566 |
} |
| 567 |
if err := delete(f.mapper.URI, f.mapper.Content); err != nil { |
| 568 |
return err |
| 569 |
} |
| 570 |
|
| 571 |
case c.DeleteFile != nil: |
| 572 |
f := cli.getFile(c.DeleteFile.URI) |
| 573 |
if f.err != nil { |
| 574 |
return f.err |
| 575 |
} |
| 576 |
if err := delete(f.mapper.URI, f.mapper.Content); err != nil { |
| 577 |
return err |
| 578 |
} |
| 579 |
|
| 580 |
default: |
| 581 |
return fmt.Errorf("unknown DocumentChange: %#v", c) |
| 582 |
} |
| 583 |
} |
| 584 |
return nil |
| 585 |
} |
| 586 |
|
| 587 |
|
| 588 |
|
| 589 |
func applyTextEdits(mapper *protocol.Mapper, edits []protocol.TextEdit, flags *EditFlags) error { |
| 590 |
if len(edits) == 0 { |
| 591 |
return nil |
| 592 |
} |
| 593 |
newContent, diffEdits, err := protocol.ApplyEdits(mapper, edits) |
| 594 |
if err != nil { |
| 595 |
return err |
| 596 |
} |
| 597 |
return updateFile(mapper.URI.Path(), mapper.Content, newContent, diffEdits, flags) |
| 598 |
} |
| 599 |
|
| 600 |
|
| 601 |
|
| 602 |
|
| 603 |
|
| 604 |
func updateFile(filename string, old, new []byte, edits []diff.Edit, flags *EditFlags) error { |
| 605 |
if flags.List { |
| 606 |
fmt.Println(filename) |
| 607 |
} |
| 608 |
|
| 609 |
if flags.Write { |
| 610 |
if flags.Preserve && old != nil { |
| 611 |
if err := os.WriteFile(filename+".orig", old, 0666); err != nil { |
| 612 |
return err |
| 613 |
} |
| 614 |
} |
| 615 |
|
| 616 |
if new != nil { |
| 617 |
|
| 618 |
if err := os.WriteFile(filename, new, 0666); err != nil { |
| 619 |
return err |
| 620 |
} |
| 621 |
} else { |
| 622 |
|
| 623 |
if err := os.Remove(filename); err != nil { |
| 624 |
return err |
| 625 |
} |
| 626 |
} |
| 627 |
} |
| 628 |
|
| 629 |
if flags.Diff { |
| 630 |
|
| 631 |
|
| 632 |
unified, err := diff.ToUnified(filename+".orig", filename, string(old), edits, diff.DefaultContextLines) |
| 633 |
if err != nil { |
| 634 |
return err |
| 635 |
} |
| 636 |
fmt.Print(unified) |
| 637 |
} |
| 638 |
|
| 639 |
|
| 640 |
|
| 641 |
|
| 642 |
|
| 643 |
if !(flags.List || flags.Write || flags.Diff) { |
| 644 |
os.Stdout.Write(new) |
| 645 |
} |
| 646 |
|
| 647 |
return nil |
| 648 |
} |
| 649 |
|
| 650 |
func (cli *client) PublishDiagnostics(ctx context.Context, p *protocol.PublishDiagnosticsParams) error { |
| 651 |
|
| 652 |
|
| 653 |
|
| 654 |
|
| 655 |
|
| 656 |
if p.Version == 0 { |
| 657 |
return nil |
| 658 |
} |
| 659 |
|
| 660 |
file := cli.getFile(p.URI) |
| 661 |
|
| 662 |
file.diagnosticsMu.Lock() |
| 663 |
defer file.diagnosticsMu.Unlock() |
| 664 |
|
| 665 |
file.diagnostics = append(file.diagnostics, p.Diagnostics...) |
| 666 |
|
| 667 |
|
| 668 |
|
| 669 |
|
| 670 |
|
| 671 |
type key [6]any |
| 672 |
seen := make(map[key]bool) |
| 673 |
out := file.diagnostics[:0] |
| 674 |
for _, d := range file.diagnostics { |
| 675 |
var codeHref string |
| 676 |
if desc := d.CodeDescription; desc != nil { |
| 677 |
codeHref = desc.Href |
| 678 |
} |
| 679 |
k := key{d.Range, d.Severity, d.Code, codeHref, d.Source, d.Message} |
| 680 |
if !seen[k] { |
| 681 |
seen[k] = true |
| 682 |
out = append(out, d) |
| 683 |
} |
| 684 |
} |
| 685 |
file.diagnostics = out |
| 686 |
|
| 687 |
return nil |
| 688 |
} |
| 689 |
|
| 690 |
func (cli *client) Progress(_ context.Context, params *protocol.ProgressParams) error { |
| 691 |
if _, ok := params.Token.(string); !ok { |
| 692 |
return fmt.Errorf("unexpected progress token: %[1]T %[1]v", params.Token) |
| 693 |
} |
| 694 |
|
| 695 |
switch v := params.Value.(type) { |
| 696 |
case *protocol.WorkDoneProgressBegin: |
| 697 |
if v.Title == server.DiagnosticWorkTitle(server.FromInitialWorkspaceLoad) { |
| 698 |
cli.progressMu.Lock() |
| 699 |
cli.iwlToken = params.Token |
| 700 |
cli.progressMu.Unlock() |
| 701 |
} |
| 702 |
|
| 703 |
case *protocol.WorkDoneProgressReport: |
| 704 |
if cli.app.Verbose { |
| 705 |
fmt.Fprintln(os.Stderr, v.Message) |
| 706 |
} |
| 707 |
|
| 708 |
case *protocol.WorkDoneProgressEnd: |
| 709 |
cli.progressMu.Lock() |
| 710 |
iwlToken := cli.iwlToken |
| 711 |
cli.progressMu.Unlock() |
| 712 |
|
| 713 |
if params.Token == iwlToken { |
| 714 |
close(cli.iwlDone) |
| 715 |
} |
| 716 |
} |
| 717 |
return nil |
| 718 |
} |
| 719 |
|
| 720 |
func (cli *client) ShowDocument(ctx context.Context, params *protocol.ShowDocumentParams) (*protocol.ShowDocumentResult, error) { |
| 721 |
var success bool |
| 722 |
if params.External { |
| 723 |
|
| 724 |
success = browser.Open(params.URI) |
| 725 |
} else { |
| 726 |
|
| 727 |
|
| 728 |
log.Printf("Server requested that client editor open %q (takeFocus=%t, selection=%+v)", |
| 729 |
params.URI, params.TakeFocus, params.Selection) |
| 730 |
success = true |
| 731 |
} |
| 732 |
return &protocol.ShowDocumentResult{Success: success}, nil |
| 733 |
} |
| 734 |
|
| 735 |
func (cli *client) WorkDoneProgressCreate(context.Context, *protocol.WorkDoneProgressCreateParams) error { |
| 736 |
return nil |
| 737 |
} |
| 738 |
|
| 739 |
func (cli *client) DiagnosticRefresh(context.Context) error { |
| 740 |
return nil |
| 741 |
} |
| 742 |
|
| 743 |
func (cli *client) InlayHintRefresh(context.Context) error { |
| 744 |
return nil |
| 745 |
} |
| 746 |
|
| 747 |
func (cli *client) SemanticTokensRefresh(context.Context) error { |
| 748 |
return nil |
| 749 |
} |
| 750 |
|
| 751 |
func (cli *client) InlineValueRefresh(context.Context) error { |
| 752 |
return nil |
| 753 |
} |
| 754 |
|
| 755 |
|
| 756 |
func (cli *client) getFile(uri protocol.DocumentURI) *cmdFile { |
| 757 |
cli.filesMu.Lock() |
| 758 |
defer cli.filesMu.Unlock() |
| 759 |
|
| 760 |
file, found := cli.files[uri] |
| 761 |
if !found || file.err != nil { |
| 762 |
file = &cmdFile{ |
| 763 |
uri: uri, |
| 764 |
} |
| 765 |
cli.files[uri] = file |
| 766 |
} |
| 767 |
if file.mapper == nil { |
| 768 |
content, err := os.ReadFile(uri.Path()) |
| 769 |
if err != nil { |
| 770 |
file.err = fmt.Errorf("getFile: %v: %v", uri, err) |
| 771 |
return file |
| 772 |
} |
| 773 |
file.mapper = protocol.NewMapper(uri, content) |
| 774 |
} |
| 775 |
return file |
| 776 |
} |
| 777 |
|
| 778 |
|
| 779 |
|
| 780 |
func (cli *client) openFile(ctx context.Context, uri protocol.DocumentURI) (*cmdFile, error) { |
| 781 |
file := cli.getFile(uri) |
| 782 |
if file.err != nil { |
| 783 |
return nil, file.err |
| 784 |
} |
| 785 |
|
| 786 |
|
| 787 |
var langID protocol.LanguageKind |
| 788 |
switch filepath.Ext(uri.Path()) { |
| 789 |
case ".go": |
| 790 |
langID = "go" |
| 791 |
case ".mod": |
| 792 |
langID = "go.mod" |
| 793 |
case ".sum": |
| 794 |
langID = "go.sum" |
| 795 |
case ".work": |
| 796 |
langID = "go.work" |
| 797 |
case ".s": |
| 798 |
langID = "go.s" |
| 799 |
} |
| 800 |
|
| 801 |
p := &protocol.DidOpenTextDocumentParams{ |
| 802 |
TextDocument: protocol.TextDocumentItem{ |
| 803 |
URI: uri, |
| 804 |
LanguageID: langID, |
| 805 |
Version: 1, |
| 806 |
Text: string(file.mapper.Content), |
| 807 |
}, |
| 808 |
} |
| 809 |
if err := cli.server.DidOpen(ctx, p); err != nil { |
| 810 |
|
| 811 |
file.err = fmt.Errorf("%v: %v", uri, err) |
| 812 |
return nil, file.err |
| 813 |
} |
| 814 |
return file, nil |
| 815 |
} |
| 816 |
|
| 817 |
func diagnoseFiles(ctx context.Context, server protocol.Server, files []protocol.DocumentURI) error { |
| 818 |
cmd := command.NewDiagnoseFilesCommand("Diagnose files", command.DiagnoseFilesArgs{ |
| 819 |
Files: files, |
| 820 |
}) |
| 821 |
_, err := executeCommand(ctx, server, cmd) |
| 822 |
return err |
| 823 |
} |
| 824 |
|
| 825 |
func (cli *client) terminate(ctx context.Context) { |
| 826 |
if err := cli.server.Shutdown(ctx); err != nil { |
| 827 |
log.Printf("server shutdown failed: %v", err) |
| 828 |
} |
| 829 |
|
| 830 |
|
| 831 |
|
| 832 |
|
| 833 |
} |
| 834 |
|
| 835 |
|
| 836 |
func (cli *client) Close() error { |
| 837 |
return nil |
| 838 |
} |
| 839 |
|
| 840 |
|
| 841 |
|
| 842 |
|
| 843 |
|
| 844 |
func (f *cmdFile) locationSpan(loc protocol.Location) (span, error) { |
| 845 |
|
| 846 |
return f.rangeSpan(loc.Range) |
| 847 |
} |
| 848 |
|
| 849 |
|
| 850 |
|
| 851 |
func (f *cmdFile) rangeSpan(r protocol.Range) (span, error) { |
| 852 |
start, end, err := f.mapper.RangeOffsets(r) |
| 853 |
if err != nil { |
| 854 |
return span{}, err |
| 855 |
} |
| 856 |
return f.offsetSpan(start, end) |
| 857 |
} |
| 858 |
|
| 859 |
|
| 860 |
|
| 861 |
func (f *cmdFile) offsetSpan(start, end int) (span, error) { |
| 862 |
if start > end { |
| 863 |
return span{}, fmt.Errorf("start offset (%d) > end (%d)", start, end) |
| 864 |
} |
| 865 |
startPoint, err := offsetPoint(f.mapper, start) |
| 866 |
if err != nil { |
| 867 |
return span{}, fmt.Errorf("start: %v", err) |
| 868 |
} |
| 869 |
endPoint, err := offsetPoint(f.mapper, end) |
| 870 |
if err != nil { |
| 871 |
return span{}, fmt.Errorf("end: %v", err) |
| 872 |
} |
| 873 |
return newSpan(f.mapper.URI, startPoint, endPoint), nil |
| 874 |
} |
| 875 |
|
| 876 |
|
| 877 |
|
| 878 |
func offsetPoint(m *protocol.Mapper, offset int) (point, error) { |
| 879 |
if !(0 <= offset && offset <= len(m.Content)) { |
| 880 |
return point{}, fmt.Errorf("invalid offset %d (want 0-%d)", offset, len(m.Content)) |
| 881 |
} |
| 882 |
line, col8 := m.OffsetLineCol8(offset) |
| 883 |
return newPoint(line, col8, offset), nil |
| 884 |
} |
| 885 |
|
| 886 |
|
| 887 |
|
| 888 |
|
| 889 |
|
| 890 |
func (f *cmdFile) spanLocation(s span) (protocol.Location, error) { |
| 891 |
rng, err := f.spanRange(s) |
| 892 |
if err != nil { |
| 893 |
return protocol.Location{}, err |
| 894 |
} |
| 895 |
return f.mapper.URI.Location(rng), nil |
| 896 |
} |
| 897 |
|
| 898 |
|
| 899 |
|
| 900 |
func (f *cmdFile) spanRange(s span) (protocol.Range, error) { |
| 901 |
|
| 902 |
|
| 903 |
|
| 904 |
|
| 905 |
|
| 906 |
|
| 907 |
if !strings.EqualFold(f.mapper.URI.Base(), s.URI().Base()) { |
| 908 |
return protocol.Range{}, bug.Errorf("mapper is for file %q instead of %q", f.mapper.URI, s.URI()) |
| 909 |
} |
| 910 |
start, err := pointPosition(f.mapper, s.Start()) |
| 911 |
if err != nil { |
| 912 |
return protocol.Range{}, fmt.Errorf("start: %w", err) |
| 913 |
} |
| 914 |
end, err := pointPosition(f.mapper, s.End()) |
| 915 |
if err != nil { |
| 916 |
return protocol.Range{}, fmt.Errorf("end: %w", err) |
| 917 |
} |
| 918 |
return protocol.Range{Start: start, End: end}, nil |
| 919 |
} |
| 920 |
|
| 921 |
|
| 922 |
func pointPosition(m *protocol.Mapper, p point) (protocol.Position, error) { |
| 923 |
if p.HasPosition() { |
| 924 |
return m.LineCol8Position(p.Line(), p.Column()) |
| 925 |
} |
| 926 |
if p.HasOffset() { |
| 927 |
return m.OffsetPosition(p.Offset()) |
| 928 |
} |
| 929 |
return protocol.Position{}, fmt.Errorf("point has neither offset nor line/column") |
| 930 |
} |
| 931 |
|
| 932 |
|
| 933 |
type fix struct{ app *Application } |
| 934 |
|
| 935 |
func (*fix) Name() string { return "fix" } |
| 936 |
func (cmd *fix) Parent() string { return cmd.app.Name() } |
| 937 |
func (*fix) Usage() string { return "" } |
| 938 |
func (*fix) ShortHelp() string { return "apply suggested fixes (obsolete)" } |
| 939 |
func (*fix) DetailedHelp(flags *flag.FlagSet) { |
| 940 |
fmt.Fprintf(flags.Output(), `No longer supported; use "gopls codeaction" instead.`) |
| 941 |
} |
| 942 |
func (*fix) Run(ctx context.Context, args ...string) error { |
| 943 |
return tool.CommandLineErrorf(`no longer supported; use "gopls codeaction" instead`) |
| 944 |
} |