Add feature branches to break up master

I recently started working on an abandonned project that i started when i did not know much about git, and the result is a lot of commits in the master Branch, which should have been created on release/feature Branches. So i thought about restructuring the Repo.

I tried moving commits to other branches but that left me with the problem that i still needed to somehow get the final commit to merge with the master, which i was clueless on how to do.

Is there a way to restructure the Repo into multiple developement branches and still have the releases in master without losing commits?

1 answer

  • answered 2020-10-21 23:12 Etienne Batise

    If I understand correctly, you want to re-write the history of the master branch.

    As a rule of thumb, it is generally a bad idea to rewrite the history of any branch that has been pushed to the remote (especially the master branch). It can lead to loosing other peoples contributions and break their local repo. More on that here.

    If multiple persons have been contributing to your repo (or if you have a lot of commits) I’d suggest accepting the past and start structuring your repo with release/feature branches now and call it a day.

    If you really want to have a clean commit history from the beginning, you need to rewrite the entire history without loosing any steps, here’s the thing I would to:

    1. Copy your repo elsewhere on your file system for backup.

    2. Using the Git Log, I would find every group of commits that would fit together in the same feature branch. I’d note the last commit hash and the related feature title.

    3. For each of those groups, I would create a feature branch

      1. Begin on master git checkout master
      2. Create and switch to the new feature branch get checkout -b <name of the feature>
      3. Remove all commit since the last on git reset --hard <the hash of the last commit of the feature>
    4. Now that you have a bunch of nice feature branches, you need to merge them into master. But first, you need to erase the all history of commits on master. You can do that by resetting the branch to the first commit it the git log: git reset --hard $(git rev-list --max-parents=0 HEAD)

    5. Finally, following the order in which the commits were added in the first place, you can do git merge <a feature branch> for every branch you have created in step 2. If you haven’t forgotten any commit and respected the order in which they appeared, you should not have any conflicts.