Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git hook to reject commits where files contain a specific string

Tags:

git

I am using Guard with Rspec; I use focus: true to force it run only tests I am working on. But sometimes I forget to remove focus: true and it is causing distraction for my future self and people I work with.

I want to make a git hook that would check the spec folder to make sure there is no focus: true in test files apart from spec/rails_helper.rb and keep it in Repository.

I have read this answer Putting git hooks into repository, guess it has to be a bit awkward.

How are hooks used to prevent a commit based on the contents of files?

Update

Here is what I have now but it doesn't work, even if there is no match, git refuses to commit.

FILES_PATTERN='\.rb(\..+)?$'
FORBIDDEN="(\, focus: true|binding\.pry)"
git diff --cached --name-only | egrep "$FILES_PATTERN" | xargs egrep --with-filename -n "$FORBIDDEN" && echo "Commit reject, found $FORBIDDEN reference, please remove" && exit 1
exit 0
like image 337
firedev Avatar asked Nov 10 '14 02:11

firedev


People also ask

What is bypass commit hooks?

This hook is invoked by git commit, and can be bypassed with --no-verify option. It takes no parameter, and is invoked before obtaining the proposed commit log message and making a commit. Exiting with non-zero status from this script causes the git commit to abort.

What type of git hook could be used to validate that a commit message contains a ticket number?

The commit-msg hook takes one parameter, which again is the path to a temporary file that contains the commit message written by the developer. If this script exits non-zero, Git aborts the commit process, so you can use it to validate your project state or commit message before allowing a commit to go through.

How do you find a list of files that have changed in a particular commit?

Find what file changed in a commit To find out which files changed in a given commit, use the git log --raw command.

How do I ignore a git hook?

Use the --no-verify option to skip git commit hooks, e.g. git commit -m "commit message" --no-verify . When the --no-verify option is used, the pre-commit and commit-msg hooks are bypassed.


1 Answers

A good source of information is the book at git-scm.

You want the pre-commit hook. To return a non-zero value (and thus abort the commit), you'd want something along these lines:

FILES_PATTERN='\.rb(\..+)?$'
FORBIDDEN='focus: true'
git diff --cached --name-only | \
  grep -spec/ | \
  grep -E $FILES_PATTERN | \
  xargs grep --with-filename -n $FORBIDDEN && echo "COMMIT REJECTED Found '$FORBIDDEN' references. Please remove them before commiting" && exit 1

That's lifted from this rather good tips site. I haven't tested the tweaks I made.

like image 161
Paul Hicks Avatar answered Oct 05 '22 21:10

Paul Hicks