protogen-lib
A lightweight Go library for writing Protocol Buffer code generators (protoc plugins) without depending on the standard protogen package. This library provides a clean, minimal interface for creating protoc plugins with built-in support for command-line options parsing and file generation.
Features
- Declarative options parsing: Declare the protogen options similar to cobra / urfavecli's Flags
- Customizable Request Validation: Provide custom validation logic to your options to ensure correct input
- Customizable Codegen: Control how the codegen transforms the Proto File's AST into output files
Installation
go get github.com/junpeng-jp/protogen-lib
Quick Start
Here's a minimal example of a protoc plugin using protogen-lib:
package main
import (
"fmt"
"github.com/junpeng-jp/protogen-lib/command"
"github.com/junpeng-jp/protogen-lib/opts"
)
func main() {
var outputDir string
var verbose bool
cmd := &command.GenerateCommand{
Name: "my-plugin",
Version: "1.0.0",
Options: []opts.Option{
&opts.StringOption{
Name: "output_dir",
Default: ".",
Destination: &outputDir,
},
&opts.BoolOption{
Name: "verbose",
Default: false,
Destination: &verbose,
},
},
Generate: func(pl *command.PluginContext) error {
for _, file := range pl.Files {
if !pl.FilesToGenerate[file.GetName()] {
continue
}
// Generate output file
outFile := pl.NewGeneratedFile(file.GetName() + ".generated.go")
outFile.Fprint("// Generated code for", file.GetName())
outFile.Fprint("package", file.GetPackage())
// ... more generation logic
}
return nil
},
}
if err := cmd.Run(); err != nil {
panic(err)
}
}
Usage with protoc
Once compiled, the plugin can be used with protoc:
protoc --plugin=protoc-gen-my-plugin=./my-plugin \
--my-plugin_out=output_dir=./gen,verbose=true:. \
*.proto
Feature Coverage
A non-exhaustive list of features that are not yet implemented.
Some might be implemented in the future.
| Feature |
protogen-lib |
protogen |
| Option Parsing |
string & boolean |
✅ |
| Option Validation |
✅ |
✅ |
| Pre-processing of Codegen Request |
❌ |
✅ |
| Annotations |
❌ |
✅ |
| Source Code Info |
❌ |
✅ |
| Comments |
❌ |
✅ |
| ... |
|
|