Black Sheep Code

How to prevent further modification commits to a file with a pre-commit hook

Published:
Accidentally making changes to test data file while working other things

I've been working on AI tool recently, and it involves saving large structured data files which I use my tests.

Sometimes I'll have a file that's working in one context, and I'm trying to work it work in another context, and I'll want to modify for that other context, just temporarily, to see if works.

But I don't want to accidentally make a permanent change to my 'source of truth' files.

A pre-commit git hook helps here:

#! /bin/sh -e

# .git/hooks/pre-commit
# Prevent the test files etc from accidentally being modified 
REGEX='.*(preservedLogs|specs|testFixtures).*'
git diff --name-only --cached | grep -qxE "$REGEX" && { echo "❌ Excluded file included in the commit:"; git diff --name-only --cached | grep -E "$REGEX"; exit 1; }

Chmod this file with

chmod +x .git/hooks/pre-commit

and you're set!

If your change is intentional, you can always opt out of the pre-commit logic with git commit --no-verify.

Note that git hooks in themselves will not be version controlled, so if you need this hook to be used by everyone in your project, you may wish to use a tool like Husky.



Questions? Comments? Criticisms? Get in the comments! 👇

Spotted an error? Edit this page with Github