github.com/pojntfx/hydrapp/hydrapp@v0.0.0-20240516002902-d08759d6ca9f/pkg/renderers/renderer.go (about)

     1  package renderers
     2  
     3  import (
     4  	"bytes"
     5  	"strings"
     6  	"text/template"
     7  	"time"
     8  
     9  	"golang.org/x/text/cases"
    10  	"golang.org/x/text/language"
    11  )
    12  
    13  type Release struct {
    14  	Version     string    `json:"version" yaml:"version"`
    15  	Date        time.Time `json:"date" yaml:"date"`
    16  	Description string    `json:"description" yaml:"description"`
    17  	Author      string    `json:"author" yaml:"author"`
    18  	Email       string    `json:"email" yaml:"email"`
    19  }
    20  
    21  type Renderer interface {
    22  	Render(templateOverride string) (filePath string, fileContent []byte, err error)
    23  }
    24  
    25  type renderer struct {
    26  	filePath string
    27  	template string
    28  	data     interface{}
    29  }
    30  
    31  func NewRenderer(
    32  	filePath string,
    33  	template string,
    34  	data interface{},
    35  ) Renderer {
    36  	return &renderer{
    37  		filePath,
    38  		template,
    39  		data,
    40  	}
    41  }
    42  
    43  func (r *renderer) Render(templateOverride string) (filePath string, fileContent []byte, err error) {
    44  	titler := cases.Title(language.English)
    45  
    46  	t, err := template.
    47  		New(r.filePath).
    48  		Funcs(template.FuncMap{
    49  			"LastRelease": func(releases []Release) Release {
    50  				return releases[0]
    51  			},
    52  			"Titlecase": func(title string) string {
    53  				return titler.String(title)
    54  			},
    55  		}).
    56  		Parse(func() string {
    57  			if strings.TrimSpace(templateOverride) != "" {
    58  				return templateOverride
    59  			}
    60  
    61  			return r.template
    62  		}())
    63  	if err != nil {
    64  		return "", []byte{}, err
    65  	}
    66  
    67  	buf := bytes.NewBuffer([]byte{})
    68  	if err := t.Execute(buf, r.data); err != nil {
    69  		return "", []byte{}, err
    70  	}
    71  
    72  	return r.filePath, buf.Bytes(), err
    73  }