"go generate" 多行命令

"go generate" multiline command

我试图在编译代码之前使用 //go:generate 到 运行 外部工具,并且由于我需要传递一定数量的参数,因此该行变得相当长。

好像没有办法写多行go:generate命令,对吗?有替代方法吗?

谢谢

没有办法将go generate命令分成几行,但是有一些小技巧。

如果你需要运行多个短命令,你可以像下面这样一个一个地写。

//go:generate echo command A
//go:generate echo command B
//go:generate ls

您还应该知道没有 bash 脚本,而是原始命令。所以下面的作品并不像人们想象的那样。

//go:generate echo something | tr a-z A-Z > into_file
// result in "something | tr a-z A-Z > into_file"

对于较长或复杂的命令,您应该使用从 go:generate 评论中调用的单独脚本(或者可能是 go 程序)。

//go:generate sh generate.sh
//go:generate go run generator.go arg-A arg-B

在generator.go中你应该使用构建标签来防止它与其他文件正常编译。

// +build ignore

package main
// ...

学习围棋最好的地方是围棋资源:https://github.com/golang/go/blob/master/src/runtime/runtime.go#L13

这远非理想的解决方案,但您可以使用形式为

的指令
//go:generate -command <alias> <command-with-parameters>

上面的指令指定,仅对当前源文件的剩余部分<alias>等同于命令<command-with-parameters>.

此方法可能对您的情况有用,因为您提到您需要传递一定数量的参数(我假设有很多)。您可以使用它来模拟 换行符。我说 single 因为嵌套别名不起作用(至少现在)。

一个例子:

//go:generate BAKE "ramen"


  // The above go:generate directive does NOT work, unless:
  //  - You somehow have bake on your path.
  //  - You did a `//go:generate -command BAKE ...`


/* Now, assuming you have a command `kitchen-tools` with lots of possible parameters... */

//go:generate -command BAKE kitchen-tools -appliance=sun -temp=5800K -time=1ns 
//go:generate BAKE -panic=if-burnt -safety=fire_extinguisher,mitts "fresh pizza"


  // The previous //go:generate line runs the following command:
  //  kitchen-tools -appliance=sun -temp=5800K -time=1ns -panic=always -safety=fire_extinguisher,mitts "fresh pizza"

/* BAKE can be used as many times as necessary for the rest of the file. For instance... */

//go:generate BAKE -no-return -unsafe "grand piano"
  

此外,我建议您使用构建标签 generate(而不是 ignore 之类的东西),因为 go generate 工具在检查您的文件时会设置构建标签 generate

// +build generate

package main
// ...