2

Let's say I have a commit history like this:

commit 1 - The first commit
commit 2 - The commit I want to revert, but keep the changes of
commit 3 - The third commit
commit 4 - The fourth commit
[uncommited work]

If I haven't pushed anything yet (or only up to commit 1), how can I delete commit 2, but apply the changes made in commit 2 to the currently uncommited work?

All I could find was about how to delete the commit and it's changes or reset to that commit, which would (as I understand) remove all commits afterwards from the history.

causa prima
  • 1,502
  • 1
  • 14
  • 24
  • Watch [how to push specific commit](https://stackoverflow.com/questions/3230074/how-can-i-push-a-specific-commit-to-a-remote-and-not-previous-commits) – Òscar Raya Jun 29 '17 at 14:09
  • I don't want to push a specific commit. I want to delete a specific commit, but keep the changes made (for now). – causa prima Jun 29 '17 at 14:30

2 Answers2

3

I would reorder the revisions the way you want, then cherry-pick commit 2, stash pop and then set the HEAD pointer to "rebuilt" commit 4:

git stash save "will come back"
git checkout commit1
git cherry-pick commit2..commit4
git cherry-pick  commit2
git stash pop
git reset --soft HEAD~1

That should do

eftshift0
  • 26,375
  • 3
  • 36
  • 60
  • You are right, this should do. But I thought there might be a single command for that, so if someone else has such a command I will accept that answer instead. Maybe @Pandelis answer also works, but I'm not sure about that yet. – causa prima Jun 29 '17 at 14:26
  • Not to sound too pessimistic but I don't think the git community can not provide a single separate git command for every single situation that might come up. The case you exposed just happens to be (kind of) "easily solvable" by using the commands already available with git. – eftshift0 Jun 29 '17 at 14:49
  • Yes, and this makes perfect sense. I just thought that I might have missed an option. I also didn't realize that you can cherry-pick like that, so thanks for that! – causa prima Jun 30 '17 at 05:54
  • 1
    Here you end up in a detached HEAD state, so you need to also do: `git branch temp git checkout git reset --hard temp` – user2340939 Mar 27 '22 at 12:40
  • Good catch. Just in case, this was from before the times I learned the wonders that `git rebase -i` can do. :-) – eftshift0 Mar 27 '22 at 12:50
0

I believe git rebase -i HEAD~3 should do the trick.

You'll then be able to select commit 2 to edit, change the contents of the commit or the files that have been changed, then git will 'replay' commit 3 and 4 on top of the edited commit 2

Pandelis
  • 1,854
  • 13
  • 20
  • But I don't want to edit the commit 2 and apply commits 3 and 4 on top of that. Maybe I even decide that the current changes and the changes made in commit 2 are all useless and I delete them all. – causa prima Jun 29 '17 at 14:29