Skip to content

x/tools/gopls: add "if err != nil" snippet completion for Test/Benchmark Functions #43310

Closed
@marwan-at-work

Description

@marwan-at-work

One of my favorite features of Gopls is that it can auto-complete my error returns by writing a contextual if-statement block like so:

if err != nil {
  return <zero types>, ${1:err}
}

It accomplishes the above by doing the following:

  1. Checks if the enclosing function's signature returns an error
  2. Checks if the cursor's previous statement assigns an error.
  3. Offers an auto-complete snippet that writes out the entire block above.

The main logic of this feature lives here: https://github.com/golang/tools/blob/1965356128881de7178c4c0a1cbeb15035659dea/internal/lsp/source/completion/statements.go#L175

I propose that we update this function to include the following use case (that I find myself running into a lot):

func TestSomeLogic(t *testing.T) {
  _, err := os.Open("foo")
  <>
}

If the client asked for completion at the previous cursor, we should offer the following completion:

if err != nil {
  t.Fatal(err)
}

Reasoning:

Writing if err != nil { t.Fatal(err) } is quite common.

Quickly searching for the statement in popular repos I found that in the x/tools repository, this exact block appears about 393 times:

Screen Shot 2020-12-21 at 4 35 59 PM

While, in the moby/moby repository, it appears 749 times:

Screen Shot 2020-12-21 at 4 36 16 PM

Therefore, having this auto-completion will make Go developer's write tests more quickly when they need it.

In the future, more clever UX can be sketched out that will handle other common scenarios such as Fatalf but I believe as an initial implementation, t.Fatal(err) is a really good start and perhaps good enough.

Metadata

Metadata

Assignees

No one assigned

    Labels

    FeatureRequestIssues asking for a new feature that does not need a proposal.FrozenDueToAgeToolsThis label describes issues relating to any tools in the x/tools repository.goplsIssues related to the Go language server, gopls.help wanted

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions