raza.sayed
raza.sayed

Reputation: 549

Shifting all code from master to a new branch and removing the code from master

I have my code in the master branch of my project. I want the code in a separate branch and none of it in the master. I can create a new branch off master. But after creating the branch is it possible to remove all code from the master in such a way that if i later rebase or merge my new branch into master it wont cause any problems ?

Thank You

Upvotes: 2

Views: 2044

Answers (1)

Jonas Schäfer
Jonas Schäfer

Reputation: 20718

This is a bit tricky and you cannot do it properly if others already have copies of your commits. I.e. if you pushed your master branch to a remote repository other people are using or if people directly pulled from your repository, there is no clean way to get rid of this.

You have to rewrite the history of the master branch. There are two cases we have to look at here. From your question, I assume that in master, there is a commit which has been created before any of the code commits you want to remove from master. Let the ID of that commit be rootcommit. Skip step 1 and 2 if you already have a new branch for your code, branched off master.

  1. git checkout master: make sure you are in master.
  2. git checkout -b my-fancy-new-branch: create your new feature branch.
  3. git checkout master: switch back to master
  4. git reset --hard rootcommit: reset master to the state before your own commits.
  5. optional and if you have a remote you pull from: git pull --ff (if this fails because the pull is not fast-forward, you have to reconsider rootcommit. It contains some of your work)

In fact, this should even work if you pulled from any remote while working on your code. If you want to have your commits on top of the commits from the remote, you can rebase your new branch on the remote changes:

git checkout my-fancy-new-branch
git rebase master

To apply these changes to the remote, which is possible, but a huge hassle, you have to do a force-push on master now. Everyone having a clone of that repository, has to take special care now when pulling, because the history of master has changed. They must do essentially the same steps as you did, then pull and then reapply their local changes, if any. To do the force push, you have to execute:

git checkout master
git push --force

As said, force pushs are really evil and you probably should avoid it. If you can, just leave the commits in the history and do it better next time.

Upvotes: 3

Related Questions