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!")
}
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.
f := Group()
f.AddPackage("main")
// package main
f := Group()
f.NewImport().
AddPath("context").
AddDot("math").
AddBlank("time").
AddAlias("x", "testing")
// import (
// "context"
// . "math"
// _ "time"
// x "testing"
// )
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)
//}
f := Group()
f.NewStruct("World").
AddField("x", "int64").
AddField("y", "string")
// type World struct {
// x int64
// y string
//}
gg
is inspired by dave/jennifer, I borrowed most ideas and some code from it. Nice work!