Zaki Aziz
Zaki Aziz

Reputation: 3852

Deleting all commits in a branch after certain commit

I'm having a difficult time grasping how I can use rebase/revert to accomplish this.

I was working on my master branch and after a certain commit my software stopped working. I did not want to loose the changes made at the time and I was pressured on time to reach a milestone so I went back a few commits with git checkout and created a new branch called working and started pushing all my changes there. Later on I realized that these changes (made on the master branch) were not needed. Now I want to go back to my master branch and delete all the commits after the commit I used to create my working branch and then merge my working branch to master branch.

I've created an image with an online photo editor to try and explain what I'm trying to do. I hope it helps:

screen shot of bitbucket

I want to keep everything after 5cb967f. get rid of everything between 5cb967f and a0c1de2 (not including those)

Upvotes: 25

Views: 28321

Answers (2)

jthill
jthill

Reputation: 60275

Something about the history graphic is screwy. Going by the text markup in it, what you want is simply

$ git branch -f master working

because there weren't any post-working-base commits on master that you want to keep.

Upvotes: 3

djs
djs

Reputation: 4776

You have two options:

Rewrite history (destructive)

You can use git-rebase to rewrite history, ommiting these commits. You can run an interactive rebase. From your description, I'm not certain exactly what you have in master and working, but I am assuming all the history (wanted and unwanted) is present there.

  git checkout master
  git rebase -i a0c1de2

At this point, your $EDITOR will pop up with a list of commits from a0c1de2 to the HEAD of master. You can remove the lines corresponding to c460070..a3cb10e to delete them from history.

Your history will be rewritten locally. If you attempt to push this change, it will be a non fast-forward update.

Revert, preserving history (non-destructive)

IF you prefer to keep the history, you can revert a sequence of commits:

git checkout master
git revert c460070..a3cb10e

This will create 7 new commits, each reverting the changes in these unwanted commits, in order.

Upvotes: 24

Related Questions