I have a commit template set up for git, and I would like to include the name of the current branch in it. I usually set up the branch to be the bug id, and it would help me
Just cobbling together the comments from Jefromi's answer, I end up with something like this. Surely it could be tighter (if I knew what I was doing):
tempFile='/tmp/git-commit-template'
git config commit.template "$tempFile"
rm $tempFile
branch=$(git symbolic-ref HEAD|sed s#refs/heads/##) exec 3<> "$tempFile" && awk -v TEXT="[$branch]" 'BEGIN {print TEXT}{print}' "$tempFile" >&3
git add .
git commit -a
I'd probably just use the prepare-commit-msg hook to add that to the file. From the (linked) manpage:
This hook is invoked by git commit right after preparing the default log message, and before the editor is started.
It takes one to three parameters. The first is the name of the file that contains the commit log message. The second is the source of the commit message ... [message, template, merge, squash, or commit] ...
If the exit status is non-zero, git commit will abort.
The purpose of the hook is to edit the message file in place ...
You can get the current branch with git symbolic-ref HEAD
.
You could just bypass templates altogether, and have the hook prepend/insert/append the branch name. Simplest case, appending, the script is just a shebang line, then git symbolic-ref HEAD >> "$1"
. Use your favorite method if you want to embed it - most readable to move the original aside, write, and append, but the method linked in the comments certainly works too.
If you'd prefer to use a template with placeholders, you could just do something like sed -i "s/Bug : \$BUG/BUG : $(git symbolic-ref HEAD)/" "$1"
. I'm sure you can imagine a lot of other variations.
You might want to suppress this behavior for some of the types of commits (that second argument) or even only turn it on if the second argument is "template", if you're using the boilerplate substitution approach.
A solution using git alias but no template:
$ git config --global alias.com '!sh -c "bug=`git symbolic-ref HEAD|sed s#refs/heads/##`; git commit -em \"BUG: \${bug}\""'
$ git com