Skip to content

Commit

Permalink
internal/lsp/source: don't format generated files
Browse files Browse the repository at this point in the history
Fixes golang/go#49555

Change-Id: I53e3c0d34be6a545386d6766371fbeda8a2b2ffb
GitHub-Last-Rev: 5161687
GitHub-Pull-Request: #349
Reviewed-on: https://go-review.googlesource.com/c/tools/+/365295
Reviewed-by: Robert Findley <rfindley@google.com>
Trust: Robert Findley <rfindley@google.com>
Trust: Hyang-Ah Hana Kim <hyangah@gmail.com>
Run-TryBot: Robert Findley <rfindley@google.com>
gopls-CI: kokoro <noreply+kokoro@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
  • Loading branch information
ShoshinNikita authored and findleyr committed Dec 6, 2021
1 parent c882a49 commit feb39d0
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
33 changes: 33 additions & 0 deletions gopls/internal/regtest/misc/formatting_test.go
Expand Up @@ -268,3 +268,36 @@ func main() {
})
}
}

func TestFormattingOfGeneratedFile_Issue49555(t *testing.T) {
const input = `
-- main.go --
// Code generated by generator.go. DO NOT EDIT.
package main
import "fmt"
func main() {
fmt.Print("hello")
}
`

Run(t, input, func(t *testing.T, env *Env) {
wantErrSuffix := "file is generated"

env.OpenFile("main.go")
err := env.Editor.FormatBuffer(env.Ctx, "main.go")
if err == nil {
t.Fatal("expected error, got nil")
}
// Check only the suffix because an error contains a dynamic path to main.go
if !strings.HasSuffix(err.Error(), wantErrSuffix) {
t.Fatalf("unexpected error %q, want suffix %q", err.Error(), wantErrSuffix)
}
})
}
5 changes: 5 additions & 0 deletions internal/lsp/source/format.go
Expand Up @@ -29,6 +29,11 @@ func Format(ctx context.Context, snapshot Snapshot, fh FileHandle) ([]protocol.T
ctx, done := event.Start(ctx, "source.Format")
defer done()

// Generated files shouldn't be edited. So, don't format them
if IsGenerated(ctx, snapshot, fh.URI()) {
return nil, fmt.Errorf("can't format %q: file is generated", fh.URI().Filename())
}

pgf, err := snapshot.ParseGo(ctx, fh, ParseFull)
if err != nil {
return nil, err
Expand Down

0 comments on commit feb39d0

Please sign in to comment.