Bostonian
Bostonian

Reputation: 687

How to revert the non lastest commit but still keep the head intact

Below is the my git history:

commit-X: LOCAL HEAD which has not been push to remote commit-A: The commit I want to undo and it is not push to remote yet. commit-B: The REMOTE HEAD.

It is possible to undo commit-A and still keep my LOCAL HEAD pointing to commit-X?

Thank you.

Upvotes: 1

Views: 39

Answers (2)

Andrei Mustata
Andrei Mustata

Reputation: 1133

You can try an interactive rebase, with git rebase --interactive HEAD~2

This will mark HEAD and the commit before it as up for rebase; for 3 commits, use HEAD~3, etc. This means you can change the commit itself, just the message, make more commits out of 1, make 1 commit out of many.

Practically, your default text editor will be brought up with the list of commits, and what action to take for each. Once you save the file (exit, or whatever), git will try to apply your changes.

If you want to nuke it, obliterate it completely, then you can simply remove the whole line of commit-A. Not touching the commit-X line means that git will re-apply the commit exactly as you made it (same changes, same message), without you having to do anything else.

Before doing any destructive git stuff, you could make it a habit to create a new branch where you are at the time. This way, if your commit surgery goes sideways, you can always get back to the original branch safely. For a broader safety net, check out git reflog.

Be aware that changing a commit (messages, contents, etc) means that it has a new hash, and all the downstream commits (made after the changed one), will have to be redone. This is important, because, if you've already pushed to the remote before changing it, then you can't sync the remote, unless you do a --force push, but that will potentially make the other parties unhappy.

Upvotes: 1

Green-Avocado
Green-Avocado

Reputation: 891

If you want to remove commit-A while keeping the same changes under commit-x, one option is to run git reset --soft HEAD~2, which will remove the last 2 commits while keeping your files as they are. From here, you can reapply commit-x.

Upvotes: 1

Related Questions