feat: write changelog to path

main
hau 2020-11-10 17:36:50 +07:00
parent 6a5d3fe235
commit dc386b27f4
1 changed files with 43 additions and 0 deletions

View File

@ -2,6 +2,8 @@ package changelog
import ( import (
"fmt" "fmt"
"io/ioutil"
"strings"
"time" "time"
"github.com/haunt98/changeloguru/pkg/convention" "github.com/haunt98/changeloguru/pkg/convention"
@ -28,6 +30,18 @@ func NewMarkdownGenerator(path string, version string, t time.Time) *MarkdownGen
} }
func (g *MarkdownGenerator) Generate(commits []convention.Commit) error { func (g *MarkdownGenerator) Generate(commits []convention.Commit) error {
lines := g.getLines(commits)
previousLines, err := g.getPreviousLines()
if err != nil {
return err
}
lines = append(lines, previousLines...)
if err := g.writeLines(lines); err != nil {
return err
}
return nil return nil
} }
@ -71,6 +85,35 @@ func (g *MarkdownGenerator) getLines(commits []convention.Commit) []string {
return lines return lines
} }
func (g *MarkdownGenerator) getPreviousLines() ([]string, error) {
prevData, err := ioutil.ReadFile(g.path)
if err != nil {
return nil, err
}
prevLines := strings.Split(string(prevData), "\n")
finalPrevLines := make([]string, 0, len(prevLines))
for _, prevLine := range prevLines {
prevLine = strings.TrimSpace(prevLine)
if prevLine == "" || prevLine == markdownTitle {
continue
}
finalPrevLines = append(finalPrevLines, prevLine)
}
return finalPrevLines, nil
}
func (g *MarkdownGenerator) writeLines(lines []string) error {
data := strings.Join(lines, "\n")
if err := ioutil.WriteFile(g.path, []byte(data), 0644); err != nil {
return err
}
return nil
}
func (g *MarkdownGenerator) composeVersionHeader() string { func (g *MarkdownGenerator) composeVersionHeader() string {
year, month, day := g.t.Date() year, month, day := g.t.Date()
return fmt.Sprintf("## %s (%d-%d-%d)", g.version, year, month, day) return fmt.Sprintf("## %s (%d-%d-%d)", g.version, year, month, day)