Skip to content

Commit

Permalink
fix: file name inserted in empty templates (#138)
Browse files Browse the repository at this point in the history
* remove shared template state

* ensure files with empty whitespace aren't written to output

* remove gocyclo
  • Loading branch information
hay-kot committed May 12, 2024
1 parent f9ada30 commit cd5caae
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 5 deletions.
1 change: 1 addition & 0 deletions .examples/nested/{{ .ProjectKebab }}/child/comment.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{{/* file shouldn't render when only comment present */}}
1 change: 0 additions & 1 deletion .golangci.toml
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ enable = [
"unconvert",
"unused",
"whitespace",
"gocyclo",
"exhaustive",
"typecheck",
"asciicheck",
Expand Down
12 changes: 8 additions & 4 deletions app/core/engine/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ var ErrTemplateIsEmpty = fmt.Errorf("template is empty")
type Vars map[string]any

type Engine struct {
baseTemplate *template.Template
fm template.FuncMap
}

func New() *Engine {
Expand All @@ -27,10 +27,14 @@ func New() *Engine {
fm["wraptmpl"] = wraptmpl

return &Engine{
baseTemplate: template.New("scaffold").Funcs(fm),
fm: fm,
}
}

func (e *Engine) parse(tmpl string) (*template.Template, error) {
return template.New("scaffold").Funcs(e.fm).Parse(tmpl)
}

func isTemplate(s string) bool {
return strings.Contains(s, "{{")
}
Expand All @@ -40,7 +44,7 @@ func (e *Engine) TmplString(str string, vars any) (string, error) {
return str, nil
}

tmpl, err := e.baseTemplate.Parse(str)
tmpl, err := e.parse(str)
if err != nil {
log.Err(err).Msg("failed to parse template")
return "", err
Expand Down Expand Up @@ -73,7 +77,7 @@ func (e *Engine) Factory(reader io.Reader) (*template.Template, error) {
return nil, ErrTemplateIsEmpty
}

return e.baseTemplate.Parse(string(out))
return e.parse(string(out))
}

func (e *Engine) Render(w io.Writer, tmpl *template.Template, vars any) error {
Expand Down
6 changes: 6 additions & 0 deletions app/scaffold/render_funcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,12 @@ func RenderRWFS(eng *engine.Engine, args *RWFSArgs, vars engine.Vars) error {
return nil
}

// Skip whitespace files
if len(strings.TrimSpace(buff.String())) == 0 {
_ = f.Close()
return nil
}

// Ensure the directory exists
err = args.WriteFS.MkdirAll(filepath.Dir(outpath), os.ModePerm)
if err != nil {
Expand Down

0 comments on commit cd5caae

Please sign in to comment.