-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloggit.go
More file actions
427 lines (361 loc) · 10.4 KB
/
loggit.go
File metadata and controls
427 lines (361 loc) · 10.4 KB
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
package main
import (
"bufio"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log"
"math/rand"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"time"
)
const (
defaultBumpVersionMsg = "Bump version"
defaultVersionRegexpStr = "\\d+\\.\\d+\\.\\d+"
defaultLogGitTrailer = "log:"
defaultUseCommitTitleMsg = "%s"
defaultChangelogRelativePath = "CHANGELOG.md"
defaultVersionHeader = "# Version "
defaultMasterBranchName = "master"
configFileName = "loggit.json"
)
var (
config Config
defaultAlsoTag = true
)
type Config struct {
BumpVersionMsg string
VersionRegexpStr string
LogGitTrailer string
UseCommitTitleMsg string
ChangelogRelativePath string
VersionHeader string
MasterBranchName string
AlsoTag *bool
}
func getConfigDir() string {
var homePath string
if runtime.GOOS == "windows" {
homePath = "HOMEPATH"
} else {
homePath = "HOME"
}
return filepath.Join(os.Getenv(homePath), ".config")
}
func setNilConfigFields(config *Config) {
if config.BumpVersionMsg == "" {
config.BumpVersionMsg = defaultBumpVersionMsg
}
if config.LogGitTrailer == "" {
config.LogGitTrailer = defaultLogGitTrailer
}
if config.UseCommitTitleMsg == "" {
config.UseCommitTitleMsg = defaultUseCommitTitleMsg
}
if config.VersionHeader == "" {
config.VersionHeader = defaultVersionHeader
}
if config.VersionRegexpStr == "" {
config.VersionRegexpStr = defaultVersionRegexpStr
}
if config.ChangelogRelativePath == "" {
config.ChangelogRelativePath = defaultChangelogRelativePath
}
if config.MasterBranchName == "" {
config.MasterBranchName = defaultMasterBranchName
}
if config.AlsoTag == nil {
config.AlsoTag = &defaultAlsoTag
}
}
func openDefaultConfigFile() (*os.File, error) {
var (
configPath string
configFile *os.File
out []byte
err error
)
cmd := exec.Command("git", "rev-parse", "--show-toplevel")
out, err = cmd.Output()
if err == nil {
repoRoot := strings.TrimSpace(string(out))
configPath = filepath.Join(repoRoot, configFileName)
configFile, err = os.Open(configPath)
}
if err != nil {
configDir := getConfigDir()
err = os.MkdirAll(configDir, os.ModePerm)
if err != nil {
log.Fatalf("Error mkdir'ing in readConfig: %s\n", err)
}
configPath = filepath.Join(configDir, configFileName)
configFile, err = os.Open(configPath)
}
return configFile, err
}
func readConfig(configPath string) {
var (
configFile *os.File
err error
)
if len(configPath) == 0 {
configFile, err = openDefaultConfigFile()
} else {
configFile, err = os.Open(configPath)
}
if err == nil {
defer configFile.Close()
configBytes, err := io.ReadAll(configFile)
if err != nil {
log.Fatalf("Error reading config file in readConfig: %s\n", err)
}
err = json.Unmarshal(configBytes, &config)
if err != nil {
log.Fatalf("Error unmarshalling in readConfig: %s\n", err)
}
}
setNilConfigFields(&config)
}
func getNewVersion(commitMsgPath string) (string, error) {
commitMsgFile, err := os.Open(commitMsgPath)
if err != nil {
log.Fatalln("Could not open the commit message file")
}
commitMsgBytes, err := io.ReadAll(commitMsgFile)
if err != nil {
log.Fatalln("Could not read the commit message")
}
commitMsg := string(commitMsgBytes)
if !strings.HasPrefix(commitMsg, config.BumpVersionMsg) {
return "", fmt.Errorf("No new version in this commit")
}
versionRegexp := regexp.MustCompile(config.VersionRegexpStr)
versionMatch := versionRegexp.Find(commitMsgBytes)
if len(versionMatch) == 0 {
log.Fatalln("Invalid format for new version in this commit")
}
return string(versionMatch), nil
}
func getPrevBumpCommitHash() string {
grepArg := "--grep=" + config.BumpVersionMsg
formatArg := "--pretty=format:%H"
cmd := exec.Command("git", "log", grepArg, "-n", "1", formatArg)
out, err := cmd.Output()
var exitError *exec.ExitError
if errors.As(err, &exitError) {
log.Fatalf("Could not read the previous bump-commit hash: %s\n", string(exitError.Stderr))
}
outStr := string(out)
outLines := strings.Split(outStr, "\n")
if len(outLines) == 1 && outLines[0] == "" {
return ""
}
return outLines[0]
}
func getCurrentGitBranch() string {
cmd := exec.Command("git", "branch", "--show-current")
output, err := cmd.Output()
var exitError *exec.ExitError
if errors.As(err, &exitError) {
log.Fatalf("Could not get the current Git branch: %s\n", string(exitError.Stderr))
}
return strings.TrimSpace(string(output))
}
func getFirstBranchCommitHash(branchName string) string {
interval := config.MasterBranchName + "~.." + branchName
formatArg := "--pretty=format:%H"
cmd := exec.Command("git", "log", interval, formatArg)
out, err := cmd.Output()
var exitError *exec.ExitError
if errors.As(err, &exitError) {
log.Fatalf("Could not read the previous bump-commit hash: %s\n", string(exitError.Stderr))
}
outStr := string(out)
outLines := strings.Split(outStr, "\n")
nLines := len(outLines)
if nLines == 0 || outLines[nLines-1] == "" {
log.Fatalln("Could not read the first commit hash of the current branch")
}
return outLines[nLines-1]
}
func getGitCommitSubjects(commitsInterval string, grepArg string) []string {
formatSubjectArg := "--pretty=format:%s"
cmd := exec.Command("git", "log", commitsInterval, grepArg, formatSubjectArg)
subjectOut, err := cmd.Output()
var exitError *exec.ExitError
if errors.As(err, &exitError) {
log.Fatalf("Failed to collect log messages (subjects): %s\n", string(exitError.Stderr))
}
outStr := strings.TrimSpace(string(subjectOut))
outLineSubjects := strings.Split(outStr, "\n")
return outLineSubjects
}
func getGitCommitBodies(commitsInterval string, grepArg string) []string {
formatBodyArg := "--pretty=format:%b"
cmd := exec.Command("git", "log", commitsInterval, grepArg, formatBodyArg)
bodyOut, err := cmd.Output()
var exitError *exec.ExitError
if errors.As(err, &exitError) {
log.Fatalf("Failed to collect log messages (bodies): %s\n", string(exitError.Stderr))
}
outStr := strings.TrimSpace(string(bodyOut))
outLineAllBodies := strings.Split(outStr, "\n")
var outLineBodies []string
for i := 0; i < len(outLineAllBodies); i++ {
body := outLineAllBodies[i]
if len(body) > 0 {
outLineBodies = append(outLineBodies, body)
}
}
return outLineBodies
}
func collectLogMsgs(prevCommitHash string) []string {
lowerLimit := ""
if len(prevCommitHash) > 0 {
lowerLimit = prevCommitHash + ".."
}
commitsInterval := lowerLimit + "HEAD"
grepArg := "--grep=" + config.LogGitTrailer
outLineSubjects := getGitCommitSubjects(commitsInterval, grepArg)
outLineBodies := getGitCommitBodies(commitsInterval, grepArg)
if len(outLineBodies) != len(outLineSubjects) {
log.Fatalln("Different number of commit bodies and subjects")
}
gitTrailerLen := len(config.LogGitTrailer)
var logMsgs []string
for i := 0; i < len(outLineBodies); i++ {
bodyMsg := outLineBodies[i]
subjectMsg := outLineSubjects[i]
if strings.HasPrefix(bodyMsg, config.LogGitTrailer) {
logMsg := strings.TrimSpace(bodyMsg[gitTrailerLen:])
if logMsg == config.UseCommitTitleMsg {
logMsgs = append(logMsgs, subjectMsg)
} else {
logMsgs = append(logMsgs, logMsg)
}
}
}
return logMsgs
}
func getVersionLogHeader(version string) string {
today := time.Now().Format("2006-01-02")
return config.VersionHeader + version + " - " + today
}
func writeTempLogFile(tempLogFile *os.File, newVersionHeader string,
newLogLines []string) {
logFile, err := os.Open(config.ChangelogRelativePath)
if err != nil {
logFile, err = os.Create(config.ChangelogRelativePath)
if err != nil {
log.Fatalln("Could not open nor create the changelog file")
}
}
defer logFile.Close()
_, err = tempLogFile.WriteString(newVersionHeader + "\n")
if err != nil {
log.Fatal(err)
}
for i := 0; i < len(newLogLines); i++ {
_, err = tempLogFile.WriteString("* " + newLogLines[i] + "\n")
if err != nil {
log.Fatal(err)
}
}
_, err = tempLogFile.WriteString("\n")
if err != nil {
log.Fatal(err)
}
scanner := bufio.NewScanner(logFile)
for scanner.Scan() {
_, err = tempLogFile.WriteString(scanner.Text() + "\n")
if err != nil {
log.Fatal(err)
}
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
tempLogFile.Sync()
}
func CreateNewVersionGitTag(newVersion string) {
cmd := exec.Command("git", "tag", newVersion)
out, err := cmd.Output()
var exitError *exec.ExitError
if errors.As(err, &exitError) {
log.Fatalf("Could not create a new tag: %s\n", string(exitError.Stderr))
}
if len(out) > 0 {
log.Fatal(string(out))
}
}
func AppendToChangelog(commitMsgPath string, alsoTag bool) {
newVersion, err := getNewVersion(commitMsgPath)
if err != nil {
fmt.Println(err)
os.Exit(0)
}
newVersionHeader := getVersionLogHeader(newVersion)
prevHash := getPrevBumpCommitHash()
logMsgs := collectLogMsgs(prevHash)
randNumber := strconv.Itoa(rand.Int())
tempFile, err := os.Create("loggit-" + randNumber)
if err != nil {
log.Fatalln("Could not create a temporary file")
}
defer tempFile.Close()
writeTempLogFile(tempFile, newVersionHeader, logMsgs)
err = os.Rename(tempFile.Name(), config.ChangelogRelativePath)
if err != nil {
log.Fatal(err)
}
if alsoTag {
CreateNewVersionGitTag(newVersion)
}
}
func WriteBranchChangelog() {
currentBranch := getCurrentGitBranch()
prevHash := getFirstBranchCommitHash(currentBranch)
logMsgs := collectLogMsgs(prevHash)
_, logFileName := filepath.Split(config.ChangelogRelativePath)
if len(logFileName) == 0 {
_, logFileName = filepath.Split(defaultChangelogRelativePath)
}
branchLogFile, err := os.Create(currentBranch + "-" + logFileName)
if err != nil {
log.Fatalln("Could not create branch changelog")
}
defer branchLogFile.Close()
for i := 0; i < len(logMsgs); i++ {
line := "* " + logMsgs[i] + "\n"
fmt.Print(line)
_, err = branchLogFile.WriteString(line)
if err != nil {
log.Fatal(err)
}
}
}
func parseCliArgsAndRun() {
branchModePtr := flag.Bool("branch", false, "Use all commits from the current branch")
configPathPtr := flag.String("config", "", "Path to the configuration file")
flag.Parse()
if len(os.Args) == 1 {
log.Fatal("Please provide the commit message file or specify branch mode with `-branch`")
}
readConfig(*configPathPtr)
if *branchModePtr {
WriteBranchChangelog()
return
}
AppendToChangelog(os.Args[1], *config.AlsoTag)
}
func main() {
parseCliArgsAndRun()
}