'Removing all local commits while preserving all the work

My remote repository looks like -

A->B->C

My local repository looks like -

A->B->C->D->E

The commits D and E were made by me. I also have some other local changes which have not been committed. I now want to remove commits D and E, but none of my work should get affected. When I'm done with everything, I want my local repository to look like -

A->B->C->X

What should I do from here?

git


Solution 1:[1]

You can use git stash to stash your local uncommitted work and then after you remove commits D and E using git reset you can perform git stash pop to bring back your uncommitted work from the stash

OR

If you want those commits D and E as a backup for later, you can create a new branch; say new_branch by checking out from the current branch

git checkout -b new_branch.

Now you have A->B->C->D->E in the new_branch

You can now commit your current work on top of this as commit X. So now it becomes A->B->C->D->E->X

Now you can checkout back to your previous branch, remove commits D and E using git reset and then cherry pick commit X from new_branch.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Arun T