-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
477 lines (418 loc) · 11.9 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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"os"
"os/exec"
"strings"
"time"
)
const shellToUse = "bash"
const appVersion = "v1.2.3"
var (
gitBaseCommand = "git"
latestTag = ""
newTag = ""
tagMessage = ""
logFileFolder = "release-logs"
releaseFileName = "release-log.md"
isCommitLog = false
gitRemoteURL, gitRemoteName, projectPath, outputPath string
haveBreakChange = false
haveLog = false
writeNewFile = new(bool)
logFromBeginning = new(bool)
showVersionNumber = new(bool)
//conventional commit types
features []string
fixes []string
chores []string
)
func main() {
parseCliOptions()
if *showVersionNumber {
printVersionInfo()
}
findGitRemote()
findLatestTag()
collectGitLogs()
if haveLog {
//Get new tag from user
for {
// get tag form user
newTag, tagMessage = getTagFromUserInput()
if len(newTag) > 0 && len(tagMessage) > 0 {
break
}
}
writeReleaseLog()
commitLog()
makeNewTag()
pushHeadAndTagToRemote()
} else {
fmt.Println("There are no changes made between " + latestTag + " and HEAD")
}
}
func parseCliOptions() {
// get cli option
flag.StringVar(&projectPath, "d", ".", "project directory path")
flag.StringVar(&outputPath, "o", ".", "output file path")
writeNewFile = flag.Bool("n", false, "write new release log file")
logFromBeginning = flag.Bool("b", false, "get logs from the beginning")
showVersionNumber = flag.Bool("v", false, "show the version number")
flag.Parse()
// .git directory discovery
if projectPath != "." {
if !strings.HasSuffix(projectPath, "/") {
projectPath = fmt.Sprintf("%s%s", projectPath, "/")
}
if !directoryOrFileExists(projectPath) {
fmt.Println("Project path not exists!")
os.Exit(1)
}
gitBaseCommand = fmt.Sprintf("%s --git-dir=%s.git --work-tree=%s", gitBaseCommand, projectPath, projectPath)
}
// output file location
if outputPath != "." {
if !strings.HasSuffix(outputPath, "/") {
outputPath = fmt.Sprintf("%s/", outputPath)
}
if !directoryOrFileExists(outputPath) {
fmt.Println("Output path not exists!")
os.Exit(1)
}
}
}
func printVersionInfo() {
fmt.Println("-: Awesome Release Logger(ARL) :-")
fmt.Printf("Version: %s\n", appVersion)
fmt.Println("Copyright(c) 2020 TheDevsTech - GPL-3.0")
os.Exit(0)
}
func directoryOrFileExists(path string) bool {
if _, err := os.Stat(path); os.IsNotExist(err) {
return false
}
return true
}
func shellout(command string) (string, error, string) {
var stdout bytes.Buffer
var stderr bytes.Buffer
cmd := exec.Command(shellToUse, "-c", command)
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
return stdout.String(), err, stderr.String()
}
func findGitRemote() {
remoteCommand := gitBaseCommand + " remote -v"
remote, err, _ := shellout(remoteCommand)
if err == nil && len(remote) > 0 {
remoteArray := strings.Split(remote, "\n")
remoteList := make(map[string]string)
for _, line := range remoteArray {
if len(line) > 0 {
remotePart := strings.Fields(line)
remoteList[remotePart[0]] = replaceMessage(remotePart[1], ".git", "")
}
}
if len(remoteList) > 1 {
gitRemoteURL, gitRemoteName = getRemoteFromUserInput(remoteList)
} else {
for name, url := range remoteList {
gitRemoteURL = url
gitRemoteName = name
break
}
}
//replace ssh clone url to https
if len(gitRemoteURL) > 0 {
if strings.HasPrefix(gitRemoteURL, "git@") {
gitRemoteURL = replaceMessage(gitRemoteURL, ":", "/")
gitRemoteURL = replaceMessage(gitRemoteURL, "git@", "https://")
}
}
}
}
func getRemoteFromUserInput(remoteList map[string]string) (string, string) {
remoteURL := ""
remoteName := ""
for {
choosenName := getUserChoice(remoteList)
url, exists := remoteList[choosenName]
if exists {
remoteURL = url
remoteName = choosenName
break
}
}
return remoteURL, remoteName
}
func getUserChoice(remoteList map[string]string) string {
fmt.Println("Multiple git remote found. Please choose one and write it:")
for name, _ := range remoteList {
fmt.Println(name)
}
name := ""
readUserInput("-> ", &name)
return name
}
func findLatestTag() {
latestTagCommand := gitBaseCommand + " rev-list --tags --max-count=1"
tagHas, err, _ := shellout(latestTagCommand)
if err == nil && len(tagHas) > 0 {
latestTagCommand = fmt.Sprintf("%s describe --tags %s", gitBaseCommand, tagHas)
latestTagName, err, _ := shellout(latestTagCommand)
if err == nil && len(latestTagName) > 0 {
latestTag = strings.Replace(latestTagName, "\n", "", -1)
}
}
}
func collectGitLogs() {
fmt.Println("Collecting logs...")
logCommand := gitBaseCommand + " log --format=%B%H----DELIMITER----"
if len(latestTag) > 0 && *logFromBeginning == false {
cmdSlice := []string{
gitBaseCommand,
" log ",
latestTag,
"..",
"HEAD --format=%B%H----DELIMITER----",
}
logCommand = strings.Join(cmdSlice, "")
}
logs, err, errMsg := shellout(logCommand)
if err != nil {
fmt.Println(errMsg)
}
if len(logs) > 0 {
haveLog = true
parseCommits(logs)
}
}
func makeNewTag() {
// now make the tag
tagCommand := fmt.Sprintf("%s tag -a -m '%s' %s", gitBaseCommand, tagMessage, newTag)
_, err, errMsg := shellout(tagCommand)
if err != nil {
fmt.Print(errMsg)
os.Exit(1)
}
}
func getTagFromUserInput() (string, string) {
if len(latestTag) > 0 {
fmt.Printf("Previous tag is %s\n", latestTag)
if haveBreakChange {
fmt.Println("You have breaking changes! So its might be good to update your major version number.")
}
}
nTag := ""
readUserInput("Enter new tag name: ", &nTag)
message := ""
readUserInput("Enter tag message: ", &message)
return nTag, message
}
func replaceMessage(message string, search string, replace string) string {
return strings.Replace(message, search, replace, len(search))
}
func formatMessage(message string, sha string, shortSha string) string {
messageSlice := []string{}
if len(gitRemoteURL) > 0 {
messageSlice = []string{message,
" ",
"([",
shortSha,
"](",
gitRemoteURL,
"/commit/",
sha,
"))",
}
} else {
messageSlice = []string{message,
" ",
"(",
shortSha,
")",
}
}
return strings.Join(messageSlice, "")
}
func parseCommits(commits string) {
commitsArray := strings.Split(commits, "----DELIMITER----\n")
for _, commit := range commitsArray {
commitPart := strings.Split(commit, "\n")
if len(commitPart) == 2 {
message := commitPart[0]
sha := commitPart[1]
shortSha := sha[:7]
// remove ! first for below replacement work properly
if strings.Contains(message, "!:") {
message = replaceMessage(message, "!", "")
haveBreakChange = true
}
if strings.HasPrefix(message, "chore:") {
message = replaceMessage(message, "chore: ", "")
chores = append(chores, formatMessage(message, sha, shortSha))
} else if strings.HasPrefix(message, "fix:") {
message = replaceMessage(message, "fix: ", "")
fixes = append(fixes, formatMessage(message, sha, shortSha))
} else if strings.HasPrefix(message, "breaking change:") {
message = replaceMessage(message, "breaking change: ", "")
features = append(features, formatMessage(message, sha, shortSha))
haveBreakChange = true
} else {
if strings.HasPrefix(message, "feature:") {
message = replaceMessage(message, "feature: ", "")
}
if strings.HasPrefix(message, "feat:") {
message = replaceMessage(message, "feat: ", "")
}
features = append(features, formatMessage(message, sha, shortSha))
}
}
}
}
func writeLine(f *os.File, line string) {
l := fmt.Sprintf("%s%s", line, "\n")
if _, err := f.WriteString(l); err != nil {
fmt.Println(err)
}
}
func getReleaseFilePath() string {
//path that provided via -o args
filePath := fmt.Sprintf("%s%s", outputPath, releaseFileName)
//if current directory
if outputPath == "." {
outputPath = fmt.Sprintf("./%s", logFileFolder)
//if repo directory supplied then project path need to add
if projectPath != "." {
outputPath = fmt.Sprintf("%s%s", projectPath, logFileFolder)
}
if !directoryOrFileExists(outputPath) {
os.Mkdir(outputPath, os.ModePerm)
}
filePath = fmt.Sprintf("%s/%s", outputPath, releaseFileName)
//If writing log inside of the repo, then need to commit the log
isCommitLog = true
}
return filePath
}
func writeReleaseLog() {
today := time.Now()
todayFormated := today.Format("2006-01-02")
if *writeNewFile {
releaseFileName = fmt.Sprintf("release-log-%s.md", todayFormated)
}
releaseFilePath := getReleaseFilePath()
//get previous contents because we need to prepend the latest log
oldContents := []string{}
if directoryOrFileExists(releaseFilePath) && !*writeNewFile {
f, err := os.OpenFile(releaseFilePath, os.O_RDONLY, 0600)
if err != nil {
fmt.Println(err)
} else {
// read file and store content in memory
scanner := bufio.NewScanner(f)
for scanner.Scan() {
tmp := scanner.Text()
oldContents = append(oldContents, tmp)
}
}
defer f.Close()
}
// open release log file
nf, err := os.OpenFile(releaseFilePath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// close file on exit and check for its returned error
defer func() {
if err := nf.Close(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}()
writeLine(nf, fmt.Sprintf("# Version %s (%s)", newTag, todayFormated))
if len(features) > 0 {
writeLine(nf, "## Feature")
for _, message := range features {
writeLine(nf, "* "+message)
}
//write a empty line
writeLine(nf, "")
}
if len(fixes) > 0 {
writeLine(nf, "## Fix")
for _, message := range fixes {
writeLine(nf, "* "+message)
}
//write a empty line
writeLine(nf, "")
}
if len(chores) > 0 {
writeLine(nf, "## Chore")
for _, message := range chores {
writeLine(nf, "* "+message)
}
//write a empty line
writeLine(nf, "")
}
//now write diff between two tags
if len(latestTag) > 0 {
writeLine(nf, "## Diff")
diffText := fmt.Sprintf("* %s/compare/%s...%s", gitRemoteURL, latestTag, newTag)
writeLine(nf, diffText)
}
//now write old logs
if len(oldContents) > 0 {
//write empty lines
writeLine(nf, "")
writeLine(nf, "")
for _, line := range oldContents {
writeLine(nf, line)
}
}
endMessage := "Log File: " + releaseFilePath
messageLen := len(endMessage)
fmt.Println(strings.Repeat("-", messageLen))
fmt.Println(endMessage)
fmt.Println(strings.Repeat("-", messageLen))
}
func readUserInput(question string, inputStore *string) {
fmt.Printf(question)
reader := bufio.NewReader(os.Stdin)
inputText, _ := reader.ReadString('\n')
// convert CRLF to LF
inputText = strings.Replace(inputText, "\n", "", -1)
*inputStore = inputText
}
func commitLog() {
//If writing log inside of the repo, then need to commit the log
if isCommitLog {
fmt.Println("Committing new logs...")
addAndCommitCmd := fmt.Sprintf("%s add . && %s commit -m 'added release log for tag: %s'", gitBaseCommand, gitBaseCommand, newTag)
_, err, errMsg := shellout(addAndCommitCmd)
if err != nil {
fmt.Printf("Can't commit logs!\n error: %s", errMsg)
os.Exit(1)
}
}
}
func pushHeadAndTagToRemote() {
//if has remote then push it
if len(gitRemoteURL) > 0 {
fmt.Println("Pushing HEAD & tag to remote...")
pushBaseCmd := fmt.Sprintf("%s push %s", gitBaseCommand, gitRemoteName)
pushCommitTagCmd := fmt.Sprintf("%s HEAD && %s %s", pushBaseCmd, pushBaseCmd, newTag)
_, err, errMsg := shellout(pushCommitTagCmd)
if err != nil {
fmt.Printf("Push to remote failed!\n error: %s", errMsg)
os.Exit(1)
}
fmt.Printf("HEAD & tag: %s has been pushed to remote\n", newTag)
}
}