30 January 2012

Git - alias to get my last commits

While working with Git, there is lots of situation where it is interesting to give a quick list of your last commits.
For the current version you're working on, or for any other version.
But usually, you are not alone to commit and so you need to filter result of git log (on author for instance).

This is a very simple GNU/Bash script allowing to list a short form of your last commits (for instance create a file /path/to/gitListMyLastCommits.sh and copy/paste):
#!/bin/bash
#
# Author: Bertrand BENOIT 
# Version: 1.1
# Description: lists last commit of current author according to specified (optional) branch and count.

# To use this script, create a git alias.
# git config --global alias.mc '!/path/to/gitListMyLastCommits.sh'

DEFAULT_COMMIT_COUNT=5
export GIT_PAGER=cat

# Manages command line options.
# - case 1: 2 specified arguments
# - case 2: 1 specified argument [-] (with optional negative sign)
# - case 3: no specified arguments -> work on current branch, with 5 last commits of author
if [ $# -gt 2 ] || [ $( echo "$@" |grep -cwE "(-h|--help)" ) -gt 0 ]; then
echo -e "usage: git "
echo -e "The branch can be ommitted"
echo -e "The commit count can be ommitted (default: $DEFAULT_COMMIT_COUNT will be shown)"
echo -e "If only one argument is given, it is regarded as commit count, so you can NOT only specify a branch, without a commit count"
exit 1
fi

# Ensures there is a negative sign for last argument, if needed.
if [ $# -eq 0 ]; then
arguments="-$DEFAULT_COMMIT_COUNT"
else
arguments=$( echo "$@" |sed -e 's/^\([0-9][0-9]*\)$/-\1/;s/[ ]\([0-9][0-9]*\)$/ -\1/' )
fi

authorInfo=$( git config --get user.email )
[ -z "$authorInfo" ] && echo "WARNING: unable to define author information, ensure you have configured user.email." >&2 && exit 1

echo -e "Looking last commits of author '$authorInfo', with arguments: $arguments"
git log --format='%h - %cd - %s' --date=short --author="$authorInfo" $arguments

echo -ne "\nOrdered commit short SHA1 chain (can be used with cherry-pick): "
git log --format='%h - %cd - %s' --date=short --author="$authorInfo" $arguments |awk '{print $1}' |sed -e 's/$/ /g' |tac |tr -d '\n'
echo ""
At the end, it will give a one-line list of SHA1 corresponding to reversed order of your last commit; it can then be easily copy/paste to cherry-pick.

You can add this script as a new Git alias:
git config --global alias.mc '!/path/to/gitListMyLastCommits.sh'

Then to get your last 5 commits on current version:
git mc

To get your 20 last commits on current version:
git mc 20
or
git mc -20

Finally to get 10 last commits of branch R1_0:
git mc R1_0 20

No comments:

Post a Comment

Thank you for your visit, let's share your point of view: