internal/lsp/source: don't format generated files

Fixes golang/go#49555

Change-Id: I53e3c0d34be6a545386d6766371fbeda8a2b2ffb
GitHub-Last-Rev: 516168765671c8135523fcf801f50455b352bdab
GitHub-Pull-Request: golang/tools#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>
This commit is contained in:
Shoshin Nikita 2021-12-03 16:44:45 +00:00 committed by Robert Findley
parent c882a49eac
commit feb39d0cd7
2 changed files with 38 additions and 0 deletions

View File

@ -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)
}
})
}

View File

@ -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