DEV Community

AnhChienVu
AnhChienVu

Posted on

Good practice for Merge in Git

Safe Merge Strategies:

I am learning about merging in Git, and there are 2 good practices that can help you (if you are also new dev as me) to minimize the chances of messing up with your git history.

  1. Test Merge from Main Branch: When you're working on the main branch and want to merge a feature branch, but want to avoid any risk of disrupting the main branch, you can create a test merge branch. This branch will have an identical state as main, essentially functioning as a clone. You can then perform your merge and any necessary testing on this new branch. If something goes wrong, the original main branch remains untouched, and the test branch can be safely deleted.

  2. Cross-Branch Merging for Collaborative Work: When multiple developers are working on separate branches (e.g., backend and frontend), and you want to verify if the code from both branches integrates correctly, you can create a test branch in your own working branch (e.g., you are working on back-end branch in this case). For instance, create a branch named test-frontend , where you merge the frontend branch to see if the code works as expected. If the merge is successful and you want to integrate with main, remain on the test-frontend branch and merge it with main. Once everything is verified, return to the main branch and perform a fast-forward merge with test-frontend branch. This approach reduces the risk of introducing issues into the main branch while ensuring smooth integration.

After merging into the main branch, Git will create a merge commit that has two parent commits: one from the existing main branch and the other from the test branch. If you later decide to undo the merge, you can easily reset the main branch to its state before the merge by running the command:

git checkout -B origin/main
Enter fullscreen mode Exit fullscreen mode

This command resets the main branch to match the state of origin/main (the commit where the remote main branch currently points). The reason it's origin/main is because, in Git, branches are local by default. If you haven't pushed your changes, they remain on your local machine. The origin/main reference points to the last known commit on the remote main branch, allowing you to safely revert to that state.

Top comments (0)