Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(#3) adds RenderString helper to render help consistently #4

Merged
merged 1 commit into from
May 16, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 23 additions & 9 deletions scaffold.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"bytes"
"errors"
"fmt"
"github.com/choria-io/scaffold/internal/sprig"
"github.com/kballard/go-shellquote"
"io/fs"
"os"
Expand Down Expand Up @@ -80,6 +81,16 @@ func New(cfg Config, funcs template.FuncMap) (*Scaffold, error) {
return &Scaffold{cfg: &cfg, funcs: funcs}, nil
}

// RenderString renders a string using the same functions and behavior as the scaffold, including custom delimiters
func (s *Scaffold) RenderString(str string, data any) (string, error) {
res, err := s.renderTemplateBytes("string", []byte(str), data)
if err != nil {
return "", err
}

return string(res), nil
}

// Logger configures a logger to use, no logging is done without this
func (s *Scaffold) Logger(log Logger) {
s.log = log
Expand Down Expand Up @@ -185,7 +196,7 @@ func (s *Scaffold) templateFuncs() template.FuncMap {
return nil
}

funcs := template.FuncMap{}
funcs := sprig.FuncMap()
for k, v := range s.funcs {
funcs[k] = v
}
Expand All @@ -204,8 +215,17 @@ func (s *Scaffold) templateFuncs() template.FuncMap {
}

func (s *Scaffold) renderTemplateFile(tmpl string, data any) ([]byte, error) {
td, err := os.ReadFile(tmpl)
if err != nil {
return nil, err
}

return s.renderTemplateBytes(filepath.Base(tmpl), td, data)
}

func (s *Scaffold) renderTemplateBytes(name string, tmpl []byte, data any) ([]byte, error) {
buf := bytes.NewBuffer([]byte{})
templ := template.New(filepath.Base(tmpl))
templ := template.New(name)
funcs := s.templateFuncs()
if funcs != nil {
templ.Funcs(funcs)
Expand All @@ -215,12 +235,7 @@ func (s *Scaffold) renderTemplateFile(tmpl string, data any) ([]byte, error) {
templ.Delims(s.cfg.CustomLeftDelimiter, s.cfg.CustomRightDelimiter)
}

td, err := os.ReadFile(tmpl)
if err != nil {
return nil, err
}

templ, err = templ.Parse(string(td))
templ, err := templ.Parse(string(tmpl))
if err != nil {
return nil, fmt.Errorf("parsing template %v failed: %w", tmpl, err)
}
Expand Down Expand Up @@ -351,7 +366,6 @@ func (s *Scaffold) Render(data any) error {
}

out := filepath.Join(s.cfg.TargetDirectory, strings.TrimPrefix(path, s.workingSource))

switch {
case d.IsDir():
err := os.Mkdir(out, 0775)
Expand Down
Loading