Parse prior hooks.go, if present (prep for more changes).

This commit is contained in:
Tye McQueen 2019-06-04 16:52:15 -07:00
Родитель 5b1d662d5a
Коммит 9e86b749a5
1 изменённых файлов: 26 добавлений и 10 удалений

Просмотреть файл

@ -2,6 +2,10 @@ package handlers
import (
"bytes"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"io"
"github.com/Unity-Technologies/truss/gengokit"
@ -12,25 +16,37 @@ const HookPath = "handlers/hooks.gotemplate"
// NewHook returns a new HookRender
func NewHook(prev io.Reader) (gengokit.Renderable, error) {
return &HookRender{
prev: prev,
}, nil
h := new(HookRender)
if prev != nil {
h.fset = token.NewFileSet()
var err error
h.ast, err = parser.ParseFile(h.fset, "", prev, parser.ParseComments)
if err != nil {
return nil, err
}
}
return h, nil
}
type HookRender struct {
prev io.Reader
fset *token.FileSet
ast *ast.File
}
// Render will return the existing file if it exists, otherwise it will return
// a brand new copy from the template.
func (h *HookRender) Render(_ string, _ *gengokit.Data) (io.Reader, error) {
if h.prev != nil {
return h.prev, nil
}
code := new(bytes.Buffer)
code.WriteString(templates.HookHead)
for _, hd := range templates.Hooks {
code.WriteString(hd.Code)
if h.ast == nil {
code.WriteString(templates.HookHead)
for _, hd := range templates.Hooks {
code.WriteString(hd.Code)
}
return code, nil
}
if err := printer.Fprint(code, h.fset, h.ast); nil != err {
return nil, err
}
return code, nil