golang.org/x/tools/gopls@v0.15.3/internal/protocol/command/interface.go (about)

     1  // Copyright 2021 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  //go:generate go run -tags=generate generate.go
     6  
     7  // Package command defines the interface provided by gopls for the
     8  // workspace/executeCommand LSP request.
     9  //
    10  // This interface is fully specified by the Interface type, provided it
    11  // conforms to the restrictions outlined in its doc string.
    12  //
    13  // Bindings for server-side command dispatch and client-side serialization are
    14  // also provided by this package, via code generation.
    15  package command
    16  
    17  import (
    18  	"context"
    19  
    20  	"golang.org/x/tools/gopls/internal/protocol"
    21  	"golang.org/x/tools/gopls/internal/vulncheck"
    22  )
    23  
    24  // Interface defines the interface gopls exposes for the
    25  // workspace/executeCommand request.
    26  //
    27  // This interface is used to generate marshaling/unmarshaling code, dispatch,
    28  // and documentation, and so has some additional restrictions:
    29  //  1. All method arguments must be JSON serializable.
    30  //  2. Methods must return either error or (T, error), where T is a
    31  //     JSON serializable type.
    32  //  3. The first line of the doc string is special. Everything after the colon
    33  //     is considered the command 'Title'.
    34  //     TODO(rFindley): reconsider this -- Title may be unnecessary.
    35  //
    36  // The doc comment on each method is eventually published at
    37  // https://github.com/golang/tools/blob/master/gopls/doc/commands.md,
    38  // so please be consistent in using this form:
    39  //
    40  //	Command: Capitalized verb phrase with no period
    41  //
    42  //	Longer description here...
    43  type Interface interface {
    44  	// ApplyFix: Apply a fix
    45  	//
    46  	// Applies a fix to a region of source code.
    47  	ApplyFix(context.Context, ApplyFixArgs) (*protocol.WorkspaceEdit, error)
    48  
    49  	// Test: Run test(s) (legacy)
    50  	//
    51  	// Runs `go test` for a specific set of test or benchmark functions.
    52  	Test(context.Context, protocol.DocumentURI, []string, []string) error
    53  
    54  	// TODO: deprecate Test in favor of RunTests below.
    55  
    56  	// Test: Run test(s)
    57  	//
    58  	// Runs `go test` for a specific set of test or benchmark functions.
    59  	RunTests(context.Context, RunTestsArgs) error
    60  
    61  	// Generate: Run go generate
    62  	//
    63  	// Runs `go generate` for a given directory.
    64  	Generate(context.Context, GenerateArgs) error
    65  
    66  	// RegenerateCgo: Regenerate cgo
    67  	//
    68  	// Regenerates cgo definitions.
    69  	RegenerateCgo(context.Context, URIArg) error
    70  
    71  	// Tidy: Run go mod tidy
    72  	//
    73  	// Runs `go mod tidy` for a module.
    74  	Tidy(context.Context, URIArgs) error
    75  
    76  	// Vendor: Run go mod vendor
    77  	//
    78  	// Runs `go mod vendor` for a module.
    79  	Vendor(context.Context, URIArg) error
    80  
    81  	// EditGoDirective: Run go mod edit -go=version
    82  	//
    83  	// Runs `go mod edit -go=version` for a module.
    84  	EditGoDirective(context.Context, EditGoDirectiveArgs) error
    85  
    86  	// UpdateGoSum: Update go.sum
    87  	//
    88  	// Updates the go.sum file for a module.
    89  	UpdateGoSum(context.Context, URIArgs) error
    90  
    91  	// CheckUpgrades: Check for upgrades
    92  	//
    93  	// Checks for module upgrades.
    94  	CheckUpgrades(context.Context, CheckUpgradesArgs) error
    95  
    96  	// AddDependency: Add a dependency
    97  	//
    98  	// Adds a dependency to the go.mod file for a module.
    99  	AddDependency(context.Context, DependencyArgs) error
   100  
   101  	// UpgradeDependency: Upgrade a dependency
   102  	//
   103  	// Upgrades a dependency in the go.mod file for a module.
   104  	UpgradeDependency(context.Context, DependencyArgs) error
   105  
   106  	// RemoveDependency: Remove a dependency
   107  	//
   108  	// Removes a dependency from the go.mod file of a module.
   109  	RemoveDependency(context.Context, RemoveDependencyArgs) error
   110  
   111  	// ResetGoModDiagnostics: Reset go.mod diagnostics
   112  	//
   113  	// Reset diagnostics in the go.mod file of a module.
   114  	ResetGoModDiagnostics(context.Context, ResetGoModDiagnosticsArgs) error
   115  
   116  	// GoGetPackage: 'go get' a package
   117  	//
   118  	// Runs `go get` to fetch a package.
   119  	GoGetPackage(context.Context, GoGetPackageArgs) error
   120  
   121  	// GCDetails: Toggle gc_details
   122  	//
   123  	// Toggle the calculation of gc annotations.
   124  	GCDetails(context.Context, protocol.DocumentURI) error
   125  
   126  	// TODO: deprecate GCDetails in favor of ToggleGCDetails below.
   127  
   128  	// ToggleGCDetails: Toggle gc_details
   129  	//
   130  	// Toggle the calculation of gc annotations.
   131  	ToggleGCDetails(context.Context, URIArg) error
   132  
   133  	// ListKnownPackages: List known packages
   134  	//
   135  	// Retrieve a list of packages that are importable from the given URI.
   136  	ListKnownPackages(context.Context, URIArg) (ListKnownPackagesResult, error)
   137  
   138  	// ListImports: List imports of a file and its package
   139  	//
   140  	// Retrieve a list of imports in the given Go file, and the package it
   141  	// belongs to.
   142  	ListImports(context.Context, URIArg) (ListImportsResult, error)
   143  
   144  	// AddImport: Add an import
   145  	//
   146  	// Ask the server to add an import path to a given Go file.  The method will
   147  	// call applyEdit on the client so that clients don't have to apply the edit
   148  	// themselves.
   149  	AddImport(context.Context, AddImportArgs) error
   150  
   151  	// StartDebugging: Start the gopls debug server
   152  	//
   153  	// Start the gopls debug server if it isn't running, and return the debug
   154  	// address.
   155  	StartDebugging(context.Context, DebuggingArgs) (DebuggingResult, error)
   156  
   157  	// StartProfile: Start capturing a profile of gopls' execution
   158  	//
   159  	// Start a new pprof profile. Before using the resulting file, profiling must
   160  	// be stopped with a corresponding call to StopProfile.
   161  	//
   162  	// This command is intended for internal use only, by the gopls benchmark
   163  	// runner.
   164  	StartProfile(context.Context, StartProfileArgs) (StartProfileResult, error)
   165  
   166  	// StopProfile: Stop an ongoing profile
   167  	//
   168  	// This command is intended for internal use only, by the gopls benchmark
   169  	// runner.
   170  	StopProfile(context.Context, StopProfileArgs) (StopProfileResult, error)
   171  
   172  	// RunGovulncheck: Run vulncheck
   173  	//
   174  	// Run vulnerability check (`govulncheck`).
   175  	RunGovulncheck(context.Context, VulncheckArgs) (RunVulncheckResult, error)
   176  
   177  	// FetchVulncheckResult: Get known vulncheck result
   178  	//
   179  	// Fetch the result of latest vulnerability check (`govulncheck`).
   180  	FetchVulncheckResult(context.Context, URIArg) (map[protocol.DocumentURI]*vulncheck.Result, error)
   181  
   182  	// MemStats: Fetch memory statistics
   183  	//
   184  	// Call runtime.GC multiple times and return memory statistics as reported by
   185  	// runtime.MemStats.
   186  	//
   187  	// This command is used for benchmarking, and may change in the future.
   188  	MemStats(context.Context) (MemStatsResult, error)
   189  
   190  	// WorkspaceStats: Fetch workspace statistics
   191  	//
   192  	// Query statistics about workspace builds, modules, packages, and files.
   193  	//
   194  	// This command is intended for internal use only, by the gopls stats
   195  	// command.
   196  	WorkspaceStats(context.Context) (WorkspaceStatsResult, error)
   197  
   198  	// RunGoWorkCommand: Run `go work [args...]`, and apply the resulting go.work
   199  	// edits to the current go.work file
   200  	RunGoWorkCommand(context.Context, RunGoWorkArgs) error
   201  
   202  	// AddTelemetryCounters: Update the given telemetry counters
   203  	//
   204  	// Gopls will prepend "fwd/" to all the counters updated using this command
   205  	// to avoid conflicts with other counters gopls collects.
   206  	AddTelemetryCounters(context.Context, AddTelemetryCountersArgs) error
   207  
   208  	// MaybePromptForTelemetry: Prompt user to enable telemetry
   209  	//
   210  	// Checks for the right conditions, and then prompts the user
   211  	// to ask if they want to enable Go telemetry uploading. If
   212  	// the user responds 'Yes', the telemetry mode is set to "on".
   213  	MaybePromptForTelemetry(context.Context) error
   214  
   215  	// ChangeSignature: Perform a "change signature" refactoring
   216  	//
   217  	// This command is experimental, currently only supporting parameter removal.
   218  	// Its signature will certainly change in the future (pun intended).
   219  	ChangeSignature(context.Context, ChangeSignatureArgs) (*protocol.WorkspaceEdit, error)
   220  
   221  	// DiagnoseFiles: Cause server to publish diagnostics for the specified files.
   222  	//
   223  	// This command is needed by the 'gopls {check,fix}' CLI subcommands.
   224  	DiagnoseFiles(context.Context, DiagnoseFilesArgs) error
   225  
   226  	// Views: List current Views on the server.
   227  	//
   228  	// This command is intended for use by gopls tests only.
   229  	Views(context.Context) ([]View, error)
   230  }
   231  
   232  type RunTestsArgs struct {
   233  	// The test file containing the tests to run.
   234  	URI protocol.DocumentURI
   235  
   236  	// Specific test names to run, e.g. TestFoo.
   237  	Tests []string
   238  
   239  	// Specific benchmarks to run, e.g. BenchmarkFoo.
   240  	Benchmarks []string
   241  }
   242  
   243  type GenerateArgs struct {
   244  	// URI for the directory to generate.
   245  	Dir protocol.DocumentURI
   246  
   247  	// Whether to generate recursively (go generate ./...)
   248  	Recursive bool
   249  }
   250  
   251  // TODO(rFindley): document the rest of these once the docgen is fleshed out.
   252  
   253  type ApplyFixArgs struct {
   254  	// The name of the fix to apply.
   255  	//
   256  	// For fixes suggested by analyzers, this is a string constant
   257  	// advertised by the analyzer that matches the Category of
   258  	// the analysis.Diagnostic with a SuggestedFix containing no edits.
   259  	//
   260  	// For fixes suggested by code actions, this is a string agreed
   261  	// upon by the code action and golang.ApplyFix.
   262  	Fix string
   263  
   264  	// The file URI for the document to fix.
   265  	URI protocol.DocumentURI
   266  	// The document range to scan for fixes.
   267  	Range protocol.Range
   268  	// Whether to resolve and return the edits.
   269  	ResolveEdits bool
   270  }
   271  
   272  type URIArg struct {
   273  	// The file URI.
   274  	URI protocol.DocumentURI
   275  }
   276  
   277  type URIArgs struct {
   278  	// The file URIs.
   279  	URIs []protocol.DocumentURI
   280  }
   281  
   282  type CheckUpgradesArgs struct {
   283  	// The go.mod file URI.
   284  	URI protocol.DocumentURI
   285  	// The modules to check.
   286  	Modules []string
   287  }
   288  
   289  type DependencyArgs struct {
   290  	// The go.mod file URI.
   291  	URI protocol.DocumentURI
   292  	// Additional args to pass to the go command.
   293  	GoCmdArgs []string
   294  	// Whether to add a require directive.
   295  	AddRequire bool
   296  }
   297  
   298  type RemoveDependencyArgs struct {
   299  	// The go.mod file URI.
   300  	URI protocol.DocumentURI
   301  	// The module path to remove.
   302  	ModulePath string
   303  	// If the module is tidied apart from the one unused diagnostic, we can
   304  	// run `go get module@none`, and then run `go mod tidy`. Otherwise, we
   305  	// must make textual edits.
   306  	OnlyDiagnostic bool
   307  }
   308  
   309  type EditGoDirectiveArgs struct {
   310  	// Any document URI within the relevant module.
   311  	URI protocol.DocumentURI
   312  	// The version to pass to `go mod edit -go`.
   313  	Version string
   314  }
   315  
   316  type GoGetPackageArgs struct {
   317  	// Any document URI within the relevant module.
   318  	URI protocol.DocumentURI
   319  	// The package to go get.
   320  	Pkg        string
   321  	AddRequire bool
   322  }
   323  
   324  type AddImportArgs struct {
   325  	// ImportPath is the target import path that should
   326  	// be added to the URI file
   327  	ImportPath string
   328  	// URI is the file that the ImportPath should be
   329  	// added to
   330  	URI protocol.DocumentURI
   331  }
   332  
   333  type ListKnownPackagesResult struct {
   334  	// Packages is a list of packages relative
   335  	// to the URIArg passed by the command request.
   336  	// In other words, it omits paths that are already
   337  	// imported or cannot be imported due to compiler
   338  	// restrictions.
   339  	Packages []string
   340  }
   341  
   342  type ListImportsResult struct {
   343  	// Imports is a list of imports in the requested file.
   344  	Imports []FileImport
   345  
   346  	// PackageImports is a list of all imports in the requested file's package.
   347  	PackageImports []PackageImport
   348  }
   349  
   350  type FileImport struct {
   351  	// Path is the import path of the import.
   352  	Path string
   353  	// Name is the name of the import, e.g. `foo` in `import foo "strings"`.
   354  	Name string
   355  }
   356  
   357  type PackageImport struct {
   358  	// Path is the import path of the import.
   359  	Path string
   360  }
   361  
   362  type DebuggingArgs struct {
   363  	// Optional: the address (including port) for the debug server to listen on.
   364  	// If not provided, the debug server will bind to "localhost:0", and the
   365  	// full debug URL will be contained in the result.
   366  	//
   367  	// If there is more than one gopls instance along the serving path (i.e. you
   368  	// are using a daemon), each gopls instance will attempt to start debugging.
   369  	// If Addr specifies a port, only the daemon will be able to bind to that
   370  	// port, and each intermediate gopls instance will fail to start debugging.
   371  	// For this reason it is recommended not to specify a port (or equivalently,
   372  	// to specify ":0").
   373  	//
   374  	// If the server was already debugging this field has no effect, and the
   375  	// result will contain the previously configured debug URL(s).
   376  	Addr string
   377  }
   378  
   379  type DebuggingResult struct {
   380  	// The URLs to use to access the debug servers, for all gopls instances in
   381  	// the serving path. For the common case of a single gopls instance (i.e. no
   382  	// daemon), this will be exactly one address.
   383  	//
   384  	// In the case of one or more gopls instances forwarding the LSP to a daemon,
   385  	// URLs will contain debug addresses for each server in the serving path, in
   386  	// serving order. The daemon debug address will be the last entry in the
   387  	// slice. If any intermediate gopls instance fails to start debugging, no
   388  	// error will be returned but the debug URL for that server in the URLs slice
   389  	// will be empty.
   390  	URLs []string
   391  }
   392  
   393  // StartProfileArgs holds the arguments to the StartProfile command.
   394  //
   395  // It is a placeholder for future compatibility.
   396  type StartProfileArgs struct {
   397  }
   398  
   399  // StartProfileResult holds the result of the StartProfile command.
   400  //
   401  // It is a placeholder for future compatibility.
   402  type StartProfileResult struct {
   403  }
   404  
   405  // StopProfileArgs holds the arguments to the StopProfile command.
   406  //
   407  // It is a placeholder for future compatibility.
   408  type StopProfileArgs struct {
   409  }
   410  
   411  // StopProfileResult holds the result to the StopProfile command.
   412  type StopProfileResult struct {
   413  	// File is the profile file name.
   414  	File string
   415  }
   416  
   417  type ResetGoModDiagnosticsArgs struct {
   418  	URIArg
   419  
   420  	// Optional: source of the diagnostics to reset.
   421  	// If not set, all resettable go.mod diagnostics will be cleared.
   422  	DiagnosticSource string
   423  }
   424  
   425  type VulncheckArgs struct {
   426  	// Any document in the directory from which govulncheck will run.
   427  	URI protocol.DocumentURI
   428  
   429  	// Package pattern. E.g. "", ".", "./...".
   430  	Pattern string
   431  
   432  	// TODO: -tests
   433  }
   434  
   435  // RunVulncheckResult holds the result of asynchronously starting the vulncheck
   436  // command.
   437  type RunVulncheckResult struct {
   438  	// Token holds the progress token for LSP workDone reporting of the vulncheck
   439  	// invocation.
   440  	Token protocol.ProgressToken
   441  }
   442  
   443  // CallStack models a trace of function calls starting
   444  // with a client function or method and ending with a
   445  // call to a vulnerable symbol.
   446  type CallStack []StackEntry
   447  
   448  // StackEntry models an element of a call stack.
   449  type StackEntry struct {
   450  	// See golang.org/x/exp/vulncheck.StackEntry.
   451  
   452  	// User-friendly representation of function/method names.
   453  	// e.g. package.funcName, package.(recvType).methodName, ...
   454  	Name string
   455  	URI  protocol.DocumentURI
   456  	Pos  protocol.Position // Start position. (0-based. Column is always 0)
   457  }
   458  
   459  // MemStatsResult holds selected fields from runtime.MemStats.
   460  type MemStatsResult struct {
   461  	HeapAlloc  uint64
   462  	HeapInUse  uint64
   463  	TotalAlloc uint64
   464  }
   465  
   466  // WorkspaceStatsResult returns information about the size and shape of the
   467  // workspace.
   468  type WorkspaceStatsResult struct {
   469  	Files FileStats   // file stats for the cache
   470  	Views []ViewStats // stats for each view in the session
   471  }
   472  
   473  // FileStats holds information about a set of files.
   474  type FileStats struct {
   475  	Total   int // total number of files
   476  	Largest int // number of bytes in the largest file
   477  	Errs    int // number of files that could not be read
   478  }
   479  
   480  // ViewStats holds information about a single View in the session.
   481  type ViewStats struct {
   482  	GoCommandVersion  string       // version of the Go command resolved for this view
   483  	AllPackages       PackageStats // package info for all packages (incl. dependencies)
   484  	WorkspacePackages PackageStats // package info for workspace packages
   485  	Diagnostics       int          // total number of diagnostics in the workspace
   486  }
   487  
   488  // PackageStats holds information about a collection of packages.
   489  type PackageStats struct {
   490  	Packages        int // total number of packages
   491  	LargestPackage  int // number of files in the largest package
   492  	CompiledGoFiles int // total number of compiled Go files across all packages
   493  	Modules         int // total number of unique modules
   494  }
   495  
   496  type RunGoWorkArgs struct {
   497  	ViewID    string   // ID of the view to run the command from
   498  	InitFirst bool     // Whether to run `go work init` first
   499  	Args      []string // Args to pass to `go work`
   500  }
   501  
   502  // AddTelemetryCountersArgs holds the arguments to the AddCounters command
   503  // that updates the telemetry counters.
   504  type AddTelemetryCountersArgs struct {
   505  	// Names and Values must have the same length.
   506  	Names  []string // Name of counters.
   507  	Values []int64  // Values added to the corresponding counters. Must be non-negative.
   508  }
   509  
   510  // ChangeSignatureArgs specifies a "change signature" refactoring to perform.
   511  type ChangeSignatureArgs struct {
   512  	RemoveParameter protocol.Location
   513  	// Whether to resolve and return the edits.
   514  	ResolveEdits bool
   515  }
   516  
   517  // DiagnoseFilesArgs specifies a set of files for which diagnostics are wanted.
   518  type DiagnoseFilesArgs struct {
   519  	Files []protocol.DocumentURI
   520  }
   521  
   522  // A View holds summary information about a cache.View.
   523  type View struct {
   524  	ID         string               // view ID (the index of this view among all views created)
   525  	Type       string               // view type (via cache.ViewType.String)
   526  	Root       protocol.DocumentURI // root dir of the view (e.g. containing go.mod or go.work)
   527  	Folder     protocol.DocumentURI // workspace folder associated with the view
   528  	EnvOverlay []string             // environment variable overrides
   529  }