Convert a `git commit --amend` into a different commit

by GabLeRoux
macOS ◆ xterm-256color ◆ zsh 764 views

thanks to git reflog, this is pure magic!

mkdir gitfun
cd gitfun

git init

touch test
git add test
git commit -m "added test"

touch other_file
git add other_file
git commit --amend
#"but this is a mistake"

git  reflog > some_temporary_reflog
cat some_temporary_reflog
git checkout <HEAD@{1}: commit (initial): added test>
# now in detached head

git cherry-pick <hash from HEAD@{0}: commit (amend): but this is a mistake> --no-commit
# still on detashed head but with unstaged changes from wrong ammend

git commit -m "new commit I wanted to do before"

# you can then reset a local branch to your current HEAD
git checkout -B master

Some documentation:

https://en.wikibooks.org/wiki/Git/Internal_structure#The_Reflog

The reflogs record changes that are not saved as part of the commit history—things like rebases, fast-forward merges, resets and the like. There is one reflog per branch. The reflog is not a public part of the repository, it is strictly specific to your local copy, and information is only kept in it for a limited time (2 weeks by default). It provides a safety net, allowing you to recover from mistakes like deleting or overwriting things you didn’t mean to.

https://www.atlassian.com/git/tutorials/refs-and-the-reflog/the-reflog