Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

git: Show message of last commit in commit template

Tags:

git

git commit opens the text editor and displays some information about the changes to be committed:

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#

#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#

I would like to extend this template to display

  • the first line of the N last commit messages and/or
  • the complete message of the last commit

of the current branch. How can I do that?

like image 362
realtime Avatar asked Sep 28 '13 06:09

realtime


1 Answers

This will use git hooks.

  • In your project root directory navigate to .git/hooks/
  • Now create the file prepare-commit-msg
  • Add the following bit of code:
#!/bin/sh
ORIG_MSG_FILE="$1"  # Grab the current template
TEMP=`mktemp /tmp/git-msg-XXXXX` # Create a temp file
trap "rm -f $TEMP" exit # Remove temp file on exit

MSG=`git log -1 --pretty=%s` # Grab the first line of the last commit message

(printf "\n\n# Last Commit: %s \n\n" "$MSG"; cat "$ORIG_MSG_FILE") > "$TEMP"  # print all to temp file
cat "$TEMP" > "$ORIG_MSG_FILE" # Move temp file to commit message
  • chmod +x prepare-commit_message

Idea borrowed from Enhancing git commit messages

You can grab the whole commit message by using %b and %B, but could run into issues with multiline commits. Might be able to get fancy with %-b and %-B, or just read more in the Documentation (scroll to format)

like image 92
Brombomb Avatar answered Oct 23 '22 11:10

Brombomb