simple utility to facilitate mundane work by generating code based on templates and variables.
gg
hinges on the following:
- json schema with definitions that will be used for code generation;
- text/template package and its semantics;
- template files should end with
.tmpl
.
The programme needs Go ^1.18 to be compiled.
go install github.com/omerkaya1/gg@latest
-c string
path to config (shortened)
-configuration string
path to config
-o string
output destination path (shortened)
-output string
output destination path
-separator
print separator between files
-t string
path to templates (shortened)
-templates string
path to templates
Currently, gg
supports global template variables (the ones that span throughout files and may occur in a lot of places)
and local variables (the ones that are specific to the file and won't be used elsewhere).
Placeholders for global variables should be prefixed with .Global pattern, while local ones with .Local.
By default, gg
prints its output to STDOUT.
If the template path is not provided, gg
looks for templates in the working directory it was called.
Otherwise, use -o path
to specify output directory.
Suppose we have this setup:
templates are stored in our local directory:
$ ls -a ./templates
main.tmpl go.mod.tmpl
main.go file template
package main
import (
"fmt"
)
const (
serviceName = "{{.Global.ServiceName}}"
)
func main() { {{if .Local.PrintThis}}
fmt.Printf("this is: "){{end}}
fmt.Println(serviceName)
}
go.mod file template
module {{.Global.ModuleName}}
go {{.Local.GoVersion}}
json config file
{
"global": {
"ServiceName": "New Awesome Service",
"ModuleName": "github.com/omerkaya1/new-awesome-service"
},
"files": [
{
"name": "main.go",
"template": "main.tmpl",
"path": "",
"local": {
"PrintThis": true
}
},
{
"name": "go.mod",
"template": "go.mod.tmpl",
"path": "",
"local": {
"GoVersion": "1.19"
}
}
],
"commands": [
{
"name": "gofmt",
"args": [
"-s"
]
},
{
"name": "go",
"args": [
"mod",
"tidy",
"-e"
]
}
]
}
Running:
gg -c config.json -o /destination/path -t /path/to/templates
Produces:
$ ls /destination/path
go.mod main.go
With:
- /destination/path/main.go
package main
import (
"fmt"
)
const (
serviceName = "New Awesome Service"
)
func main() {
fmt.Printf("this is: ")
fmt.Println(serviceName)
}
- /destination/path/go.mod
module github.com/omerkaya1/new-awesome-service
go 1.19
See examples for more details.
You can achieve the same result by just piping config data to the programme:
cat examples/config.json | gg -t examples
or
gg -t examples < examples/config.json
Simple deletion of the binary should suffice:
rm $(which gg)