可以在设计用于go generate的模板上使用gofmt吗?

huangapple go评论80阅读模式
英文:

Is it possible to use gofmt on templates that are designed to be used with go generate?

问题

我正在使用go:generate来自动生成一些数据库模型,并希望通过gofmt运行我的go模板,但是由于额外的{{ ... }}动态部分,它无法正常工作。

我是否漏掉了一些明显的东西?我希望gofmt的开发人员已经解决了这个问题,因为gofmtgo generate都是go工具链的重要组成部分。

显然,在go generate之后运行go fmt是可行的,但是让格式不良的模板(其中99%是go代码)存在感觉不太好。

英文:

I am using go:generate to handle automatically generating some database models and I was hoping to run my go template through gofmt, but it chokes with all the extra {{ ... }} dynamic sections.

Am I missing something obvious? I was hoping that this was a use case the gofmt people had addressed, given both gofmt and go generate are prominent parts of the go toolchain.

Obviously, it works to just run go fmt after go generate but it just feels dirty to have poorly formatted templates that are 99% go code sitting around.

答案1

得分: 17

大多数生成工具将模板执行到*bytes.Buffer中,使用format.Source格式化缓冲区字节,并将结果写入输出文件。

给定模板t和输出写入器w,代码大致如下:

var buf bytes.Buffer
if err := t.Execute(&buf, data); err != nil {
    // 处理错误
}
p, err := format.Source(buf.Bytes())
if err != nil {
    // 处理错误
}
w.Write(p)

对模板进行gofmt操作并不能确保输出结果是经过gofmt格式化的。考虑到使用go/format包很容易对输出进行gofmt操作,因此创建一个用于对模板进行gofmt的工具的价值很小。

英文:

Most generation tools execute the template to a *bytes.Buffer, format the buffer bytes using format.Source and write the result to the output file.

Given template t and output writer w, the code looks something like this:

var buf bytes.Buffer
if err := t.Execute(&buf, data); err != nil {
    // handle error
}
p, err := format.Source(buf.Bytes())
if err != nil {
    // handle error
}
w.Write(p)

Gofmting the template does not ensure that the output will be gofmted. Given how easy it is to gofmt the output using the go/format package, there's little value in creating a tool to gofmt templates.

huangapple
  • 本文由 发表于 2015年12月7日 11:43:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/34126083.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定