sa1
sa1

Reputation: 199

Remove file from amended commit

I pushed a commit to a repo where I accidentally added a file. Nobody else has merged from the remote repo so I can rewrite history. But when I remove file(unstage, not remove from source control, or disk) from local commit, I am unable to push changes. git push shows Everything up-to-date

Upvotes: 16

Views: 10124

Answers (5)

xeruf
xeruf

Reputation: 3010

With these two commands you immediately revert all changes to FILE in the last commit without changing its (working tree) contents:

git reset HEAD~ "FILE"
git commit --amend --no-edit

Simplified based on the answer at https://superuser.com/a/567550

Note that this will add all currently staged changes into the commit as well, so you might want to run git restore --staged -- $(git rev-parse --git-dir) beforehand.


Previous solution derived from the answer of @ColinHebert

git diff -p HEAD~ -- "FILE" | git apply --reverse --cached
git commit --amend --no-edit

Upvotes: 3

sa1
sa1

Reputation: 199

While I did something similar to what Colin and ydroneaud have suggested,

The answer was to use

git push +sa1:sa1

where sa1 is my branch. This forces to push even 'nothing'.

Upvotes: 3

Colin Hebert
Colin Hebert

Reputation: 93197

Here you go:

git checkout HEAD~ -- path/to/your/file
git add path/to/your/file
git commit --amend -C HEAD

git diff -p HEAD~ -- path/to/your/file | git apply -R
git commit --amend -C HEAD

git reset HEAD~ -- path/to/your/file
git commit --amend -C HEAD

Upvotes: 16

Yann Droneaud
Yann Droneaud

Reputation: 5493

If you need to rewrite the full commit, try to use

git reset HEAD^
git add <files to be part of the commit>
# or git add -pu
git commit -C <previous commit number>

Before doing this you will need to keep the last commit number to able to reuse the commit message/date/author.

Upvotes: 6

KurzedMetal
KurzedMetal

Reputation: 12946

Try:

git rm --cached <yourfile>
git commit --amend
git push -f

Upvotes: 9

Related Questions