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

Most upvoted comments

@zephyrtronium, we already have a way to specify the package name: add a package directive to the same source file that contains the go:generate directive.

Moreover, that seems like the clear tiebreaker, too: when go generate invokes a tool, it should set GOPACKAGE based on the file containing that specific go:generate comment.

the package must typecheck before “go generate” is allowed to run

Is this actually the case?

$ cat a.go
package a

blah
$ cat b.go
package a

$ cat c.go
// +build ignnore

package main

$ go generate

I think go generate only requires that the package clause can be parsed (along with build constraints).

Which I think makes sense because go generate sets GOPACKAGE when it runs?