Reputation: 776
This is my pre-commit hook:
#!/bin/sh
echo "removing file.txt"
rm file.txt
exit 0
and this is the output for git commit:
$ git commit -m "test"
removing file.txt
[master (root-commit) b82b2e1] test
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 file.txt
Why does it recognize file.txt ?? Is it because it's not included in gitignore?
Upvotes: 0
Views: 11413
Reputation: 38734
If you would have added the file to .gitignore
, it would not have been added to the index unless you force it to, so I guess you want to put it to .gitignore
instead. If you still want to do it via pre-commit
hook, you should remove the file from the index, not the worktree, so use git rm --cached --ignore-unmatch -- file.txt
instead of rm file.txt
in your pre-commit
hook to remove the file from the index if present, instead of removing it from the worktree.
Upvotes: 1
Reputation: 490078
I am not sure what, precisely, you mean by the verb recognize, but the main issue here is that Git does not make commits from the work-tree. Git makes commits from the index.
When you git add file.txt
, that copies the contents of file.txt
from the work-tree into the index. If the file file.txt
did not appear in the index before, it does now. If it was in the index before, the old index contents are now replaced with whatever was in the work-tree file.txt
.
When you run git commit
, that takes whatever is in the index right now and turns that into a commit. In your pre-commit hook, you modify the work-tree, but not the index—so the index remains as it was, and the file goes into the commit.
Upvotes: 2
Reputation: 142642
If you already added the file to git in the past girt will track it until you tell it not to = delete it.
.gitignore
will not help you in this case since its already tracked.
You have to do this:
# remove it from the index and commit it
git rm --cached <file.txt>
and now add it to the .gitignore and commit it.
Upvotes: 1