oef/template_generator/main.go
2019-11-13 12:06:29 +01:00

81 lines
1.6 KiB
Go

package main
import (
"flag"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"text/template"
tpl_util "git.andreafazzi.eu/andrea/oef/util/template"
"github.com/jinzhu/inflection"
)
var (
fnPatterns = map[string]string{
"all": "%s",
"show": "%s_show",
"add_update": "%s_add_update",
}
)
func toUpper(str string) string {
return strings.Title(str)
}
func main() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
flag.PrintDefaults()
}
outDir := flag.String("outdir", "./templates", "Output directory")
tplDir := flag.String("tpldir", "./template_generator/templates", "Generator template directory")
flag.Parse()
if len(flag.Args()) == 0 {
flag.Usage()
return
}
funcMap := template.FuncMap{
"toUpper": toUpper,
}
model := flag.Args()[0]
for tplName, pattern := range fnPatterns {
var data struct {
Model string
Models string
}
data.Model = inflection.Singular(model)
data.Models = inflection.Plural(model)
name := fmt.Sprintf(pattern, strings.ToLower(data.Models))
tpl, err := tpl_util.LoadTextTemplate(filepath.Join(*tplDir, tplName+".tpl"), funcMap)
if err != nil {
panic(err)
}
filename := filepath.Join(*outDir, name+".html.tpl")
if _, err := os.Stat(filename); err != nil {
oFn, err := os.Create(filename)
if err != nil {
panic(err)
}
defer oFn.Close()
log.Printf("Generating html template %s for model %s...", filename, name)
err = tpl.Execute(oFn, data)
if err != nil {
panic(err)
}
} else {
log.Printf("Template %s already exists. Skipping.", filename)
}
}
}