First question... is it even possible to accomplish this with git? :)
What I want is this:
Sometimes I switch one variable in my code to true
(localMode = true;
) for my own debugging purposes. But this should never be commited. I should only commit code with the variable set to false
. And of course sometimes I forget to make this change. Is it possible for git to somehow stop or warn me if I am about to commit the 'wrong' code?
UPD:
Thanks for the help! I ended up with the following shell script:
#!/bin/bash
git diff --cached --name-only | while read FILE; do
if [[ $(echo "$FILE" | grep -E "^.+main\-controller\.js$") ]]; then
content=$(<"$FILE")
if [[ $(echo "$content" | grep -E "rootScope\.localMode = true") ]]; then
echo -e "\e[1;31m\tCommit contains localMode set to true.\e[0m" >&2
exit 1
fi
fi
done
The pre-commit hook is run first, before you even type in a commit message. It's used to inspect the snapshot that's about to be committed, to see if you've forgotten something, to make sure tests run, or to examine whatever you need to inspect in the code.
Once the terminal windows is open, change directory to . git/hooks . Then use the command chmod +x pre-commit to make the pre-commit file executable.
Just run git commit . You don't have to add anything before doing this, hence in the end you get the message no changes added to commit .
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.
Yes, you can use a pre-commit
hook.
Just drop a shell script named pre-commit
(with no extension) inside your ".git/hooks" folder with the logic to check your variable and either:
false
and continue with the commit orThe hooks folder should contain a few samples, such as "pre-commit.sample", which you might find helpful.
From the docs:
The
pre-commit
hook is run first, before you even type in a commit message. It’s used to inspect the snapshot that’s about to be committed, to see if you’ve forgotten something, to make sure tests run, or to examine whatever you need to inspect in the code. Exiting non-zero from this hook aborts the commit, although you can bypass it with git commit --no-verify. You can do things like check for code style (run lint or something equivalent), check for trailing whitespace (the default hook does exactly this), or check for appropriate documentation on new methods.
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