How to automatically prefix Git commit message with current branch label?

git
jira

#1

There is a really nice feature of the Jira / Git integration where if you give a Git branch the same name as a Jira ticket label (e.g. SP-678), then the commit history of that branch is automatically reported in the Jira ticket. Well, it seems that the linking is automatic, but the commit reporting only works if you also remember to prefix your commit message with the branch name. This seems like repetition to me and I invariably forget.

So my question is How can I automatically add the branch name prefix to my commit messages?

Alternatively, is there another way?


#2

Sounds like a job for a prepare-commit hook.

Save this as prepare-commit-msg in .git/hooks in your repository. Change the first line to wherever your Rscript is located.

#!C:/R/R-3.5.1/bin/Rscript.exe

last_commit <- commandArgs(trailingOnly = TRUE)[1]
branches <- system("git branch", intern = TRUE)
current_branch <- strsplit(branches[startsWith(branches, "*")], split = " ")[[1]][2]

if (current_branch != "master" && !startsWith(last_commit, current_branch)) {
  stop("Commit failed to have the required prefix: ", current_branch)
}

I've assumed you don't want this to apply to the master branch


#3

Thanks very much Hugh. In your example last_commit is just the name of the file holding the message, right? (It was a revelation to see all this .git stuff in the background.)

I've modified it slightly to paste in the current_branch and rewrite the file. I hope readLines and writeLines will work in general.

#!C:/Program Files/R/R-3.5.2/bin/Rscript.exe

# current branch name
branches <- system("git branch", intern = TRUE)
current_branch <- strsplit(branches[startsWith(branches, "*")], split = " ")[[1]][2]

# commit message file name
commit_msg_file <- commandArgs(trailingOnly = TRUE)[1]

# check, ?add prefix
commit_msg <- readLines(commit_msg_file)
if (current_branch != "master" && !startsWith(commit_msg, current_branch)) {
  writeLines(paste(current_branch, commit_msg), commit_msg_file)
}

# check again
commit_msg <- readLines(commit_msg_file)
if (current_branch != "master" && !startsWith(commit_msg, current_branch)) {
  stop("Commit failed to have the required prefix: ", current_branch)
}

closed #4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.