This repository has been archived by the owner on Aug 26, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
236 lines (195 loc) · 5.83 KB
/
main.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package main
import (
"context"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"github.com/google/go-github/github"
ga "github.com/sethvargo/go-githubactions"
"github.com/spf13/viper"
"golang.org/x/oauth2"
)
type tagData struct {
tagName string
link string
publishedAt *github.Timestamp
}
type issuesData struct {
title string
issueNumber int
link string
}
type pullsData struct {
title string
prNumber int
link string
assigneeUser string
assigneeLink string
}
const (
closedIssues = "\n\n**Closed issues:**\n"
mergedPR = "\n\n**Merged pull requests:**\n"
)
var (
title = "\n## [%s](%s) (%s)"
fullChangelog = "\n\n[Full Changelog](https://github.com/%v/%v/compare/%v...%v)"
issueTemplate = "\n- %s [#%v](%s)"
prTemplate = "\n- %s [#%v](%s) ([%s](%s))"
token = ga.GetInput("token")
owner = ga.GetInput("owner")
repo = ga.GetInput("repo")
ctx = context.Background()
)
func main() {
client := setupClient()
if token == "" || repo == "" {
ga.Fatalf("missing required inputs")
}
ga.AddMask(token)
previousRelease := getPreviousRelease(client)
nextRelease := getNextRelease(client)
closedIssues := filterIssues(client, previousRelease, nextRelease)
mergedPulls := filterPulls(client, previousRelease, nextRelease)
generateChangelog(previousRelease, nextRelease, closedIssues, mergedPulls)
fmt.Println("Finish!")
}
func generateChangelog(previousRelease, nextRelease tagData, issues []issuesData, prs []pullsData) {
// Leitura do arquivo
file := filepath.Join("CHANGELOG.md")
fileRead, _ := ioutil.ReadFile(file)
lines := strings.Split(string(fileRead), "\n")
// Lógica: https: //stackoverflow.com/questions/46128016/insert-a-value-in-a-slice-at-a-given-index
lines = append(lines[:1+1], lines[1:]...)
formatTitle := fmt.Sprintf(title, nextRelease.tagName, nextRelease.link, nextRelease.publishedAt.Format("2006-01-04"))
formatFullChangelog := fmt.Sprintf(fullChangelog, owner, repo, previousRelease.tagName, nextRelease.tagName) // TODO: Ajustar para o caso da zup (ou quando o owner ou organização for diferente...)
lines[1] = formatTitle + formatFullChangelog
// Valida e formata a parte das issues
if len(issues) > 0 {
lines[1] = lines[1] + closedIssues
for _, issue := range issues {
lines[1] = lines[1] + fmt.Sprintf(issueTemplate, issue.title, issue.issueNumber, issue.link)
}
}
// Valida e formata a parte das prs
if len(prs) > 0 {
lines[1] = lines[1] + mergedPR
for _, pr := range prs {
lines[1] = lines[1] + fmt.Sprintf(prTemplate, pr.title, pr.prNumber, pr.link, pr.assigneeUser, pr.assigneeLink)
}
}
// Escreve no arquivo o changelog gerado
newFile := strings.Join(lines, "\n")
ioutil.WriteFile(file, []byte(newFile), os.ModePerm)
}
func filterIssues(client *github.Client, pr, nr tagData) []issuesData {
// Seleciona todas as issues fechadas depois da data de criação da tag
issues, _, err := client.Issues.ListByRepo(
context.Background(),
owner,
repo,
&github.IssueListByRepoOptions{State: "closed", Since: pr.publishedAt.Time},
)
if err != nil {
log.Fatalf("error listing issues: %v", err)
}
// Coloca todos os títulos das issues elegíveis dentro do slice para uso posterior
var filteredIssues []issuesData
for _, issue := range issues {
if issue.ClosedAt.After(pr.publishedAt.Time) && issue.PullRequestLinks == nil && issue.ClosedAt.Before(nr.publishedAt.Time) {
filterIssue := issuesData{
title: *issue.Title,
issueNumber: *issue.Number,
link: *issue.HTMLURL,
}
filteredIssues = append(filteredIssues, filterIssue)
}
}
return filteredIssues
}
func filterPulls(client *github.Client, psr, nr tagData) []pullsData {
// Seleciona todas as pr fechadas
prs, _, err := client.PullRequests.List(
ctx,
owner,
repo,
&github.PullRequestListOptions{State: "closed"},
)
if err != nil {
log.Fatalf("error listing prs: %v", err)
}
// Filtra as prs mergeadas após a data de criação da tag
// TODO: abrir issue no repo go-github, pois retorna erro ao usar o campo name da struct de user
var mergedPulls []pullsData
for _, pr := range prs {
if pr.MergedAt.After(psr.publishedAt.Time) && pr.MergedAt.Before(nr.publishedAt.Time) {
filterPull := pullsData{
title: *pr.Title,
prNumber: *pr.Number,
link: *pr.HTMLURL,
assigneeUser: *pr.User.Login,
assigneeLink: *pr.User.HTMLURL,
}
mergedPulls = append(mergedPulls, filterPull)
}
}
return mergedPulls
}
func getNextRelease(client *github.Client) tagData {
// Pega a última tag do repositório
lastTag, _, err := client.Repositories.GetLatestRelease(
context.Background(),
owner,
repo,
)
if err != nil {
log.Fatalf("error getting the last tag: %v", err)
}
nrData := tagData{
tagName: *lastTag.TagName,
link: *lastTag.HTMLURL,
publishedAt: lastTag.PublishedAt,
}
return nrData
}
func getPreviousRelease(client *github.Client) tagData {
// Pega a última tag do repositório
tags, _, err := client.Repositories.ListReleases(
context.Background(),
owner,
repo,
&github.ListOptions{},
)
if err != nil {
log.Fatalf("error getting the previous tag: %v", err)
}
previousRelease := tags[1]
prData := tagData{
tagName: *previousRelease.TagName,
link: *previousRelease.HTMLURL,
publishedAt: previousRelease.PublishedAt,
}
return prData
}
func getConfig(key string) string {
viper.SetConfigFile(".env")
err := viper.ReadInConfig()
if err != nil {
log.Fatalf("error while reading config file: %v", err)
}
value, ok := viper.Get(key).(string)
if !ok {
log.Fatalf("invalid type assertion")
}
return value
}
func setupClient() *github.Client {
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
return client
}