英文:
is there a way that go generate will skip unchanged files/ pkg
问题
有没有一种简单的方法来运行"go generate ./...",并且在所有调用generate的pkg文件没有改变的情况下,go generate会跳过再次生成这些文件?(原因是生成过程耗时)
例如:
-a (directory)
example1.go //包含 //go:generate -output generated_example1.go
example2.go //包含 //go:generate -output generated_example2.go
...
假设我有7个要生成的文件,我只改变了文件'example1.go',所以当我运行"go generate ./..."时,我希望它只生成example1,而不是尝试生成所有7个文件。
(从内部目录调用"go generate"不能解决这个问题,因为同一个目录下有几个要生成的文件。)
英文:
Is there an easy way to run go generate ./...
and in case that all the file in the pkg that call the generate didn't change- that go generate skip generating again this file?
(the reason is time consumption on generate)
For example:
-a (directory)
example1.go //contain //go:generate -output generated_example1.go
example2.go //contain //go:generate -output generated_example2.go
...
lets say i have 7 files to generate,
and I had changed only file 'example1.go'
so when i run go generate ./... I would like that it will not try to generate all the 7 files but only example1 because only this source has changed
(calling the go generate from inner directory will not solve the issue because there are couple of files to generate from same directory.)
答案1
得分: 3
这是不支持的。你使用go generate
命令运行的工具可能支持这个功能。参考相关链接:https://stackoverflow.com/questions/57757242/how-to-run-go-generate-only-for-changed-templates
一些原因是:go generate
可以用来运行任意工具,不仅仅是源代码生成/操作工具,再次运行可能不会产生相同的输出/副作用。此外,工具的运行可能会失败,而go generate
不会保留成功/失败运行的数据库,因此即使源文件没有更改,它也不知道要再次运行哪些命令。
总的来说,你的工具应该检查所需输出文件(及其版本)的存在性,以决定是否需要(重新)生成。这比想象的要简单:由于生成是在源文件更改后运行的,只需比较最后修改的时间戳即可。如果源文件(包含//go:generate
)的时间戳较新,则应该运行生成。否则可以跳过。注意,go generate
将$GOFILE
环境变量设置为触发该命令的文件的基本名称,因此很容易进行检查。
英文:
This is not supported. The tool (command) you run with go generate
may support this. See related: https://stackoverflow.com/questions/57757242/how-to-run-go-generate-only-for-changed-templates
Some reasoning: go generate
may be used to run arbitrary tool, not just source generation / manipulation tools, and running again may not have the same output / side effect. Also, running the tools may fail, and go generate
does not keep a database of successful / failed runs, in which case it would not know which commands to run again even if source files didn't change.
All-in-all, your tool should check the existence of the desired output files (and their versions) to decide if (re-)generation is needed. This is easier than one might think though: since generation runs after the source file change, it's enough to compare the last modified timestamps. If the source (containing //go:generate
) has a newer timestamp, generation should run. Otherwise it can be skipped. Note that go generate
sets the $GOFILE
env var to the base name of the file that triggered the command, so it's easy to check this.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论