From 8df9e1ecf28396497f1a60e255467b9bdc0133c6 Mon Sep 17 00:00:00 2001 From: Alex Bezzubov Date: Thu, 16 Feb 2023 17:47:44 +0100 Subject: [PATCH] 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 --- .../code-generator/generator/generator.go | 22 ++++++------------- internal/code-generator/main.go | 2 +- 2 files changed, 8 insertions(+), 16 deletions(-) diff --git a/internal/code-generator/generator/generator.go b/internal/code-generator/generator/generator.go index ce0bdd4..b081d47 100644 --- a/internal/code-generator/generator/generator.go +++ b/internal/code-generator/generator/generator.go @@ -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) } diff --git a/internal/code-generator/main.go b/internal/code-generator/main.go index 5eda1da..4fa40f4 100644 --- a/internal/code-generator/main.go +++ b/internal/code-generator/main.go @@ -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) } } }