Description
gopls refuses to execute a Format
or CodeAction(source.organizeImports)
request on a file containing a // Code generated by...
comment; it fails with an can't format %q: file is generated
error. For Format
, this behavior was implemented in https://go.dev/cl/365295 to address issue #49555, in which a user objected to the formatting of generated files on the grounds that some code generators emit misformatted output. For CodeAction, this behavior was implemented in https://go.dev/cl/230999 to address issue #38467, in which a different user, whose client is configured to apply quick fixes on save, objected to arbitrary unspecified quick fixes being applied in generated files.
I believe this change was a mistake. Go developers have plenty of reasons to edit generated files, for example to quickly experiment with changes without having to rewrite the code generator, or to add a log.Print statement while debugging. If a client asks gopls to format a file or organize its imports, gopls should do that, even if the file contains a "generated..." comment.
I agree with @hyangah that a better fix to the original problem is to fix all the code generators; there is really no excuse for generating misformatted files. And I agree with @findleyr that when the client makes a reasonable request, the server should honor it.
I would also support having gopls send a showMessage
notification to the client when it first receives a DidChange event to an open file that is generated and differs from its on-disk state, but this should be tied to editing, not to other operations. [Edit: in fact it has had this feature for a long time.]
Related: