Git Branches and Merges β The Basics of Collaboration
After completing this topic, you will:
Understand why branches are necessary, how to create and merge them, and how to resolve conflicts.
What if there were no branches?
Three team members are simultaneously modifying the same code. A creates a login, B creates a payment, and C fixes a bug. Every time they merge, conflicts arise, and it becomes difficult to track who changed what.
A branch is an independent workspace for code. Each person works on their own branch and merges it when finished.
Creating and switching branches
# Check the list of branchesgit branch
# Create a new branchgit branch feature/login
# Switch to the branchgit checkout feature/login
# Create and switch at the same timegit checkout -b feature/loginmain (or master) is the default branch. When creating new features, branch off and merge into main when finished.
Working and committing
# Work on the feature/login branchgit add login.jsgit commit -m "feat: add login form"
git add auth.jsgit commit -m "feat: add authentication logic"These commits only exist in the feature/login branch. They do not affect the main branch.
Merge: Combining
# Go back to maingit checkout main
# Merge feature/login into maingit merge feature/loginThe commits from feature/login are merged into main. If there are no conflicts, it completes automatically.
Resolving conflicts
If the same part of the same file has been modified in two branches, a conflict occurs:
<<<<<<< HEAD
const greeting = "Hello";
=======
const greeting = "Hi";
>>>>>>> feature/loginCheck the content between <<<<<<< and >>>>>>> and keep only the desired code:
const greeting = "Hi";After modifying, commit:
git add greeting.jsgit commit -m "fix: resolve merge conflict"Pull Request (PR)
In practice, git merge is not done directly in the local environment. It is merged through a Pull Request.
- Work on a branch and push
- Create a PR on GitHub/GitLab
- Team members review the code
- If approved, merge
A PR is a request to merge the code into main. Because it goes through a code review, bugs are reduced, and team members can understand the code changes.
Branch naming conventions
feature/login β New feature
fix/cart-bug β Bug fix
refactor/auth β Refactoring
docs/readme-update β DocumentationThe type/description format is common. Each team may have different rules, so follow the rules of the project.
Key takeaways
Branches are independent workspaces for code, and are merged when finished. If the same part is modified, a conflict occurs, and it must be resolved manually. In practice, code is merged through a Pull Request after a code review.