github.com/artisanhe/tools@v1.0.1-0.20210607022958-19a8fef2eb04/codegen/genfile.go (about)

     1  package codegen
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"io"
     7  	"text/template"
     8  )
     9  
    10  func NewGenFile(pkgName string, filename string) *GenFile {
    11  	return &GenFile{
    12  		PkgName:  pkgName,
    13  		Filename: filename,
    14  		Importer: &Importer{},
    15  		Buffer:   &bytes.Buffer{},
    16  	}
    17  }
    18  
    19  type GenFile struct {
    20  	Filename string
    21  	PkgName  string
    22  	Data     interface{}
    23  	*bytes.Buffer
    24  	*Importer
    25  }
    26  
    27  func (f *GenFile) WithData(data interface{}) *GenFile {
    28  	f.Data = data
    29  	return f
    30  }
    31  
    32  func (f *GenFile) Block(tpl string) *GenFile {
    33  	f.writeTo(f.Buffer, tpl)
    34  	return f
    35  }
    36  
    37  func (f *GenFile) writeTo(writer io.Writer, tpl string) {
    38  	t, parseErr := template.New(f.Filename).Parse(tpl)
    39  	if parseErr != nil {
    40  		panic(fmt.Sprintf("template Prase failded: %s", parseErr.Error()))
    41  	}
    42  	err := t.Execute(writer, f)
    43  	if err != nil {
    44  		panic(fmt.Sprintf("template Execute failded: %s", err.Error()))
    45  	}
    46  }
    47  
    48  func (f *GenFile) String() string {
    49  	return fmt.Sprintf(`
    50  package %s
    51  %s
    52  %s
    53  `,
    54  		f.PkgName,
    55  		f.Importer.String(),
    56  		f.Buffer.String(),
    57  	)
    58  }
    59  
    60  func (f *GenFile) OutputTo(outputs Outputs) {
    61  	outputs.Add(f.Filename, f.String())
    62  }