github.com/jgarto/itcv@v0.0.0-20180826224514-4eea09c1aa0d/cmd/coreGen/core_gen.go (about)

     1  package main
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"io"
     7  	"strings"
     8  	"text/template"
     9  )
    10  
    11  type coreGen struct {
    12  	buf  *bytes.Buffer
    13  	tbuf *bytes.Buffer
    14  	jbuf *bytes.Buffer
    15  }
    16  
    17  func newCoreGen() *coreGen {
    18  	return &coreGen{
    19  		buf:  bytes.NewBuffer(nil),
    20  		tbuf: bytes.NewBuffer(nil),
    21  		jbuf: bytes.NewBuffer(nil),
    22  	}
    23  }
    24  
    25  func (c *coreGen) pf(format string, vals ...interface{}) {
    26  	fmt.Fprintf(c.buf, format, vals...)
    27  }
    28  
    29  func (c *coreGen) tpf(format string, vals ...interface{}) {
    30  	fmt.Fprintf(c.tbuf, format, vals...)
    31  }
    32  
    33  func (c *coreGen) jpf(format string, vals ...interface{}) {
    34  	fmt.Fprintf(c.jbuf, format, vals...)
    35  }
    36  
    37  func (c *coreGen) pln(vals ...interface{}) {
    38  	fmt.Fprintln(c.buf, vals...)
    39  }
    40  
    41  func (c *coreGen) tpln(vals ...interface{}) {
    42  	fmt.Fprintln(c.tbuf, vals...)
    43  }
    44  
    45  func (c *coreGen) jpln(vals ...interface{}) {
    46  	fmt.Fprintln(c.jbuf, vals...)
    47  }
    48  
    49  func (c *coreGen) pt(tmpl string, val interface{}) {
    50  	tmplExec(c.buf, tmpl, val)
    51  }
    52  
    53  func (c *coreGen) tpt(tmpl string, val interface{}) {
    54  	tmplExec(c.tbuf, tmpl, val)
    55  }
    56  
    57  func (c *coreGen) jpt(tmpl string, val interface{}) {
    58  	tmplExec(c.jbuf, tmpl, val)
    59  }
    60  
    61  func tmplExec(w io.Writer, tmpl string, val interface{}) {
    62  	tmpl = strings.TrimPrefix(tmpl, "\n")
    63  
    64  	t := template.New("tmp")
    65  
    66  	_, err := t.Parse(tmpl)
    67  	if err != nil {
    68  		fatalf("unable to parse template: %v", err)
    69  	}
    70  
    71  	err = t.Execute(w, val)
    72  	if err != nil {
    73  		fatalf("cannot execute template: %v", err)
    74  	}
    75  }