-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
387 lines (363 loc) · 12.6 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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
// Copyright (C) 2023 Lee Wannacott
package main
import (
"bufio"
"bytes"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
"sync"
"time"
)
type tag struct {
Name string `json:"name"`
}
type gitHubReleases struct {
ID int `json:"id"`
Name string `json:"name"`
Body string `json:"body"`
URL string `json:"url"`
TagName string `json:"tag_name"`
}
type changeLogVersion struct {
lineNumber int
title string
number string
}
type releaseMetaData struct {
TagVersionReleaseBodyMap map[string]string
ReleaseVersionTagMap map[string]string
ReleaseVersionTitleMap map[string]string
LatestReleaseVersion string
}
type changeLog struct {
changeLogText []string
versions []changeLogVersion
}
type releaseTagValidationInput struct {
authToken string
tags []tag
changeLog changeLog
releaseNotes []string
repoPath string
}
type releaseRequest struct {
authToken string
repoPath string
requestType string
urlWithID string
tagForRelease string
versionTitle string
releaseNote string
makeLatestRelease string
}
// Syntax highlighting for CLI warning messages.
const orangeColor = "\033[33m"
const redColor = "\033[31m"
const resetColor = "\033[0m"
func main() {
start := time.Now()
help, authTokenPtr, repoPtr, tagsRepoPtr, changeLogPtr := parseFlags()
displayHelp(help)
pathToChangeLog := getChangeLogPath(*changeLogPtr)
file, err := os.Open(pathToChangeLog)
if err != nil {
log.Fatal(err)
}
defer file.Close()
changeLog := getChangeLogInfo(bufio.NewScanner(file))
releaseNotes := createReleaseNotes(changeLog)
tags := getTagsFromGitHub(*tagsRepoPtr)
repoPath := *repoPtr
releaseTagValidationInput := releaseTagValidationInput{
authToken: *authTokenPtr,
tags: tags,
changeLog: changeLog,
releaseNotes: releaseNotes,
repoPath: repoPath,
}
releases := getReleases(*authTokenPtr, repoPath)
releaseMetaData := validateTagsHaveReleases(releaseTagValidationInput)
updateReleasesIfChanged(releaseMetaData, *authTokenPtr, repoPath, releases)
fmt.Println("Updated releases.")
createMissingReleases(releaseMetaData, *authTokenPtr, repoPath, releases)
fmt.Println("Created missing releases.")
elapsed := time.Since(start)
fmt.Println("Time taken:", elapsed)
}
func parseFlags() (*bool, *string, *string, *string, *string) {
authTokenPtr := flag.String("token", "", "(https://github.com/settings/tokens) generate token with 'public_repo' or 'repo' (private repos) permission.")
tagsRepoPtr := flag.String("tags", "owner/repo", "Repo where you want tags from.")
repoPtr := flag.String("target", "owner/repo", "Repo where you want to update the releases.")
changeLogPtr := flag.String("changelog", "docs/CHANGELOG.md", "Relative path to CHANGELOG.md.")
help := flag.Bool("help", false, "Display help")
flag.Parse()
if *authTokenPtr == "" {
fmt.Println(redColor + "Error: No GitHub access token given for flag -token. Refer to --help" + resetColor)
}
return help, authTokenPtr, repoPtr, tagsRepoPtr, changeLogPtr
}
func displayHelp(help *bool) {
if *help {
fmt.Fprintf(os.Stderr, "Usage: %s [OPTIONS]\n", os.Args[0])
flag.PrintDefaults()
os.Exit(0)
}
}
func getChangeLogPath(changeLogPath string) string {
_, filename, _, _ := runtime.Caller(0)
pathToChangeLog := filepath.Join(filepath.Dir(filename), changeLogPath)
return pathToChangeLog
}
func createMissingReleases(releaseMetaData releaseMetaData, authToken string, repoPath string, releases []gitHubReleases) {
releaseTagVersionMap := make(map[string]string)
for i := range releases {
releaseTagVersionMap[releases[i].TagName] = releases[i].TagName
}
createReleaseWaitGroup := &sync.WaitGroup{}
for releaseVersion, tagVersion := range releaseMetaData.ReleaseVersionTagMap {
// only send POST request if the tagVersion does not exist in the releases from the API.
if tagVersion != releaseTagVersionMap[tagVersion] {
makeLatestRelease := "false"
if releaseVersion == releaseMetaData.LatestReleaseVersion {
makeLatestRelease = "true"
}
repoOwner, repoName := splitAndEncodeURLPath(repoPath)
requestURL := fmt.Sprintf("https://api.github.com/repos/%v/%v/releases", repoOwner, repoName)
postRequest := releaseRequest{
authToken: authToken,
repoPath: repoPath,
requestType: "POST",
tagForRelease: tagVersion,
versionTitle: releaseMetaData.ReleaseVersionTitleMap[releaseVersion],
releaseNote: releaseMetaData.TagVersionReleaseBodyMap[tagVersion],
makeLatestRelease: makeLatestRelease,
}
createReleaseWaitGroup.Add(1)
go updateOrCreateGitHubRelease(postRequest, requestURL, createReleaseWaitGroup)
}
}
createReleaseWaitGroup.Wait()
}
func updateReleasesIfChanged(releaseMetaData releaseMetaData, authToken string, repoPath string, releases []gitHubReleases) {
updateReleaseWaitGroup := &sync.WaitGroup{}
repoOwner, repoName := splitAndEncodeURLPath(repoPath)
for _, release := range releases {
if release.Body != releaseMetaData.TagVersionReleaseBodyMap[release.TagName] {
requestURL := fmt.Sprintf("https://api.github.com/repos/%v/%v/releases/%v", repoOwner, repoName, release.ID)
patchRequest := releaseRequest{
authToken: authToken,
repoPath: repoPath,
requestType: "PATCH",
tagForRelease: release.TagName,
versionTitle: release.Name,
releaseNote: releaseMetaData.TagVersionReleaseBodyMap[release.TagName],
makeLatestRelease: "false",
}
updateReleaseWaitGroup.Add(1)
go updateOrCreateGitHubRelease(patchRequest, requestURL, updateReleaseWaitGroup)
}
}
updateReleaseWaitGroup.Wait()
}
func validateTagsHaveReleases(releaseTagValidationInput releaseTagValidationInput) releaseMetaData {
releaseMetaData := releaseMetaData{
TagVersionReleaseBodyMap: make(map[string]string),
ReleaseVersionTagMap: make(map[string]string),
ReleaseVersionTitleMap: make(map[string]string),
LatestReleaseVersion: "",
}
for i, release := range releaseTagValidationInput.changeLog.versions {
releaseVersionHasTag := false
for _, tagVersion := range releaseTagValidationInput.tags {
if release.number == tagVersion.Name {
releaseVersionHasTag = true
}
}
if releaseVersionHasTag {
if i == 0 {
releaseMetaData.LatestReleaseVersion = release.number
}
releaseMetaData.ReleaseVersionTitleMap[release.number] = release.title
releaseMetaData.ReleaseVersionTagMap[release.number] = release.number
releaseMetaData.TagVersionReleaseBodyMap[release.number] = releaseTagValidationInput.releaseNotes[i]
} else {
fmt.Println(orangeColor+"WARNING: release", release, "missing tag"+resetColor)
}
}
for _, tag := range releaseTagValidationInput.tags {
tagHasVersionNumber := false
for _, release := range releaseTagValidationInput.changeLog.versions {
if tag.Name == release.number {
tagHasVersionNumber = true
}
}
if !tagHasVersionNumber {
fmt.Println(orangeColor+"WARNING: tag", tag.Name, "missing changelog version"+resetColor)
}
}
return releaseMetaData
}
func splitAndEncodeURLPath(urlPath string) (string, string) {
urlPathSplit := strings.Split(urlPath, "/")
owner, name := url.QueryEscape(urlPathSplit[0]), url.QueryEscape(urlPathSplit[1])
return owner, name
}
func getReleases(authToken string, repoPath string) []gitHubReleases {
repoOwner, repoName := splitAndEncodeURLPath(repoPath)
releasePath := fmt.Sprintf("https://api.github.com/repos/%v/%v/releases", repoOwner, repoName)
req, err := http.NewRequest("GET", releasePath, nil)
req.Header.Set("Accept", "application/vnd.github.v3+json")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "token "+authToken)
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
var releases []gitHubReleases
err = json.Unmarshal(body, &releases)
if err != nil {
fmt.Println(redColor + string(body) + resetColor)
log.Fatal(err)
}
return releases
}
func getTagsFromGitHub(tagsRepoPath string) []tag {
// https://docs.github.com/en/rest/reference/repos#list-repository-tags
tagsRepoOwner, tagsRepoName := splitAndEncodeURLPath(tagsRepoPath)
pathToTags := fmt.Sprintf("https://api.github.com/repos/%v/%v/tags", tagsRepoOwner, tagsRepoName)
resp, err := http.Get(pathToTags)
if err != nil {
log.Fatal(err)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
var tags []tag
err = json.Unmarshal(body, &tags)
if err != nil {
log.Fatal(err)
}
return tags
}
func getChangeLogInfo(scanner *bufio.Scanner) changeLog {
titleAndVersionRE := regexp.MustCompile(`##\s*(?P<title>\[?(?P<version>\d+(\.\d+)*)\]?.*)`)
unreleasedRE := regexp.MustCompile(`## \[?Unreleased\]?`)
var changeLogText []string
var versions []changeLogVersion
for scanner.Scan() {
changeLogText = append(changeLogText, scanner.Text())
unreleased := unreleasedRE.FindStringSubmatch(scanner.Text())
titleAndVersionNumber := titleAndVersionRE.FindStringSubmatch(scanner.Text())
if unreleased != nil {
fmt.Println(orangeColor+"WARNING: Line:", len(changeLogText)-1, "## Unreleased section won't be synced to GitHub"+resetColor)
}
if titleAndVersionNumber != nil {
versionIndex := titleAndVersionRE.SubexpIndex("version")
titleIndex := titleAndVersionRE.SubexpIndex("title")
title := titleAndVersionNumber[titleIndex]
versionNumber := titleAndVersionNumber[versionIndex]
changeLogVersion := changeLogVersion{title: title, number: versionNumber, lineNumber: len(changeLogText) - 1}
versions = append(versions, changeLogVersion)
}
}
if scanner.Err() != nil {
fmt.Println(scanner.Err())
}
changeLog := changeLog{
changeLogText: changeLogText,
versions: versions,
}
return changeLog
}
func createReleaseNotes(changeLog changeLog) []string {
linkReferenceDefinitionRE, err := regexp.Compile(`^\[.+\]: .+`)
if err != nil {
log.Fatal(err)
}
contributorsAndErrors := bytes.Buffer{}
for _, line := range changeLog.changeLogText {
if linkReferenceDefinitionRE.MatchString(line) {
contributorsAndErrors.WriteString(line + "\n")
}
}
lastVersionIdx := len(changeLog.versions) - 1
var releaseNotes []string
for i, version := range changeLog.versions {
releaseBody := bytes.Buffer{}
var versionEndLine int
if i < lastVersionIdx {
versionEndLine = changeLog.versions[i+1].lineNumber
} else {
versionEndLine = len(changeLog.changeLogText)
}
for j := version.lineNumber + 1; j < versionEndLine; j++ {
if linkReferenceDefinitionRE.MatchString(changeLog.changeLogText[j]) {
continue
}
releaseBody.WriteString(changeLog.changeLogText[j] + "\n")
}
releaseNotes = append(releaseNotes, releaseBody.String()+contributorsAndErrors.String())
}
return releaseNotes
}
func updateOrCreateGitHubRelease(releaseRequest releaseRequest, requestURL string, waitGroup *sync.WaitGroup) {
defer waitGroup.Done()
postBody, err := json.Marshal(map[string]interface{}{
"name": releaseRequest.versionTitle,
"tag_name": releaseRequest.tagForRelease,
"body": releaseRequest.releaseNote,
"make_latest": releaseRequest.makeLatestRelease,
})
if err != nil {
log.Fatal(err)
}
requestBody := bytes.NewBuffer(postBody)
req, err := http.NewRequest(releaseRequest.requestType, requestURL, requestBody)
req.Header.Set("Accept", "application/vnd.github.v3+json")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "token "+releaseRequest.authToken)
resp, err := http.DefaultClient.Do(req)
if err != nil {
if resp.StatusCode == http.StatusNotFound {
fmt.Printf("Error: Status code: %d - GitHub release not found.\n", http.StatusNotFound)
return
} else if resp.StatusCode == http.StatusInternalServerError {
fmt.Printf("Error: Status code: %d - Internal server error.\n", http.StatusInternalServerError)
return
} else {
log.Fatal(err)
}
}
defer resp.Body.Close()
// https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps
repoPermission := false
if len(resp.Header["X-Oauth-Scopes"]) > 0 {
scopes := strings.Split(resp.Header.Get("X-Oauth-Scopes"), ", ")
for _, permission := range scopes {
// public_repo is the least permission; use repo for a private repo.
if permission == "public_repo" || permission == "repo" {
repoPermission = true
}
}
} else {
log.Fatalln(redColor + "Error: GitHub access Token has no permissions at all for X-Oauth-Scopes (select `public_repo` or `repo` scopes)" + resetColor)
}
if !repoPermission {
log.Fatalln(redColor + "Error: GitHub access Token doesn't include X-Oauth-Scope: `public_repo` or `repo`." + resetColor)
}
}