code-gen: improve ability to debug failures

Code generation failres were hard to identify and undertand

 * avoid unnececary re-formating & memory allocation
 * return clear formatting errors
This commit is contained in:
Alex Bezzubov 2023-02-16 17:47:44 +01:00
parent 6d99af7bbc
commit 8df9e1ecf2
2 changed files with 8 additions and 16 deletions

View File

@ -3,7 +3,6 @@
package generator
import (
"bytes"
"fmt"
"go/format"
"io"
@ -22,12 +21,15 @@ type File func(fileToParse, samplesDir, outPath, tmplPath, tmplName, commit stri
func formatedWrite(outPath string, source []byte) error {
formatedSource, err := format.Source(source)
if err != nil {
return err
err = fmt.Errorf("'go fmt' fails on %v", err)
// write un-formatter source to simplify debugging
formatedSource = source
}
if err := ioutil.WriteFile(outPath, formatedSource, 0666); err != nil {
return err
}
return nil
return err
}
func executeTemplate(w io.Writer, name, path, commit string, fmap template.FuncMap, data interface{}) error {
@ -51,20 +53,10 @@ func executeTemplate(w io.Writer, name, path, commit string, fmap template.FuncM
headerPath := filepath.Join(filepath.Dir(path), headerTmpl)
h := template.Must(template.New(headerTmpl).Funcs(fmap).ParseFiles(headerPath))
buf := bytes.NewBuffer(nil)
if err := h.Execute(buf, data); err != nil {
if err := h.Execute(w, data); err != nil {
return err
}
t := template.Must(template.New(name).Funcs(fmap).ParseFiles(path))
if err := t.Execute(buf, data); err != nil {
return err
}
src, err := format.Source(buf.Bytes())
if err != nil {
return err
}
_, err = w.Write(src)
return err
return t.Execute(w, data)
}

View File

@ -134,7 +134,7 @@ func main() {
for _, file := range fileList {
if err := file.generate(file.fileToParse, file.samplesDir, file.outPath, file.tmplPath, file.tmplName, file.commit); err != nil {
log.Fatalf("error generating template %q to %q: %+v", file.tmplPath, file.outPath, err)
log.Fatalf("failed to generate %q from %q - %+v", file.outPath, file.tmplPath, err)
}
}
}