Reputation: 13
I had 2 commits (local) and my history were : A - B :
I wanted to amend the commit A and replace the file in its new form in order to have a clean history before pushing anything.
I did this :
reset --soft
on Aadd
myfile_v2.txtcommit --amend
Now I can see that my commit A has the corrected file in it, but I cannot figure out how to go back in my previous HEAD nor if this is possible without committing B again.
Any ideas?
Upvotes: 1
Views: 923
Reputation: 1031
You cannot modify a previous commit. Each commit is unique.
What you can do is to recreate the history with new commits. Using the command git-rebase
I understand that you are in this point now:
Pre_A - A - B
\
A1
You have lost your "B" Commit. To recover the commit use git-reflog
git reflog
You will see the latest position of the branch HEAD
. One of them is the B commit. Write down the Hash of the beginning of the line. Example:
git reflog
a123b Ammend Commit of Previous A that generates A1 commit
b234c git reset soft to A Commit
c345d B Commit
b234c A Commit ##Look that the HASH is the same that the git-reset##
Once you have the HASH of the B Commit. Create a branch to recover the commit.
git branch tmpBranch c345d
At this point, what you need is to put this commit in the new history of "A1" instead of being in "A". You get this using git-rebase
I assumpt that you were working in your master branch.
git checkout tmpBranch
git rebase --onto master tmpBranch~1 tmpBranch
This recreate the history from one commit backward of tmpBranch commit until tmpBranch commit (in your case only one commit, The B commit) in master (that points to A1 commit).
Upvotes: 1
Reputation: 38734
A commits hash contains the full history of this commit. So if you change the history, the history does not belong to that commit anymore, but the commit has to be recreated.
There are many ways to do this. In your case you could just cherry-pick
B
and all is good.
How I would have done it is an interactive rebase (rebase -i
). Either by first doing the interactive rebase, changing the stanza of A
to edit
, then doing the commit amending and then continuing rebasing. Or alternatively first create a new commit on top of B
and then use rebase -i
to reorder and squash
or fixup
the second commit. Or even using auto-fixup or auto-squash.
Upvotes: 1