Skip to content

Commit feb39d0

Browse files
ShoshinNikitafindleyr
authored andcommitted
internal/lsp/source: don't format generated files
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 <[email protected]> Trust: Robert Findley <[email protected]> Trust: Hyang-Ah Hana Kim <[email protected]> Run-TryBot: Robert Findley <[email protected]> gopls-CI: kokoro <[email protected]> TryBot-Result: Gopher Robot <[email protected]>
1 parent c882a49 commit feb39d0

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

gopls/internal/regtest/misc/formatting_test.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,3 +268,36 @@ func main() {
268268
})
269269
}
270270
}
271+
272+
func TestFormattingOfGeneratedFile_Issue49555(t *testing.T) {
273+
const input = `
274+
-- main.go --
275+
// Code generated by generator.go. DO NOT EDIT.
276+
277+
package main
278+
279+
import "fmt"
280+
281+
func main() {
282+
283+
284+
285+
286+
fmt.Print("hello")
287+
}
288+
`
289+
290+
Run(t, input, func(t *testing.T, env *Env) {
291+
wantErrSuffix := "file is generated"
292+
293+
env.OpenFile("main.go")
294+
err := env.Editor.FormatBuffer(env.Ctx, "main.go")
295+
if err == nil {
296+
t.Fatal("expected error, got nil")
297+
}
298+
// Check only the suffix because an error contains a dynamic path to main.go
299+
if !strings.HasSuffix(err.Error(), wantErrSuffix) {
300+
t.Fatalf("unexpected error %q, want suffix %q", err.Error(), wantErrSuffix)
301+
}
302+
})
303+
}

internal/lsp/source/format.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,11 @@ func Format(ctx context.Context, snapshot Snapshot, fh FileHandle) ([]protocol.T
2929
ctx, done := event.Start(ctx, "source.Format")
3030
defer done()
3131

32+
// Generated files shouldn't be edited. So, don't format them
33+
if IsGenerated(ctx, snapshot, fh.URI()) {
34+
return nil, fmt.Errorf("can't format %q: file is generated", fh.URI().Filename())
35+
}
36+
3237
pgf, err := snapshot.ParseGo(ctx, fh, ParseFull)
3338
if err != nil {
3439
return nil, err

0 commit comments

Comments
 (0)