You could do what you want by using a pre-commit hook:
pre-commit
This hook is invoked by git-commit
, and can be bypassed with the --no-verify
option. It takes no parameters, and is invoked before obtaining the proposed commit log message and making a commit. Exiting with a non-zero status from this script causes the git commit command to abort before creating a commit.
The simple code below unstages any changes to file2.py
immediately prior to commit and refuses to create any new empty commit — that is, if the only file changed was file2.py
.
#! /bin/bash
if ! git diff-index --quiet --cached HEAD -- file2.py; then
echo Discarding file2.py changes from the index
git reset HEAD -- file2.py
if git diff-index --quiet --cached HEAD; then
echo Aborting empty commit 1>&2
exit 1
fi
fi
Now that the academic question has been answered, I suggest using a different approach because the hook intentionally dumps the effort of controlling versions of the two different flavors of file2.py
back onto the human user. If you want to do manual version control, why use git at all?
Instead, let git do the job it’s good at by placing your changes into a separate branch
git checkout --no-track -b feature/singrium origin/master
that as master changes (to which you catch up by running git fetch
)
git checkout feature/singrium
git rebase origin/master
or into which you periodically merge changes from master.
git checkout feature/singrium
git merge origin/master
The difference between git rebase
and git merge
are in the respective histories they produce. If your changes to file2.py
are small and localized to a small number of commits, the rebase approach keeps those commits together as a patch on top of whatever the latest master is. If your history is more unwieldy, merges may be easier, at least in the short term.