Git Hooks: Automating Your Workflow with Pre-Commit and Post-Receive
It’s 2008, and the Linux kernel, Ruby on Rails, and jQuery have all moved to Git. Many of us are still getting used to the "distributed" nature of Git after years of SVN. But one feature is already proving to be a game-changer for team productivity: Hooks.
Hooks are scripts that Git executes before or after certain events (like committing, pushing, or receiving). They reside in the .git/hooks directory of your repository.
Preventing Bad Commits (pre-commit)
We've all been there: you commit code only to realize you left a console.log or a syntax error in it. A pre-commit hook can stop the commit if it doesn't pass your quality checks.
#!/bin/sh
# .git/hooks/pre-commit
# Run a linter (e.g., JSLint via Rhino in 2008)
jslint src/*.js
if [ $? -ne 0 ]; then
echo "JSLint failed! Commit aborted."
exit 1
fi
echo "JSLint passed. Proceeding with commit..."
exit 0
Automated Deployment (post-receive)
This is the "killer app" for Git hooks. By setting up a post-receive hook on your production server, you can deploy your site simply by running git push production master.
#!/bin/sh
# On the server: /path/to/repo.git/hooks/post-receive
# Define where the live site files should go
TARGET="/var/www/my-awesome-site"
GIT_DIR="/path/to/repo.git"
while read oldrev newrev refname
do
if [ "$refname" = "refs/heads/master" ]; then
echo "Master branch received. Deploying to production..."
GIT_WORK_TREE=$TARGET git checkout -f master
# Run any build scripts
cd $TARGET
./build.sh
fi
done
Sharing Hooks with Your Team
Because the .git directory isn't versioned, you can't commit your hooks directly. The standard 2008 practice is to create a hooks directory in your project root and tell your teammates to symlink them:
ln -s ../../hooks/pre-commit .git/hooks/pre-commit
Git is more than just a place to store code; it's an automation engine. By leveraging hooks, we can ensure that our "Master" branch is always clean and that our deployment process is as simple as a single command.
Aunimeda provides DevOps engineering and infrastructure services - CI/CD pipelines, containerization, cloud deployments, and monitoring setups.
Contact us to discuss your infrastructure needs. See also: DevOps Services, Custom Software Development