Create a branch from master with removed code

71 views Asked by At

I wrote some code to implement two new features on a project, but I committed the changes to master. I now realize that this was a mistake, because one of the features is working well, and the other is not.

I would like to keep the working feature code in master, but remove the non-working feature code from master.

I'd like to have the current version of the project (with both features) in a new branch.

I would just create a new branch from master and then remove the code from the non-working feature from master, but I'm worried that the commits will basically be in the wrong order, and when I merge the branch back into master at some point, git will just discard the code for the non-working feature because the new branch will have been behind commits that remove that code.

Is there a better way to do this?

1

There are 1 answers

1
Anshul Goyal On BEST ANSWER

First, you should save your current master branch as a development branch, using

git checkout -b development

Next, you need to restore your master (because master is not for development, consider it sacrosanct unless you are the sole developer and you know what you are doing).

git branch -D master && git checkout -b master --track origin/master

If you don't have an upstream origin repository (github/bitbucket/gitlab etc), you can use git reset HEAD instead, or you can use git checkout -b master <SHA_of_last_sane_commit_on_master>.

Now, create a fresh branch for feature 1 out of master, and cherry pick commits for feature 1 to this branch, using

git checkout -b feature_1
git cherry-pick SHA_of_first_commit_for_feature_1
git cherry-pick SHA_of_second_commit_for_feature_1
# and so on.

Next, create a fresh branch for feature 2 in the same manner as above.

This assumes that your commits do not overlap for the 2 features, if they do, you will have to manually change contents of the files.

Now, when merging, all you need to do is merge feature_1 into master, then feature_2 into master.