1

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?

MarkTO
  • 115

1 Answers1

2

What you are after is actually an update hook.

Your commit hook seems to need tweaking before it will work, but in any case a commit hook would only prevent users from committing to their own (remote) repo.

Since it is their own repo, they could simply change the hook to allow their commit, and then push to your repo. So this would not give you anything stronger than .gitignore.

An update hook, on the other hand, will control what can be pushed to your (master) repo. There's an example here based on checking file contents, which you can adapt to check filenames instead.

Reg Edit
  • 4,886