“去生成”多行命令

Joh*_*ite 5 code-generation go

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

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

谢谢

小智 6

没有办法将 go generate 命令拆分成几行,但是有一些提示。

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

//go:generate echo command A
//go:generate echo command B
//go:generate ls
Run Code Online (Sandbox Code Playgroud)

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

//go:generate echo something | tr a-z A-Z > into_file
// result in "something | tr a-z A-Z > into_file"
Run Code Online (Sandbox Code Playgroud)

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

//go:generate sh generate.sh
//go:generate go run generator.go arg-A arg-B
Run Code Online (Sandbox Code Playgroud)

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

// +build ignore

package main
// ...
Run Code Online (Sandbox Code Playgroud)

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


Yen*_*ang 5

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

//go:generate -command <alias> <command-with-parameters>
Run Code Online (Sandbox Code Playgroud)

上面的指令仅指定当前源文件的其余部分,这<alias>相当于命令<command-with-parameters>

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

一个例子:

//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"
  

Run Code Online (Sandbox Code Playgroud)

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

//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"
  

Run Code Online (Sandbox Code Playgroud)