2020-03-22

text/templateを使って良い感じにファイルジェネレートできるprotocプラグインを作った

Goのtext/templateのリテラルで記述されたテンプレートファイルを使って、protofileからファイルを出力するprotocプラグインを作ってみましたー。
protobufで自動生成されるファイル郡以外にも自動でコードジェネレートしたいというのがモチベーション。

protocのプラグインの作り方はこちらを参考にしました

インストール方法

$ go get github.com/tzmfreedom/ptoroc-gen-template

使い方

protocで–template_outを指定すればOK

$ protoc -I. --template_out=/path/to/template:. target.proto

テンプレートファイルはこんな感じでtext/templateで書きます

type {{ .Prefix }}{{ .Name }} struct {
    {{ range .Fields -}}
    {{ getName .Name }} {{ propertyType . $.PackageName }}
{{ end -}}
}

これにこんな感じなprotoを食わせると

syntax = "proto3";

package helloworld;


// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}

こういうファイルが出力されます

type HelloRequest struct {
    Name string
}

type HelloReply struct {
    Message string
}
このエントリーをはてなブックマークに追加