Awesome
gg
gg
is a General Golang Code Generator: A Good Game to play with Golang.
package main
import (
"fmt"
. "github.com/Xuanwo/gg"
)
func main() {
f := NewGroup()
f.AddPackage("main")
f.NewImport().
AddPath("fmt")
f.NewFunction("main").AddBody(
String(`fmt.Println("%s")`, "Hello, World!"),
)
fmt.Println(f.String())
}
Output (after go fmt
)
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Design
gg
is a general golang code generator that designed for resolving problems exists in the following tools:
- text/template: Additional syntax, Steep learning curve, Complex logic is difficult to maintain
- dave/jennifer: Overly abstract APIs, user need to take care about
()
,,
everywhere. - kubernetes-sigs/kubebuilder: Parse data from struct tags/comments, not a general code generator.
In short, gg
will provide near-native golang syntax and helpful API so play a good game with Golang. With gg
, we can generate golang code more easily and understandable.
Usage
Package Name
f := Group()
f.AddPackage("main")
// package main
Imports
f := Group()
f.NewImport().
AddPath("context").
AddDot("math").
AddBlank("time").
AddAlias("x", "testing")
// import (
// "context"
// . "math"
// _ "time"
// x "testing"
// )
Function
f := Group()
f.NewFunction("hello").
WithReceiver("v", "*World").
AddParameter("content", "string").
AddParameter("times", "int").
AddResult("v", "string").
AddBody(gg.String(`return fmt.Sprintf("say %s in %d times", content, times)`))
// func (v *World) hello(content string, times int) (v string) {
// return fmt.Sprintf("say %s in %d times", content, times)
//}
Struct
f := Group()
f.NewStruct("World").
AddField("x", "int64").
AddField("y", "string")
// type World struct {
// x int64
// y string
//}
Acknowledgement
gg
is inspired by dave/jennifer, I borrowed most ideas and some code from it. Nice work!