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
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.
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.
Find what file changed in a commit To find out which files changed in a given commit, use the git log --raw command.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With