0
0
mirror of https://github.com/thegeeklab/git-sv.git synced 2024-11-22 08:20:39 +00:00
git-sv/sv/formatter.go

91 lines
2.4 KiB
Go
Raw Normal View History

package sv
import (
"bytes"
"io/fs"
"sort"
"text/template"
"time"
"github.com/Masterminds/semver/v3"
)
type releaseNoteTemplateVariables struct {
Release string
Tag string
Version *semver.Version
Date time.Time
Sections []ReleaseNoteSection
AuthorNames []string
}
// OutputFormatter output formatter interface.
type OutputFormatter interface {
2021-07-31 20:34:40 +00:00
FormatReleaseNote(releasenote ReleaseNote) (string, error)
FormatChangelog(releasenotes []ReleaseNote) (string, error)
}
// OutputFormatterImpl formater for release note and changelog.
type OutputFormatterImpl struct {
templates *template.Template
}
// NewOutputFormatter TemplateProcessor constructor.
func NewOutputFormatter(templatesFS fs.FS) *OutputFormatterImpl {
templateFNs := map[string]interface{}{
"timefmt": timeFormat,
"getsection": getSection,
}
tpls := template.Must(template.New("templates").Funcs(templateFNs).ParseFS(templatesFS, "*"))
return &OutputFormatterImpl{templates: tpls}
}
// FormatReleaseNote format a release note.
2021-07-31 20:34:40 +00:00
func (p OutputFormatterImpl) FormatReleaseNote(releasenote ReleaseNote) (string, error) {
2020-02-02 03:49:54 +00:00
var b bytes.Buffer
if err := p.templates.ExecuteTemplate(&b, "releasenotes-md.tpl", releaseNoteVariables(releasenote)); err != nil {
2021-07-31 20:34:40 +00:00
return "", err
}
return b.String(), nil
2020-02-02 03:49:54 +00:00
}
2021-07-31 19:03:58 +00:00
// FormatChangelog format a changelog.
2021-07-31 20:34:40 +00:00
func (p OutputFormatterImpl) FormatChangelog(releasenotes []ReleaseNote) (string, error) {
2021-07-31 19:35:28 +00:00
templateVars := make([]releaseNoteTemplateVariables, len(releasenotes))
for i, v := range releasenotes {
templateVars[i] = releaseNoteVariables(v)
2020-02-02 03:49:54 +00:00
}
var b bytes.Buffer
if err := p.templates.ExecuteTemplate(&b, "changelog-md.tpl", templateVars); err != nil {
2021-07-31 20:34:40 +00:00
return "", err
}
return b.String(), nil
2020-02-02 03:49:54 +00:00
}
func releaseNoteVariables(releasenote ReleaseNote) releaseNoteTemplateVariables {
release := releasenote.Tag
if releasenote.Version != nil {
release = "v" + releasenote.Version.String()
}
2020-02-02 03:49:54 +00:00
return releaseNoteTemplateVariables{
Release: release,
Tag: releasenote.Tag,
Version: releasenote.Version,
Date: releasenote.Date,
Sections: releasenote.Sections,
AuthorNames: toSortedArray(releasenote.AuthorsNames),
}
}
func toSortedArray(input map[string]struct{}) []string {
result := make([]string, len(input))
i := 0
for k := range input {
result[i] = k
i++
}
sort.Strings(result)
return result
}