-
Notifications
You must be signed in to change notification settings - Fork 25
/
changelog.go
106 lines (96 loc) · 2.37 KB
/
changelog.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package ghch
import (
"bufio"
"bytes"
"context"
"log"
"strings"
"text/template"
"time"
"github.com/google/go-github/v41/github"
)
// Changelog contains Sectionst
type Changelog struct {
Sections []Section `json:"Sections"`
}
func insertNewChangelog(orig []byte, section string) string {
var bf bytes.Buffer
lineSnr := bufio.NewScanner(bytes.NewReader(orig))
inserted := false
for lineSnr.Scan() {
line := lineSnr.Text()
if !inserted && strings.HasPrefix(line, "## ") {
bf.WriteString(section)
bf.WriteString("\n\n")
inserted = true
}
bf.WriteString(line)
bf.WriteString("\n")
}
if !inserted {
bf.WriteString(section)
}
return bf.String()
}
// Section contains changes between two revisions
type Section struct {
PullRequests []*github.PullRequest `json:"pull_requests"`
FromRevision string `json:"from_revision"`
ToRevision string `json:"to_revision"`
ChangedAt time.Time `json:"changed_at"`
Owner string `json:"owner"`
Repo string `json:"repo"`
HTMLURL string `json:"html_url"`
}
var tmplStr = `{{$ret := . -}}
## [{{.ToRevision}}]({{.HTMLURL}}/compare/{{.FromRevision}}...{{.ToRevision}}) ({{.ChangedAt.Format "2006-01-02"}})
{{range .PullRequests}}
* {{.Title}} [#{{.Number}}]({{.HTMLURL}}) ([{{.User.Login}}]({{.User.HTMLURL}}))
{{- end}}`
var mdTmpl *template.Template
func init() {
var err error
mdTmpl, err = template.New("md-changelog").Parse(tmplStr)
if err != nil {
log.Fatal(err)
}
}
func (rs Section) toMkdn() (string, error) {
var b bytes.Buffer
err := mdTmpl.Execute(&b, rs)
if err != nil {
return "", err
}
return b.String(), nil
}
func (gh *Ghch) getSection(ctx context.Context, from, to string) (Section, error) {
if from == "" {
from, _ = gh.cmd("rev-list", "--max-parents=0", "HEAD")
from = strings.TrimSpace(from)
if len(from) > 12 {
from = from[:12]
}
}
r, err := gh.mergedPRs(ctx, from, to)
if err != nil {
return Section{}, err
}
t, err := gh.getChangedAt(to)
if err != nil {
return Section{}, err
}
owner, repo := gh.ownerAndRepo()
htmlURL, err := gh.htmlURL(ctx, owner, repo)
if err != nil {
return Section{}, err
}
return Section{
PullRequests: r,
FromRevision: from,
ToRevision: to,
ChangedAt: t,
Owner: owner,
Repo: repo,
HTMLURL: htmlURL,
}, nil
}