templateUtil.go 1.74 KB
Newer Older
Eric Myhre's avatar
Eric Myhre committed
1 2 3 4 5 6 7 8 9
package gengo

import (
	"io"
	"text/template"

	wish "github.com/warpfork/go-wish"
)

10
func doTemplate(tmplstr string, w io.Writer, adjCfg *AdjunctCfg, data interface{}) {
11
	tmpl := template.Must(template.New("").
12 13 14 15
		Funcs(template.FuncMap{
			"TypeSymbol":       adjCfg.TypeSymbol,
			"FieldSymbolLower": adjCfg.FieldSymbolLower,
			"FieldSymbolUpper": adjCfg.FieldSymbolUpper,
16
			"MaybeUsesPtr":     adjCfg.MaybeUsesPtr,
17
			"add":              func(a, b int) int { return a + b },
18
		}).
19 20 21 22
		// Seriously consider prepending `{{ $dot := . }}` (or 'top', or something).
		// Or a func into the map that causes `dot` to mean `func() interface{} { return data }`.
		// The number of times that the range feature has a dummy capture line above it is... not reasonable.
		//  (Grep for "/* ranging modifies dot, unhelpfully */" -- empirically, it's over 20 times already.)
23
		Parse(wish.Dedent(tmplstr)))
Eric Myhre's avatar
Eric Myhre committed
24 25 26 27
	if err := tmpl.Execute(w, data); err != nil {
		panic(err)
	}
}
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42

// We really need to do some more composable stuff around here.
// Generators should probably be carrying down their own doTemplate methods that curry customizations.
// E.g., map generators would benefit hugely from being able to make a clause for "entTypeStrung", "mTypeStrung", etc.
//
// Open question: how exactly?  Should some of this stuff should be composed by:
//   - composing template fragments;
//   - amending the funcmap;
//   - computing the whole result and injecting it as a string;
//   - ... combinations of the above?
// Adding to the complexity of the question is that sometimes we want to be
//  doing composition inside the output (e.g. DRY by functions in the result,
//   rather than by DRY'ing the templates).
// Best practice to make this evolve nicely is not at all obvious to this author.
//