Git Hooks

  • We always want to speed up our workflows, right? Of course, automation is the best way to do that.
    
    
  • Git hooks are scripts that Git executes before or after events such as: commit, push, and receive.
    
    
  • In my words, Hooks is like an event trigger, After you did some git operation it'll trigger some events.
    
    
  • There are two types of git Hooks.
    ​
           1.) Client side (Local PC)
    ​       2.) Server side (Remote Server)
    

What is Hooks

  • Git hooks is in .git folder in the project repository
     
  • You can use any scripting language
     
  • Have to make the hooks executable 

    ( Chmod +x file_name )

Where I can Find it ??

  • Built in scripts are mostly shell and perl
     
  • You can use shell script, Ruby, Python. You need to specify which interpreter are we using
               


     

Scripting Language

#!/bin/sh   => For shell Scripts

#!/usr/bin/env python    => For Python

#!/usr/bin/env ruby     => For Ruby
  • They are local to any Git repository and they are not copied to new repository.
     
  • To make the hooks stay update among developers or team it have to be under version control.
     
  • Store hooks in the project directory
     
  • Once it's updated copy those to the local .git/hooks folder

Scope of Hook..

  • applypatch-msg
  • pre-applypatch
  • post-applypatch
  • pre-commit
  • prepare-commit-msg
  • commit-msg
  • post-commit
  • pre-rebase
  • pre-receive
  • update
  • post-receive

Types Of Hooks (.git/hooks)

pre-commit

Pre-commit - Check (Commit Life Cycle)

prepare-commit-msg

commit-msg

post-commit

Pre-commit - 1 

diff_files = %x(git diff --cached --name-only)

rails_result = `grep -rlns "binding.pry" --exclude-dir=".git" #{diff_files}`

if rails_result != ""
	puts 'You have added binding.pry in your files'.colorize(:red)
	puts rails_result
	exit 1
end

Pre-commit - 2 


failures = %x(rspec spec/ |grep "examples"| grep "failure"| awk {'print $3'}).to_i


if failures!=0
	puts 'Your modified files doesnot passed the test'.colorize(:red)
	exit 1
else
	puts 'All test passed'.colorize(:green)
	exit 0
end

Tired of Scripting ?? Try pre commit

Thanks

Git Hooks

By Ashik Ajith

Git Hooks

  • 962