Jason M
Jason M

Reputation: 179

git rebase with the last commit on the branch

I have a git branch that has many commits and that was being merged with master regularly to resolve merge conflicts.

I wanted to rebase and did: git rebase master while on the branch, let's call it test_branch

but in order to rebase I have to resolve merge conflict on every commit.

Also when I git log I see mix of commit from master and test_branch and don't know how to squash properly

Is there a way I can remove all the commits on the branch, except the last one? And then rebasing it won't be even necessary

Edit: there is an open Pull Request on github, which ideally should be merged

Upvotes: 3

Views: 1938

Answers (2)

Enrico Campidoglio
Enrico Campidoglio

Reputation: 60013

Is there a way I can remove all the commits on the branch, except the last one?

Yes, more than one way, actually. Let's say that the history of your repo looks like this:

o---A---o---o (master)
     \       \
      B---C---M---D (test_branch)

An easy way to achieve what you want is to reset test_branch to the fork point A while keeping all the changes in the working directory:

git switch test_branch
git reset $(git merge-base --fork-point master test_branch)

All the changes that were made in test_branch are now going to be in your working directory. At this point, you can simply make a new commit:

o---A---o---o (master)
     \
      E (test_branch)

Since you mentioned that you have a pull request open, you'll have to force push test_branch in order to update it on the remote:

git push -f

Note that commit E is also going to contain the changes that had come from the merges with master (M in our example). Depending on how you resolved those conflicts, you should be prepared to resolve more conflicts once you merge test_branch into master.

Upvotes: 4

Romain Valeri
Romain Valeri

Reputation: 22067

One way to "fix" your PR if you need to keep it :
(starting with your test_branch checked out locally)

# make a backup
git branch backup_test_branch

# restart your branch from a clean master
git fetch
git reset --hard origin/master

# get the needed commit on it
# here <hash> is the "last commit" you refered to
git cherry-pick <hash>

# if conflicts arise at this point, resolve them as usual.

# replace remote history of your branch (we have a backup, remember)
git push -f

Then refresh the PR to see your lone cherry-picked commit ready to be merged on master.

(Note : at the cherry-pick step, if the commit you want is indeed the last on the branch, just do git cherry-pick test_branch)

Upvotes: 2

Related Questions