justzach
justzach

Reputation: 149

Git: How do I remove a branch that has already been committed, pushed, and merged into master?

I have a branch that has been committed, pushed, and merged into master. It did not pass QA. We need to pull that branch out of master for a release. How do I pull that branch out of master. Assume the branch name is "to-be-removed"

Upvotes: 1

Views: 62

Answers (2)

Pigueiras
Pigueiras

Reputation: 19356

You should have a history like this:

A--B--C---D--E      <-- Master
 \       /
  Z--Y--X          <-- Your feature

And you want to remove the commit D from the master branch. You only need to revert this commit. There is a git command to this:

git revert -m 1 [sha_of_D]

where -m mean the parent number of the commit.

It will create a new commit in master undoing the changes done by your feature branch. For more information, you can go to the main source.

Upvotes: 2

Matt Wagner
Matt Wagner

Reputation: 920

As per this post

If, on the other hand, you want to really get rid of everything you've done since then, there are two possibilities. One, if you haven't published any of these commits, simply reset:

# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32

# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts, if you've modified things which were
# changed since the commit you reset to

On the other hand, if you've published the work, you probably don't want to reset the branch, since that's effectively rewriting history. In that case, you could indeed revert the commits. With git, revert has a very specific meaning: create a commit with the reverse patch to cancel it out. This way you don't rewrite any history.

# This will create three separate revert commits:
git revert 0766c053 25eee4ca a867b4af

# It also takes ranges. This will revert the last two commits:
git revert HEAD~2..HEAD

# To get just one, you could use `rebase -i` to squash them afterwards
# Or, you could do it manually (be sure to do this at top level of the repo)
# get your index and work tree into the desired state, without changing HEAD:
git checkout 0d1d7fc32 .
# and then commit
git commit    # be sure and write a good message describing what you just did

Upvotes: 0

Related Questions