Skip to content

Instantly share code, notes, and snippets.

@sw1nn
Last active January 19, 2016 08:42
Show Gist options
  • Save sw1nn/bd0972aa57b9d6d18d3f to your computer and use it in GitHub Desktop.
Save sw1nn/bd0972aa57b9d6d18d3f to your computer and use it in GitHub Desktop.

Git hooks suggestions

Problem Statement

With a centralized workflow we expect the branch master to be what's deployed /deployable to production. Changes are implemented on feature branches (typically named feature/<feature-name>) and merged into master via Github Pull request UI workflow.

This works fine, but occasionally a developer can make an error and push to master. We'd like to put some additional checks in place to protect against that.

Git version 1.9.x vs version 2.x.x

The default behaviour for pushing to branches changed in git 2.x. The new default is to push only the current branch with added checks to ensure that the remote and local branch names are the same. This is enabled by setting push.default to simple

git-config(1) says:

This is the safest option and is suited for beginners.

Git hooks

Git allows you to specify hooks that can do 'stuff' before and after the various git actions. These hooks are specific to your local copy of a repo (i.e you don't get them when you do a git clone)

Git templates - Making it work locally each time.

Git allows you to define a template directory which is used to populate your local .git directory when you clone. By putting the hooks shown below in a template directory and then registering the template directory with git, it should all just work™

git config --global init.templatedir ~/.git_template

Summary

git config --global push.default simple
mkdir -p ~/.git_template/hooks
git config --global init.templatedir ~/.git_template

# create ~/.git_template/hooks/pre-commit shown below
# create ~/.git_template/hooks/pre-push shown below

chmod 0755 ~/.git_template/hooks/*

# For existing repos:
cp -a ~/.git_template/hooks/* ${REPO_HOME}/.git/hooks
#!/bin/bash
if test $(git rev-parse --abbrev-ref HEAD) = "master" ; then
echo "Cannot commit to master by default."
echo -e "If you really think you want to you should get a colleague to review and then do\n\n\tgit commit --no-verify\n"
exit 1
fi
#!/bin/bash
if test $(git rev-parse --abbrev-ref HEAD) = "master" ; then
echo "Cannot push to master by default."
echo -e "If you really think you want to you should get a colleague to review and then do\n\n\tgit push --no-verify\n"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment