Learner
Learner

Reputation: 1315

git remove commits in a new branch which was accidently created from branch other than master

I created a new branch from master and named it 'LoginFeature'. I completed all the work in this branch and then pushed it back to LoginFeature. Then I created a new branch 'Dashboard' from 'LoginFeature' and merged Master into 'Dashboard'. I added few code files in 'Dashboard' and pushed them to my 'Dashboard' branch on server.

Next day, I realized that I should have created 'Dashboard' from 'Master' instead of 'LoginFeature'.

How can I fix this? Can I remove all the commits of 'LoginFeature' branch from 'Dashboard' branch. Or should I delete 'Dashboard' branch from local and remote and recreate 'Dashboard' branch from master and copy paste my new files in to this branch?

Upvotes: 0

Views: 47

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522635

Let's start with a branch diagram:

master:        A -- B -- C
                     \
LoginFeature:         D -- E
                            \
Dashboard:                   F -- G

You want to obtain this structure:

LoginFeature:         D -- E
                     /
master:        A -- B -- C
                          \
Dashboard:                 F' -- G'

We can try using git rebase --onto here:

# from your Dashboard branch
git checkout Dashboard
git rebase --onto C E

This says to rebase the Dashboard branch by rewriting history such that the commit whose parent is E (which is F in the above diagram) now sits on a new commit/base of C. Here C is the latest commit on the master branch.

Note that I labelled the F' and G' commits after the rebase with dashes. This is to indicate that these commits are actually completely new commits. Rebasing commits generally means rewriting them.

Also, your actual Dashboard branch has a merge commit coming from master. But, rebase by default will ignore merge commits, so this should be dropped during to rebase onto process.

Upvotes: 1

Babru
Babru

Reputation: 21

  1. Delete the Dashboard branch and recreate it from Master branch. Add all files again and push them.
  2. You can change the parent for the branch Dashboard. Since commit SHAs involve their parents, when you change the parent of a given commit, its SHA will change and it will create confusion for other users. For this you have to use rebase:
git rebase --onto `new_parent` `old_parent`

Upvotes: 1

Related Questions