I need to set a pre-commit trigger to prevent certain file types from being committed to my GitHub Repository at all. I have already set .gitignore, which works for what it does, but that can be overridden with the -f flag. I want to lock it down so that forcing is not a thing.
I went into .git/hooks and renamed pre-commit.sample to pre-commit and used this command to try to block the use of .txt files:
git ls-files --cached | grep -qx 'txt$' && { echo "This file type is forbidden" >&2; exit 1; }
My reasoning is this:
git ls-files --cached to get a list of cached files up for commit
| grep -qx 'txt$' to filter all files ending with 'txt' but not list output to screen
&& { echo "This file type is forbidden" Tell the user no .txt files
>&2; exit 1; } pipe to stderr, escape with error so no commit happens
exit 0 if the pattern is not found, proceed with commit.
This is similar to this question: Mark file as “uncommitable” with Git
However, that question does not address the problem I have, as the solution there does not actually work for what I am trying to do. The trigger seems to only work when there is no argument on the git commit but even a -m "commit message" makes it fail.
Even though the hook does trigger, I can still add a .txt file to staging, commit it, and push it to my remote. Why does the pre-commit trigger fail to block the commit?