Continuing https://mcmap.net/q/115890/-how-to-tell-git-to-ignore-individual-lines-i-e-gitignore-for-specific-lines-of-code-duplicate, @Mike proposed to create a pre-commit
hook which will grep
in the staged files for the lines which one might want to ignore. The hook checks if those lines were staged. If so, it echo
s a warning and it exit
's with code 1
so the commit process won't continue.
Inspired by @Mike's answer, I found myself using perhaps an improved version of his hook which automatically reset
s (with the -p
flag) the specific line which we want to ignore.
I'm not sure this hook will work for a situation where you have many files with this line to be ignored, but this pre-commit
hook looks for a changed in this line in a specific file buildVars.java
. The hook script looked like this when I tested it on my machine.
#!/bin/sh
# this hook looks for lines with the text `var isPhoneGap = false;` in the file `buildVars.java` and it resets these lines to the previous state before staged with `reset -p`
if [[ $(git diff --no-ext-diff --cached buildVars.java | grep --count -e "var\ isPhoneGap[\ ]*=[\ ]*") -ne 0 ]]; then
cat <<EOW
WARNING: You are attempting to commit changes which are not supposed to be commited according to this \`pre-commit\` hook
This \`pre-commit\` hook will reset all the files containing this line to it's previous state in the last commit.
EOW
echo /$'\n'isPhoneGap$'\n'y$'\n'q | git reset -p
# BONUS: Check if after reseting, there is no actual changes to be commited and if so, exit 1 so the commit process will abort.
if [[ $(git diff --no-ext-diff --cached | wc -l) -eq 0 ]]; then
echo there are no actual changes to be commited and besides the change to the variable \'isPhoneGap\' so I won\'t commit.
exit 1
fi
fi
Explanation
What I did was echoing a control sequences which searches for the regex isPhoneGap
during an interactive reset
process. Thus emulating a user who presses /
to search for isPhoneGap
, presses y
when asked if he wants to discard this patch and finally presses q
to exit the interactive reset
.
The interactive reversed patch process is documented here: https://git-scm.com/docs/git-add#git-add-patch
NOTE: The above script assuming that the variable interactive.singleKey
is false
. If you configured yours to true
, remove any $'\n'
from the echo
command right after the warning.