How to add previous commit messages and authors to you Git commit template?

I find having the context of the previous commit messages helpful when writing a new commit message. Especially when using Scoped Commits, it helps seeing scoped used in the past.

Git comes with a customizable message template, but it is static. What is needed is a wrapper around git commit to fetch the latest git commit messages, and to prepend this text to the current git message file.

To wrap our git commit, we can simply change our editor to a script:

[core]
editor = git-commit-wrapper.sh

The script that replaces our editor gets one argument: the commit message file with text from the git message template.

In this script, we can now dynamically run every command we want to get the context need, and put it into the commit message file before opening the file in our editor.

Currently, my git commit wrapper looks like this:

#!/bin/sh
set -e

COMMIT_MSG_FILE="$1"

# Show the latest 10 commits
{
	echo ""
	echo "# Recent commits:"
	git log --pretty=format:"%s" -n 10 | while read -r line; do
		echo "# $line"
	done
} >>"$COMMIT_MSG_FILE.tmp"

cat "$COMMIT_MSG_FILE" >>"$COMMIT_MSG_FILE.tmp"
mv "$COMMIT_MSG_FILE.tmp" "$COMMIT_MSG_FILE"

$EDITOR "$COMMIT_MSG_FILE"

Another nice feature that comes with most IDEs is the suggestion of co-authors. Neovim does not have this features. Giving our wrapper above its simple to extent it with previous authors.

#!/bin/sh
set -e

COMMIT_MSG_FILE="$1"

# Show the latest 10 commits
{
	echo ""
	echo "# Recent commits:"
	git log --pretty=format:"%s" -n 10 | while read -r line; do
		echo "# $line"
	done
} >>"$COMMIT_MSG_FILE.tmp"

# Suggest the last 5 authors as co-authors
{
	echo ""
	echo "# Recent authors:"
	git log --format='%an <%ae>' -n 5 | sort -u | while read -r author; do
		echo "# Co-authored-by: $author"
	done
} >>"$COMMIT_MSG_FILE.tmp"

cat "$COMMIT_MSG_FILE" >>"$COMMIT_MSG_FILE.tmp"
mv "$COMMIT_MSG_FILE.tmp" "$COMMIT_MSG_FILE"

$EDITOR "$COMMIT_MSG_FILE"

git