//Karthik Srinivasan

Product Engineer, CTO & a Beer Enthusiast
Experiments, thoughts and scripts documented for posterity.

Quirky Personal Projects

LinkedIn

Email me

Useful Git Alias and Hooks

Dec, 2016

Git by itself is very raw and sometime hard to read the console outputs. Following are some of git alias that I tend to use on a daily basis.

git lg

This is a replacement to git log. git log doesn't provide any useful information such as branch name nor it's pretty looking! Yes pretty looking like colors and such. Following git alias solves this mundane problem.
$ git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"
Following is a comparison screenshot of git lg vs git log
Using git log:

Using git lg alias:

git unpushed

Every now and then I try to look for all uncommitted changes. But this quite a pain to look for from git console. Problem solved with the following alias:
$ git config --global alias.unpushed "log --branches --not --remotes --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"


git undo

git out-of-the-box doesn't provide an undo option to revert the previous commit. Pain! Following alias intends to solve the problem:
$ git config --global alias.undo "reset --hard HEAD~1"



Pre-push hooks

One of the most important hooks that I use is a pre-push hook that executes unit tests before pushing to "master" branch. This is important as it can save broken test cases being pushed to master branch. Following hook script:
#.git/hooks/pre-push
#!/bin/bash

CMD="sbt test" # Command to run your tests - I use Sbt test
protected_branch='master'

# Check if we actually have commits to push
commits=`git log @{u}..`
if [ -z "$commits" ]; then
exit 0
fi

current_branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')

if [[ $current_branch = $protected_branch ]]; then
    $CMD
    RESULT=$?
    if [ $RESULT -ne 0 ]; then
echo "failed $CMD"
        exit 1
    fi
fi
exit 0