diff options
| author | Andrew Gerrand <adg@golang.org> | 2019-03-25 11:35:57 +1100 |
|---|---|---|
| committer | Andrew Gerrand <adg@golang.org> | 2019-03-25 02:02:52 +0000 |
| commit | 7744f6d7ac193720bb483dc2a2c266504b33d1a9 (patch) | |
| tree | ee8009a5598eaa5798124ef09af58f12fad81ab4 /git-codereview/hook.go | |
| parent | 05c26900aa9101b5ab40490ad329fab7dfa56cb6 (diff) | |
| download | go-x-review-7744f6d7ac193720bb483dc2a2c266504b33d1a9.tar.xz | |
git-codereview: make commit-msg hook play nicely with other systems
Gerrit requires 'Change-Id:' lines to be included in each commit
message, but they are not the only kind of 'metadata line' that might
appear in a commit message. Metadata lines observed by other systems
include 'Bug:' and 'Signed-off-by:'. This change ensures that the
commit-msg hook adds its 'Change-Id:' line to the set of metadata lines,
separated only by a single linefeed, rather than creating a new set by
inserting two line feeds.
Change-Id: Ia3bdce6f52f663685eea1e648874ef81ddb2bd91
Reviewed-on: https://go-review.googlesource.com/c/review/+/169097
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
Diffstat (limited to 'git-codereview/hook.go')
| -rw-r--r-- | git-codereview/hook.go | 31 |
1 files changed, 23 insertions, 8 deletions
diff --git a/git-codereview/hook.go b/git-codereview/hook.go index b80c567..09bed8b 100644 --- a/git-codereview/hook.go +++ b/git-codereview/hook.go @@ -189,15 +189,12 @@ func hookCommitMsg(args []string) { // Add Change-Id to commit message if not present. if nChangeId == 0 { - n := len(data) - for n > 0 && data[n-1] == '\n' { - n-- + data = bytes.TrimRight(data, "\n") + sep := "\n\n" + if endsWithMetadataLine(data) { + sep = "\n" } - var id [20]byte - if _, err := io.ReadFull(rand.Reader, id[:]); err != nil { - dief("generating Change-Id: %v", err) - } - data = append(data[:n], fmt.Sprintf("\n\nChange-Id: I%x\n", id[:])...) + data = append(data, fmt.Sprintf("%sChange-Id: I%x\n", sep, randomBytes())...) } // Add branch prefix to commit message if not present and on a @@ -221,6 +218,24 @@ func hookCommitMsg(args []string) { } } +// randomBytes returns 20 random bytes suitable for use in a Change-Id line. +func randomBytes() []byte { + var id [20]byte + if _, err := io.ReadFull(rand.Reader, id[:]); err != nil { + dief("generating Change-Id: %v", err) + } + return id[:] +} + +var metadataLineRE = regexp.MustCompile(`^[a-zA-Z0-9-]+: `) + +// endsWithMetadataLine reports whether the given commit message ends with a +// metadata line such as "Bug: #42" or "Signed-off-by: Al <al@example.com>". +func endsWithMetadataLine(msg []byte) bool { + i := bytes.LastIndexByte(msg, '\n') + return i >= 0 && metadataLineRE.Match(msg[i+1:]) +} + var ( fixupBang = []byte("fixup!") squashBang = []byte("squash!") |
