Branching and Merging
In a professional environment like CodeHarborHub, we never work directly on the "Live" code (the main branch). Instead, we use Branches.
A branch is essentially a Parallel Universe. You can build a new feature, experiment with a new design, or fix a bug in a separate space without affecting the main project.
The Branching Workflowโ
Imagine you are building a website. The main branch is the version users see. You want to add a "Dark Mode."
- Create a Branch: You step into a parallel universe called
feat-dark-mode. - Work: You write your CSS and JS. The
mainbranch remains untouched and stable. - Merge: Once the dark mode is perfect, you bring those changes back into the
mainuniverse.
Step 1: Creating and Switchingโ
You can create a branch and move into it using these commands:
- The 2-Step Way
- The Pro Way (1-Step)
# Create the branch
git branch feat-dark-mode
# Switch to the branch
git checkout feat-dark-mode
# Create and switch immediately
git checkout -b feat-dark-mode
Step 2: Merging Changesโ
Once your work in the branch is finished and committed, itโs time to merge it back to the main branch. Hereโs how you do it:
1. Switch back to the destination (Main):
git checkout main
2. Pull the changes in:
git merge feat-dark-mode
3. Cleanup (Optional):
Since the feature is now part of main, you can delete the temporary branch:
git branch -d feat-dark-mode
The Logic of Mergingโ
Handling Merge Conflictsโ
Sometimes, Git gets confused. If you changed line 10 in main and your friend changed line 10 in feat-dark-mode, Git won't know which one to keep. This is a Merge Conflict.
How to fix it:
- Open the file in VS Code.
- You will see markers:
<<<<<<< HEAD(Your version) and>>>>>>> branch-name(Their version). - Delete the version you don't want and remove the markers.
git addthe file andgit committo finish the merge.
Industrial Best Practicesโ
| Rule | Why? |
|---|---|
| Descriptive Names | Use feat/login-ui or fix/header-logo so others know what the branch is for. |
| Keep Branches Small | Don't build five features in one branch. One branch = One task. |
| Pull Before Merge | Always run git pull origin main before merging to ensure you have the latest team updates. |
Not sure what branch you are on? Run git branch. The one with the asterisk (*) and highlighted in green is your current "Parallel Universe."