Typical situation:
feature-branchmain moves forward (colleagues push)main2 possible strategies:
mkdir demo-merge && cd demo-merge && git init
# Common base
echo "print('app v1')" > app.py
git add . && git commit -m "Initial version"
# Feature branch
git checkout -b feature-login
echo "print('login system')" > login.py
git add . && git commit -m "Add login"
echo "print('login v2')" > login.py
git add . && git commit -m "Improve login"
# Main moves forward in the meantime
git checkout main
echo "print('app v1.1')" > app.py
git add . && git commit -m "Update main app"git merge feature-login* Merge branch 'feature-login'
|\
| * Improve login
| * Add login
* | Update main app
|/
* Version initialeHistory: Clearly shows that there were 2 parallel lines of development.
mkdir demo-rebase && cd demo-rebase && git init
# Same setup as before...
echo "print('app v1')" > app.py
git add . && git commit -m "Initial version"
git checkout -b feature-login
echo "print('login system')" > login.py
git add . && git commit -m "Add login"
echo "print('login v2')" > login.py
git add . && git commit -m "Improve login"
git checkout main
echo "print('app v1.1')" > app.py
git add . && git commit -m "Update main app"git checkout feature-login
git rebase main # "Moves" your commits after main
git checkout main
git merge feature-login # Fast-forward merge* Improve login
* Add login
* Update main app
* Version initialeHistory: Linear, as if you had developed after the main updates.
| Aspect | MERGE | REBASE |
|---|---|---|
| History | Shows parallel branches | Linear, clean |
| Merge commit | Yes, created automatically | No, fast-forward |
| Complexity | Simple | More complex |
| Conflicts | Resolve once | Possibly several times |
| Traceability | See when the feature was created/merged | As if developed sequentially |
MERGE:
A---B---C main
/ \
D---E---F---G feature (merge commit G)REBASE:
A---B---C---D'---E'---F' main (commits D,E,F "moved")Command:
git checkout main
git merge feature-branchCommand:
git checkout feature-branch
git rebase main
git checkout main
git merge feature-branch # Fast-forwardNEVER rebase commits that are already shared/pushed!
Both work. The important thing = consistency in the team!