Execute a Git hook by branch

git_logo

Many times I’ve been working in several projects when deployment of different webs according to a branch are necessary. Finally I just wrote a tiny Git hook script that helps me out with this matter, I hope it could help you as it does to me.

By example, for branch master I need that every time someone pushes commits to it, changes deploys in /path/to/my/deployment/unstable, and if branch stable is pushed, then changes are deployed in /path/to/my/deployment/stable.

The script I wrote uses the post-update hook, and cut to “parse” the revision name and provide the branch name, then I can use that name to set the path of the repo. After that I check if that directory exists, and then change the GIT_DIR to that path. Finally I change the position to that path and execute a simple git pull specifying the name of the branch.

Feel yourself free to use it. :)

#!/bin/bash
#
# An example hook script to prepare a packed repository for use over
# dumb transports.
#
# To enable this hook, rename this file to "post-update".

BRANCH=`echo $1 | cut -d '/' -f 3`

if [ $BRANCH == 'master' ]; then

  STAGE='unstable'

else

  STAGE=$BRANCH

fi  

STAGE_PATH=/my/stage/path/$STAGE/

if [ -d $STAGE_PATH ]; then

 GIT_DIR=$STAGE_PATH/.git
 cd $STAGE_PATH
 git pull origin $BRANCH

else

 echo 'Stage path for '$STAGE' not found'

fi

exec git update-server-info

 

Basilio Briceño

DevOps evangelist, SoftwareLibre activist, sometimes speaker & eclectic metalhead.

3 comments

  1. fitorec   •  

    Interesante yo ahorita lo que ando buscando es un buen sistema de ganchos que me ayude a actualizar un sitio con la acción post-pull.

    Respecto al script veo que defines una variable STAGE_PATH, creo que el valor de esta lo puedes hacer dinamicamente y con esto reutilizas mas tu script, típicamente yo suelo ocupar la instrucción:


    PATH_SCRIPT = $(readlink -f "$0" | xargs dirname )

    En el caso especifico de git, puedes ocupar:

    git rev-parse --show-toplevel

  2. fitorec   •  

    También puedes ocupar la variable $GIT_DIR.

  3. Basilio Briceño   •  

    Gracias por el comentario, muy buen tip, en este caso puse un path absoluto como ejemplo, por que puede haber casos donde el path sea diferente a la ubicación actual.

Leave a Reply to fitorec Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>