How to Replace the Main Branch in Git with a Single Commit from Another Branch

In Git, working with branches provides a great deal of flexibility in terms of experimental development, feature additions, and version control in general. Nevertheless, there may come times when you want to replace your main branch's content with that of an experimental branch and condense all the changes into a single commit. This tutorial offers a step-by-step guide on how to achieve this operation.

Let's assume you have two branches: "main" and "v2_unsquashed", with "v2_unsquashed" being the branch you'd like to morph into "main". The ultimate goal is to replace the content of the "main" branch with the content of "v2_unsquashed" while squashing all changes into a single new commit. You can follow these steps to achieve this:

  1. Check out to a new temporary branch based on "v2_unsquashed":

    git checkout v2_unsquashed
    git checkout -b temp
  2. Perform a soft reset of the "temp" branch to "main". This will make your "temp" branch identical to "main", but keep the working directory's changes from "v2_unsquashed".

    git reset --soft main
  3. Commit all the changes in the working directory. At this point, the differences between "main" and "v2_unsquashed" will be staged and ready for a new commit.

    git commit -m "Changes from v2_unsquashed"
  4. Switch back to the "main" branch and perform a hard reset to "temp" to replace "main"'s content with "temp"'s content:

    git checkout main
    git reset --hard temp
  5. Finally, push the updated "main" branch to the remote repository to reflect the changes:

    git push origin main

This operation effectively moves all changes between "main" and "v2_unsquashed" into a single new commit and then places this commit on top of "main". Thus, the "main" branch reflects the end result of "v2_unsquashed" as a neat, single new commit, effectively erasing detailed change history in "v2_unsquashed". As always, remember to backup important data before performing such potentially irreversible operations.



Updated: 2023-07-24 20:07