go: cmd/go: generate shouldn't require a complete valid package
When developing a “go generate” script, it’s easy to create an invalid program as the output. When that happens, one can no longer run “go generate” because the package must typecheck before “go generate” is allowed to run. The result can be confusing, and I see no vital reason why this property must be true; moreover, sometimes it could be impossible to satisfy without hand-editing some files to get the package to the state where it could be run.
% go version
go version devel +0377f06168 Tue Dec 17 20:57:06 2019 +0000 darwin/amd64
potoroo=% ls
x.go
% cat x.go
package main
//go:generate sh -c "echo foo > gen.go"
func() main () {
}
% go generate
% go generate
can't load package: package .:
gen.go:1:1: expected 'package', found foo
% ls
gen.go x.go
% cat gen.go
foo
%
Let’s lift this requirement.
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Reactions: 17
- Comments: 16 (11 by maintainers)
Commits related to this issue
- cmd/go: allow generate to skip missing files This change allows go generate to process packages where files may disappear during code generation. See also #36422. Fixes #36068 — committed to tie/go by tie 3 years ago
- cmd/go: allow generate to skip missing files This change allows go generate to process packages where files may disappear during code generation. See also #36422. Updates #36068 — committed to tie/go by tie 3 years ago
@zephyrtronium, we already have a way to specify the package name: add a
packagedirective to the same source file that contains thego:generatedirective.Moreover, that seems like the clear tiebreaker, too: when
go generateinvokes a tool, it should setGOPACKAGEbased on the file containing that specificgo:generatecomment.Is this actually the case?
I think
go generateonly requires that the package clause can be parsed (along with build constraints).Which I think makes sense because
go generatesetsGOPACKAGEwhen it runs?