Reputation: 2749
I have a range of commits in my local git repository with the following messages:
Added source.h
Broken link fixed
Corrected unit test
Deleted deprecated algorithm
...
Before pushing them to the server, I would like to prepend ticket information to every commit message:
Ticket #9999 (1): Added source.h
Ticket #9999 (2): Broken link fixed
Ticket #9999 (3): Corrected unit test
Ticket #9999 (4): Deleted deprecated algorithm
...
Of course I could git rebase
and reword
every sigle commit, but I would like to automate the process as it's so repetitive.
I think it should somehow be possible with git filter-branch
, but the environment variables only provide
GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, GIT_AUTHOR_DATE, GIT_COMMITTER_NAME, GIT_COMMITTER_EMAIL, and GIT_COMMITTER_DATE
, but not the message.
How can I access and automatically manipulate the commit messages?
EDIT: Note that the ticket number is always the same, but the number in the brackets is incremented successively.
Upvotes: 1
Views: 823
Reputation: 2749
Following the hint from Mark to use the --msg-filter
option of filter-branch
, the full solution is:
If the commit range is XXX..HEAD
, the bracketed number can be expressed with git rev-list --count XXX..$GIT_COMIIT
.
Thus the messages can be transformed with sed
:
git filter-branch --msg-filter '
i=`git rev-list --count XXX..$GIT_COMIIT`
sed "1s/^/Ticket #9999 ($i): /"
' XXX..HEAD
Upvotes: 2
Reputation: 45659
Assuming you have logic for which ticket number to attach to each message, you would use the --msg-filter
option of filter-branch
. See the docs at https://git-scm.com/docs/git-filter-branch for details.
Upvotes: 2
Reputation: 56
There is a githook for this exact functionality.
This code will prepend the branch name to the commit message:
#!/bin/sh
BRANCH_NAME=$(git branch 2>/dev/null | grep -e ^* | tr -d ' *')
if [ -n "$BRANCH_NAME" ]; then
echo "[$BRANCH_NAME] $(cat $1)" > $1
fi
If you want to get this working you first need to make an executable in the .git/hooks directory in your repo and call it commit-msg
.
See this link for the source above: https://gist.github.com/bartoszmajsak/1396344/97081e76ab275f5fe526347908503febd1340495
Also another useful link about git hooks: https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks
Upvotes: 2