Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git: restore my changes which were amended to merge commit

Tags:

git

git-commit

I accidentally amended merge commit instead of creating new one. Now I don't know how to extract the changes to normal commit which I can push. The changes will show up in gitk, but will not appear in format-patch. Please, help.

like image 739
Artem Avatar asked Oct 28 '14 03:10

Artem


People also ask

How do I revert changes after merge?

You can use the Git reset command to undo a merge. Firstly, you need to check for the commit hash (or id) so you can use it to go back to the previous commit. To check for the hash, run git log or git reflog . git reflog is a better option because things are more readable with it.

How do you restore committed changes?

With GitLens installed, open your repo in VS Code and right-click on the commit from the Commits view in the sidebar to get the Revert Commit option. You can also access this option through the command palette by typing >GitLens: Git Revert or from the commit details' quick pick menu.

Can you revert a merge request?

Revert a merge requestAfter a merge request is merged, you can revert all changes in the merge request. Prerequisites: You must have a role in the project that allows you to edit merge requests, and add code to the repository.


2 Answers

You have 2 SHAs that are of interest here - the original merge commit, and the amended merge commit. What you want to do is git reset your HEAD to the original merge commit, while preserving your index and working directory. You can then create a new commit hanging off the merge commit.

Use

git reflog

to find the SHA of the original merge commit

reset to the commit with git reset ORIGINAL_MERGE_COMMIT_SHA or directly from reflog with git reset HEAD@{X} where X is 1 or the position in the reflog that represents the merge commit.

You should now be ready to git commit your original changes and don't pass in --amend here and you will create a new commit.

like image 50
Andrew C Avatar answered Oct 10 '22 20:10

Andrew C


I've found one way which works:

git diff HEAD~1 > p.patch
git checkout master
git checkout -b branch-name

Manually edit p.patch to remove unrelated changes from merge.

git apply p.patch

But I suspect there is a much easier/better way to do it.

like image 24
Artem Avatar answered Oct 10 '22 22:10

Artem