devHọc Dev
EN
Bài học

Tuần 1 - Ngày 3: Workflow Models, Pull Request/Interactive Rebase và Conflict nâng cao

Tuần 1 – Ngày 3

Bài này gộp 3 chủ đề: Workflow Models — Chọn Chiến Lược Đúng Cho Team, Pull Request, Code Review và Interactive Rebase, Conflict Resolution Nâng Cao.

Mục tiêu học tập

  • Hiểu Git Flow, GitHub Flow, GitLab Flow, Trunk-based Development
  • Biết khi nào chọn workflow nào dựa trên team size và release cadence
  • So sánh trade-off của từng workflow
  • Hiểu văn hóa Pull Request (PR) và best practices code review
  • Thực hành git rebase -i (interactive rebase): squash, fixup, edit, reword
  • Dùng --fixup và --autosquash workflow
  • Tạo atomic PR dễ review
  • Xử lý conflict trong large merge
  • Hiểu semantic conflicts (nguy hiểm nhất)
  • Sử dụng git mergetool (kdiff3, VS Code)
  • Cấu hình và dùng git rerere để tái dùng conflict resolution
  • Chiến lược --no-ff trong team workflows

Phần 1: Workflow Models — Chọn Chiến Lược Đúng Cho Team

1. Tại sao cần chọn workflow?

Git cho phép làm nhiều thứ, nhưng team cần đồng thuận về một workflow. Không có workflow duy nhất đúng — mỗi cái tối ưu cho context khác nhau.

Câu hỏi cần trả lời khi chọn:
1. Release cadence: release nhiều lần/ngày hay mỗi vài tuần?
2. Team size: 2 người hay 50 người?
3. Versioning: hỗ trợ multiple versions song song không?
4. CI/CD maturity: tự động test và deploy không?
5. Hotfix policy: có cần fix nhanh prod không cần deploy toàn bộ?

2. Git Flow (Vincent Driessen, 2010)

Cấu trúc branches

main────●────────────────────────●────│▲hotfix/────┤────●───────────────────┤────│▲(mergetomain│││+develop)│develop────●───●────────────────────●────│▲▲▲│release/────┤││●──────┤│││▲│feature/────┤│●────────┘│(nhiềubranch)└───┘

Các branches chính

BranchVai tròTồn tại
mainProduction code, luôn deployableVĩnh viễn
developIntegration branch, next releaseVĩnh viễn
feature/*Tính năng mớiTạm thời
release/*Chuẩn bị release, chỉ bugfixTạm thời
hotfix/*Fix khẩn cấp trên productionTạm thời

Lifecycle Git Flow

# Feature development
git switch develop
git switch -c feature/user-notifications
# ... làm việc ...
git switch develop
git merge --no-ff feature/user-notifications
git branch -d feature/user-notifications

# Chuẩn bị release
git switch develop
git switch -c release/1.4.0
# Chỉ bugfix trong release branch, KHÔNG thêm feature mới
git switch main
git merge --no-ff release/1.4.0
git tag -a v1.4.0 -m "Release version 1.4.0"
git switch develop
git merge --no-ff release/1.4.0   # merge bugfix về develop
git branch -d release/1.4.0

# Hotfix trên production
git switch main
git switch -c hotfix/payment-null-deref
# ... fix ...
git switch main
git merge --no-ff hotfix/payment-null-deref
git tag -a v1.4.1
git switch develop
git merge --no-ff hotfix/payment-null-deref   # đừng quên merge vào develop
git branch -d hotfix/payment-null-deref

Khi nào dùng Git Flow

Phù hợp:
✓ Release theo lịch (mỗi sprint, mỗi tháng)
✓ Hỗ trợ nhiều version song song (v1.x, v2.x)
✓ Desktop apps, mobile apps, thư viện (lib/SDK)
✓ Team lớn cần quản lý chặt

Không phù hợp:
✗ Web apps deploy liên tục (CD)
✗ Team nhỏ (<5 người) — quá nhiều overhead
✗ Startup cần move fast

3. GitHub Flow (GitHub, 2011)

Workflow đơn giản hơn rất nhiều. Chỉ có main và feature branches.

Nguyên tắc cốt lõi

1. main luôn deployable
2. Mọi thứ đều làm trên branch riêng
3. Push thường xuyên, mở PR sớm
4. Review trên PR
5. Deploy từ branch (test) trước khi merge
6. Merge vào main → deploy production ngay

Lifecycle GitHub Flow

main────●──────────────────────────●────│▲feat/x└──●──●──●──●──────────────┘PRreview+CIpassdeploybranch→stagingapprove→mergetomainauto-deploytoproduction
# Full GitHub Flow cycle
git switch main && git pull
git switch -c feature/search-autocomplete

# ... làm việc, commit nhiều lần ...
git push -u origin feature/search-autocomplete

# Mở PR trên GitHub → review → CI chạy
# Deploy feature branch lên staging để test

# Sau khi approve
# → Merge PR (squash hoặc merge commit)
# → Tự động deploy main lên production

# Dọn dẹp local
git switch main && git pull
git branch -d feature/search-autocomplete

Khi nào dùng GitHub Flow

Phù hợp:
✓ Web apps với Continuous Deployment
✓ Team nhỏ đến vừa (2-20 người)
✓ Startup, SaaS
✓ Khi main luôn reflect production

Không phù hợp:
✗ Cần maintain multiple versions
✗ Release có cửa sổ deployment (maintenance window)
✗ Regulatory compliance yêu cầu cần test giai đoạn dài

4. GitLab Flow

GitLab Flow là middle ground: đơn giản như GitHub Flow nhưng có thêm environment branches.

Với environment branches

main────●──────────────────────●────│▲feature/└──●──●──●─────────────┘▲Mergetomaintriggersdeploytostagingstaging────────●──────────────────●──▲Manualpromoteproduction─────────────────────────●──

Với release branches (khi cần versioning)

# Không có separate develop branch
# Feature → main → cherry-pick hoặc merge sang release branches

# Tạo release branch khi cần
git switch main
git switch -c release/2.3

# Hotfix: fix trên main trước
git switch main
git commit -m "fix: critical security patch"

# Backport sang release
git switch release/2.3
git cherry-pick <hash-of-fix>

5. Trunk-Based Development (TBD)

Tất cả mọi người commit thẳng lên main (trunk), thay vì dùng long-lived branches.

Hai biến thể

Biếnthể1:Committhẳngvàotrunk(teamrấtnhỏ,CImạnh)A──B──C──D──E──F←main/trunk^Dev1^Dev2^Dev1^Dev2Biếnthể2:Short-livedfeaturebranches(<2ngàytồntại)main────●──────●──────●────────●────│▲│▲feat/a└──●────┘│feat/b└────●───┘

Yêu cầu để TBD hoạt động

Bắt buộc:
✓ Feature flags (feature toggles) — tắt incomplete features ở production
✓ CI/CD rất mạnh: test chạy < 10 phút, pass → auto deploy
✓ Pair programming hoặc code review nhanh
✓ Branches sống < 1-2 ngày

Kỹ thuật hỗ trợ:
- Branch by abstraction (refactor lớn mà không lock branch)
- Strangler fig pattern (migrate dần)
# Feature flag pattern với TBD
// config/features.ts
export const FEATURES = {
  newSearchAlgorithm: process.env.FEATURE_NEW_SEARCH === 'true',
  betaPaymentFlow: process.env.FEATURE_BETA_PAYMENT === 'true',
};

// Trong code
if (FEATURES.newSearchAlgorithm) {
  return searchV2(query);   // code incomplete, disabled by flag
}
return searchV1(query);     // luôn chạy ở production

Khi nào dùng TBD

Phù hợp:
✓ Google, Facebook, Netflix scale (CI/CD mature)
✓ Team có experience cao
✓ Microservices với independent deploy
✓ Web services deploy nhiều lần/ngày

Không phù hợp:
✗ Team chưa có CI/CD tốt
✗ Outsourced development với contributors chất lượng không đều
✗ Cần maintain multiple versions

6. So sánh tổng hợp

Tiêu chíGit FlowGitHub FlowGitLab FlowTrunk-Based
Độ phức tạpCaoThấpTrung bìnhThấp–Trung
Long-lived branchesdevelop, release, hotfixKhôngstaging, productionKhông
Release cadenceTheo lịchLiên tụcLinh hoạtLiên tục
VersioningTốtKémTốtFeature flags
Team size phù hợpLớnNhỏ-VừaMọi kích thướcCó kinh nghiệm
CI/CD yêu cầuThấpTrung bìnhTrung bìnhCao

Decision tree nhanh

Deployliêntụcmỗingày?├──Có→TeamcóCI/CDtốt?│├──Có,teamnhỏ→GitHubFlowhoặcTBD│└──Có,cầnenvironmentgates→GitLabFlow└──Không(releasetheolịch)?├──Cầnmulti-versionsupport→GitFlow└──Singleversion,releasenhanh→GitHubFlow+releasetags

Phần 2: Pull Request, Code Review và Interactive Rebase

1. Pull Request — Hơn cả merge request

PR (hoặc MR trong GitLab) là cơ chế đề xuất merge code. Nó không chỉ là kỹ thuật — mà là giao tiếp.

Anatomy của một PR tốt

Title: feat(auth): add JWT refresh token endpoint

Description:
## Vấn đề
Token hết hạn sau 1 giờ khiến user bị logout đột ngột.

## Giải pháp
Thêm endpoint POST /auth/refresh nhận refresh token,
trả về access token mới. Refresh token có TTL 7 ngày.

## Thay đổi
- src/auth/refresh.ts: new endpoint
- src/auth/middleware.ts: update token validation
- tests/auth.test.ts: add tests

## Test
- [ ] Unit tests pass (npm test)
- [ ] Manual test: login → wait > 1h → request với expired token
       → gọi /auth/refresh → nhận token mới → request lại thành công
- [ ] Test case: expired refresh token → 401

## Screenshots (nếu có UI change)

Closes #123

Atomic PR — Nguyên tắc số 1

Mỗi PR nên:

  • Giải quyết một vấn đề hoặc một feature
  • Reviewer có thể review trong < 30 phút
  • Có thể deploy độc lập (không phụ thuộc PR khác chưa merge)
BAD — một PR quá lớn:
"feat: redesign entire user module"
  → 50 files changed, 2000 lines

GOOD — chia nhỏ:
PR 1: "feat(user): add avatar upload endpoint"
PR 2: "feat(user): update profile page to show avatar"
PR 3: "feat(user): add avatar crop UI"

2. Code Review — Văn hóa

Reviewer: Tư duy khi review

Hỏi, không phán xét:
BAD:  "Code này sai"
GOOD: "Tôi hiểu mục đích này, nhưng với edge case X thì sao?"

Suggest, không command:
BAD:  "Đổi sang for loop"
GOOD: "Có thể dùng .map() ở đây không? Trông idiomatic hơn — nit"

Label severity:
[blocker]: Security issue, logic bug — must fix
[major]:   Code quality, maintainability — should fix
[minor]:   Style, naming — nice to have
[nit]:     Nitpick — author's call
[question]: Tôi không hiểu, giải thích giúp

Approve khi:
- Không có blocker/major chưa resolved
- Code làm đúng điều PR title nói

Author: Mindset khi nhận review

- Comment là về code, không phải về bạn
- Giải thích lý do (trong comment hoặc commit message) khi không đồng ý
- Không defensive — reviewer thường thấy điều mình bỏ sót
- Đánh dấu "resolved" khi đã sửa hoặc đã giải thích

3. Interactive Rebase — Dọn dẹp lịch sử

git rebase -i (interactive) cho phép chỉnh sửa, kết hợp, xoá, đổi thứ tự commits trước khi push hoặc tạo PR.

Cú pháp cơ bản

# Rebase interactive N commits gần nhất
git rebase -i HEAD~3    # chỉnh 3 commits gần nhất
git rebase -i HEAD~5    # chỉnh 5 commits gần nhất

# Rebase từ điểm phân kỳ với main
git rebase -i main

Editor mở ra

# Sau git rebase -i HEAD~4, editor hiển thị:
pick abc1234 feat: add login form
pick def5678 fix: typo in button text
pick 9a8b7c6 WIP: still working on validation
pick 1f2e3d4 feat: complete login validation

# Commands:
# p, pick = dùng commit này
# r, reword = dùng commit nhưng đổi message
# e, edit = dùng commit nhưng dừng để amend
# s, squash = kết hợp vào commit trước, giữ message
# f, fixup = kết hợp vào commit trước, bỏ message này
# d, drop = xoá commit này
# Thứ tự từ trên xuống = từ cũ đến mới

Các thao tác phổ biến

squash — Kết hợp commits, merge messages
Trước:
pick abc1234 feat: add login form
squash def5678 fix: typo in button text
squash 9a8b7c6 WIP: still working
pick 1f2e3d4 feat: complete validation

→ Git kết hợp abc+def+9a8 thành một commit
→ Mở editor để bạn viết message mới
fixup — Kết hợp commits, bỏ message phụ
pick abc1234 feat: add login form
fixup def5678 fix: typo in button text    ← bỏ message này
fixup 9a8b7c6 WIP                         ← bỏ message này

→ Một commit duy nhất với message "feat: add login form"
reword — Chỉ đổi commit message
reword abc1234 feat: add login form    ← đổi message
pick def5678 feat: add logout

→ Git dừng tại abc1234, mở editor để đổi message
→ Tiếp tục rebase tự động
drop — Xoá commit
pick abc1234 feat: add feature A
drop def5678 WIP: debug logging       ← xoá hẳn
pick 9a8b7c6 feat: add feature B

→ commit def5678 không tồn tại trong lịch sử nữa
edit — Tách một commit thành nhiều commits
# Trong editor
edit abc1234 feat: add authentication and authorization

# Git dừng tại commit đó
git reset HEAD~1    # unstage nhưng giữ file changes

# Giờ bạn có 2 nhóm thay đổi trong working dir
git add src/auth/login.ts
git commit -m "feat(auth): add login logic"

git add src/auth/rbac.ts
git commit -m "feat(auth): add role-based access control"

git rebase --continue   # tiếp tục rebase

4. --fixup và --autosquash Workflow

Đây là workflow rất hiệu quả: thay vì rebase -i thủ công, bạn tạo fixup commits và --autosquash tự sắp xếp.

# Lịch sử hiện tại:
git log --oneline
# abc1234 feat: add login form
# def5678 feat: add user profile page

# Phát hiện typo trong login form, tạo fixup commit
git add src/auth/login.ts
git commit --fixup abc1234
# → Tự tạo message "fixup! feat: add login form"

# Thêm một sửa nữa cho profile
git add src/profile/profile.tsx
git commit --fixup def5678

# Xem lịch sử giờ:
git log --oneline
# 7g8h9i0 fixup! feat: add user profile page
# 5e6f7g8 fixup! feat: add login form
# def5678 feat: add user profile page
# abc1234 feat: add login form

# Autosquash: tự động sắp xếp và squash fixup commits
git rebase -i --autosquash main
# Editor mở ra với thứ tự đã được sắp xếp:
# pick abc1234 feat: add login form
# fixup 5e6f7g8 fixup! feat: add login form
# pick def5678 feat: add user profile page
# fixup 7g8h9i0 fixup! feat: add user profile page

# Chấp nhận và rebase xong — lịch sử clean!
# Cấu hình autosquash mặc định (không cần gõ --autosquash mỗi lần)
git config --global rebase.autoSquash true

5. Workflow thực tế: Feature PR với clean history

# 1. Tạo feature branch từ main mới nhất
git switch main && git pull
git switch -c feature/user-notifications

# 2. Làm việc, commit freely (không cần perfect)
git commit -m "WIP: notification component"
git commit -m "feat: add notification bell"
git commit -m "fix: typo"
git commit -m "feat: add notification count badge"
git commit -m "WIP: still need to handle click"
git commit -m "feat: complete notification dropdown"
git commit -m "test: add tests for notification"

# 3. Trước khi tạo PR, dọn dẹp lịch sử
git rebase -i main
# Squash WIP commits vào commit liên quan
# Kết quả mong muốn:
# pick a1 feat: add notification component with bell and badge
# pick a2 feat: add notification dropdown with click handler
# pick a3 test: add tests for notification component

# 4. Push (force-with-lease vì đã rebase)
git push -u origin feature/user-notifications
# Lần sau nếu có thêm fixup:
git push --force-with-lease

# 5. Tạo PR → Review → Merge

Phần 3: Conflict Resolution Nâng Cao

1. Loại Conflicts

Textual conflict — Git phát hiện được

Hai người sửa cùng dòng hoặc vùng gần nhau trong file.

<<<<<<< HEAD
const MAX_RETRY = 3;
=======
const MAX_RETRY = 5;
>>>>>>> feature/retry-policy

Git có thể phát hiện và báo cáo — bạn chỉ cần resolve thủ công.

Semantic conflict — Nguy hiểm nhất

Merge "clean" (không có textual conflict) nhưng logic bị sai.

// Developer A (main): đổi tên hàm
function processPayment(amount, currency) { ... }

// Developer B (feature/multi-currency): gọi hàm theo tên cũ
const result = processOrder(amount);    // TypeError at runtime!

Merge thành công, CI pass nếu test coverage thấp — nhưng production crash.

Cách phòng ngừa:

# Test toàn diện sau mỗi merge
npm test && npm run e2e

# TypeScript/static analysis phát hiện tên hàm sai
# Luôn chạy type-check trong CI:
tsc --noEmit

# Pair review: reviewer đọc kỹ logic, không chỉ diff

2. Xử lý Conflict trong Large Merge

Xem trước khi merge

# Xem files nào sẽ conflict trước khi merge
git merge --no-commit --no-ff feature/large-refactor
# nếu có conflict → git merge --abort để hủy
# nếu OK → git commit để hoàn thành

# Muốn xem conflict markers dạng diff3 (kèm cả bản gốc) cho file đang conflict:
git checkout --conflict=diff3 src/config.ts
# (bật diff3 mặc định: git config --global merge.conflictstyle diff3)

Chiến lược xử lý conflict lớn

# 1. Bắt đầu merge, git liệt kê files conflict
git merge feature/big-feature
# CONFLICT (content): Merge conflict in src/api/routes.ts
# CONFLICT (content): Merge conflict in src/models/user.ts
# CONFLICT (add/add): Merge conflict in src/utils/validators.ts

# 2. Xem danh sách tất cả files conflict
git diff --name-only --diff-filter=U

# 3. Resolve từng file một, bắt đầu từ file ít phụ thuộc nhất
git add src/utils/validators.ts    # đã resolve
git add src/models/user.ts         # đã resolve
# ... tiếp tục ...

# 4. Kiểm tra còn file nào chưa resolve
git status | grep "both modified"

# 5. Hoàn thành merge
git commit

# 6. QUAN TRỌNG: chạy tests ngay sau merge
npm test

Conflict markers 3-way (diff3 style)

# Bật conflict style diff3 — thấy được base chung
git config --global merge.conflictstyle diff3

# Output với diff3:
<<<<<<< HEAD
const timeout = 30000;
||||||| base     ← nội dung trước cả 2 branch thay đổi
const timeout = 20000;
=======
const timeout = 60000;
>>>>>>> feature/auth

# Hiểu context: base=20000, HEAD tăng lên 30000, feature tăng lên 60000
# Quyết định: có thể cần cả hai → 90000? hay chỉ lấy feature = 60000?

3. git mergetool — Visual Conflict Resolution

# Chạy mergetool (mở editor được cấu hình)
git mergetool

# Hoặc cho một file cụ thể
git mergetool src/api/routes.ts

Cấu hình VS Code làm mergetool

git config --global merge.tool vscode
git config --global mergetool.vscode.cmd 'code --wait $MERGED'

# Hoặc dùng VS Code built-in merge editor (Git 2.34+)
# VS Code tự động detect conflict và show 3-way merge editor

Cấu hình vimdiff

git config --global merge.tool vimdiff
git config --global mergetool.vimdiff.layout "LOCAL,BASE,REMOTE/MERGED"
# LOCAL = HEAD (bên trái)
# BASE = ancestor chung
# REMOTE = branch đang merge
# MERGED = file output (bên dưới)

Các tool phổ biến khác

# Kdiff3 (GUI, cross-platform)
git config --global merge.tool kdiff3

# Meld (Linux, GUI)
git config --global merge.tool meld

# Beyond Compare (commercial, rất mạnh)
git config --global merge.tool bc

# IntelliJ/WebStorm tích hợp built-in merge tool

4. git rerere — Reuse Recorded Resolution

rerere = Reuse Recorded Resolution. Git ghi nhớ cách bạn resolve một conflict cụ thể và tự động áp dụng lại nếu conflict đó xuất hiện lần sau.

Khi nào rerere hữu ích?

Tình huống: Long-running feature branch, thường xuyên rebase với main.
Mỗi lần rebase lại gặp cùng conflict ở cùng file.

Không có rerere: Resolve thủ công mỗi lần → mất thời gian
Có rerere: Lần đầu resolve → Git ghi nhớ → lần sau tự apply

Cấu hình và sử dụng

# Bật rerere (resolutions được lưu tại .git/rr-cache/ trong mỗi repo)
git config --global rerere.enabled true

# Hoặc chỉ cho repo hiện tại
git config rerere.enabled true
# Workflow với rerere

# 1. Lần đầu gặp conflict
git rebase main
# CONFLICT: src/config.ts
# Recorded preimage for 'src/config.ts'
# → rerere ghi lại "hình ảnh" conflict lần đầu

# Resolve thủ công
vim src/config.ts   # edit file

# Stage file
git add src/config.ts
git rebase --continue
# → Git ghi lại: "conflict này" → "resolution này"

# 2. Lần sau rebase lại (sau khi main có thêm commits)
git rebase main
# CONFLICT: src/config.ts
# Resolved 'src/config.ts' using previous resolution.
# → Git tự động điền resolution đã ghi nhớ vào file
# (bật rerere.autoUpdate để Git tự stage luôn: "Staged 'src/config.ts' using previous resolution.")

# Kiểm tra rerere đã apply đúng chưa
git diff src/config.ts    # xem kết quả
git add src/config.ts
git rebase --continue
# Xem các resolution đã ghi nhớ
git rerere status

# Xem chi tiết một resolution
ls .git/rr-cache/

# Xoá bỏ tất cả rerere records (nếu cần reset)
git rerere forget src/config.ts

# Bật tự động stage sau khi rerere apply (cẩn thận — kiểm tra trước)
git config --global rerere.autoUpdate true

5. Chiến lược --no-ff trong Team Workflows

Tại sao --no-ff quan trọng trong Git Flow

# Không có --no-ff (fast-forward khi có thể):
# git log --graph:
# * abc1234 feat: add feature C (commit của feature branch)
# * def5678 feat: add feature B
# * 9ab1234 chore: init
# → Không thể biết "feature C" kết thúc ở commit nào, bắt đầu ở đâu

# Với --no-ff:
# *   merge-hash Merge branch 'feature/C' into main
# |\
# | * abc1234 feat: complete feature C
# | * xyz1234 feat: WIP feature C
# |/
# * def5678 feat: add feature B
# → Rõ ràng: feature C gồm 2 commits, merge tại điểm nào

Khi nào dùng --no-ff

# Git Flow: luôn --no-ff khi merge feature vào develop
git switch develop
git merge --no-ff feature/user-search
git branch -d feature/user-search

# GitHub Flow: thường squash merge (GitHub UI) hoặc merge commit
# → PR merge button: "Merge commit" vs "Squash and merge" vs "Rebase and merge"

# Squash merge: tất cả commits của feature thành 1 commit
# → Lịch sử main rất clean, nhưng mất detail của feature
# → Phù hợp cho team muốn main history = list of features

# Merge commit (--no-ff): giữ structure
# → Phù hợp cho audit trail, debugging chi tiết

6. Conflict Resolution Checklist

Trước khi bắt đầu merge lớn:
□ git status clean (no uncommitted changes)
□ git pull/rebase main mới nhất
□ Thông báo team: "Đang merge X, hold off on merging to main"

Trong khi resolve:
□ Hiểu context của cả hai thay đổi (đọc commit message)
□ Dùng diff3 style để thấy base
□ Test sau mỗi file resolve (không đợi hết tất cả)
□ Ghi chú lý do resolve theo hướng nào

Sau khi merge:
□ git status sạch (không còn conflict markers)
□ Build pass: npm run build
□ Test pass: npm test
□ Kiểm tra có semantic conflict không (logic review)
□ Push với PR để reviewer check lại

Câu hỏi ôn tập

  1. Git Flow có bao nhiêu loại long-lived branches? Nêu tên và vai trò của từng loại.

    Xem đáp án

    Git Flow có 2 long-lived branches: main (code production, luôn deployable, được tag version) và develop (integration branch, nơi feature branches merge vào, là source cho release branches). Ngoài ra còn 3 loại short-lived branches: feature/*, release/*, hotfix/*.

  2. Tại sao GitHub Flow yêu cầu main luôn phải deployable?

    Xem đáp án

    GitHub Flow không có develop/staging branch riêng — main là duy nhất và trực tiếp deploy production. Nếu main không deployable, bất kỳ hotfix nào cũng không thể deploy ngay. Yêu cầu này buộc team: (1) chỉ merge PR sau khi CI pass và code review approve, (2) deploy từ branch trước khi merge, (3) maintain culture of "always green main".

  3. Feature flags trong TBD giải quyết vấn đề gì mà branching không giải quyết được?

    Xem đáp án

    Feature flags cho phép deploy code của một feature chưa hoàn chỉnh lên production mà không bật cho users — code tồn tại trong codebase nhưng disabled. Branching không thể giải quyết được vì: long-lived feature branch cuối cùng phải merge, và càng để lâu càng nhiều conflict. Feature flags tách "deploy" khỏi "release" — team có thể deploy thường xuyên (TBD) mà không lo expose incomplete features.

  4. Startup SaaS với 5 developer, deploy 3 lần/ngày nên dùng workflow nào? Tại sao?

    Xem đáp án

    GitHub Flow là lựa chọn tốt nhất. Lý do: (1) Team nhỏ — không cần overhead của Git Flow (develop, release branches). (2) Deploy liên tục (CD) — GitHub Flow được thiết kế cho Continuous Deployment từ main. (3) Đơn giản — ít branches = ít cognitive overhead = move fast. (4) Nếu CI/CD đã trưởng thành hơn và team muốn, có thể migrate sang Trunk-based Development.

  5. Khi nào nên chọn GitLab Flow thay vì Git Flow?

    Xem đáp án

    GitLab Flow phù hợp khi: (1) Cần environment gates (staging → production), tức là code phải pass từng environment trước khi promote — không muốn deploy thẳng từ main như GitHub Flow. (2) Cần versioning/multi-version support nhưng Git Flow quá phức tạp. (3) Web app với deployment pipeline có nhiều bước nhưng vẫn muốn release cadence linh hoạt hơn Git Flow truyền thống.

  6. Atomic PR nghĩa là gì? Tại sao quan trọng?

    Xem đáp án

    Atomic PR giải quyết một vấn đề duy nhất, reviewer có thể review trong dưới 30 phút, và có thể deploy độc lập. Quan trọng vì: (1) reviewer dễ hiểu context, review chất lượng hơn, (2) nếu cần revert, chỉ revert một tính năng rõ ràng, (3) tránh bottleneck — PR nhỏ merge nhanh hơn, không block đồng nghiệp.

  7. Sự khác biệt giữa squash và fixup trong interactive rebase?

    Xem đáp án

    Cả hai đều kết hợp commit vào commit trước. Khác biệt: squash mở editor để bạn chỉnh sửa commit message kết hợp (merge cả hai message lại). fixup bỏ message của commit này và chỉ giữ message của commit trước — phù hợp khi commit là minor fix không cần giải thích riêng (ví dụ sửa typo).

  8. Lệnh git commit --fixup <hash> tạo ra commit với message như thế nào?

    Xem đáp án

    Tự động tạo message có format fixup! <message-của-commit-gốc>. Ví dụ commit gốc có message "feat: add login form" → fixup commit sẽ có message "fixup! feat: add login form". Git dùng prefix fixup! này để git rebase -i --autosquash tự động sắp xếp và squash đúng vị trí.

  9. Khi nào dùng reword thay vì squash trong interactive rebase?

    Xem đáp án

    Dùng reword khi muốn chỉ đổi commit message mà không thay đổi nội dung hay kết hợp với commit khác. Ví dụ: commit message có typo, hoặc cần thêm ticket ID, hoặc đổi từ WIP: ... thành message chuẩn Conventional Commits. squash kết hợp nội dung của nhiều commits; reword chỉ edit message của một commit duy nhất.

  10. Tại sao sau git rebase -i, bạn phải dùng --force-with-lease khi push?

Xem đáp án

Interactive rebase viết lại lịch sử — tất cả commits bị chỉnh sửa có hash mới. Remote branch vẫn có commits với hash cũ. Git từ chối push thường vì local history "phân kỳ" với remote. Cần force push để ghi đè remote. Dùng --force-with-lease (không phải --force) để đảm bảo không ghi đè commits của đồng nghiệp nếu họ push trong lúc bạn đang rebase.

  1. Tại sao semantic conflict nguy hiểm hơn textual conflict?
Xem đáp án

Textual conflict Git phát hiện và báo trực tiếp — bạn biết cần resolve. Semantic conflict là khi merge clean (không có conflict markers) nhưng logic bị sai: ví dụ Dev A đổi tên function, Dev B vẫn gọi tên cũ. Merge thành công, CI pass nếu test coverage thấp, nhưng production crash. Không có tool tự động phát hiện — chỉ code review kỹ lưỡng, TypeScript/static analysis, và integration tests mới bắt được.

  1. diff3 conflict style bổ sung thêm gì so với default?
Xem đáp án

diff3 (bật bằng git config --global merge.conflictstyle diff3) thêm một section thứ ba giữa ======= markers: ||||||| base — hiển thị nội dung trước khi cả hai branches thay đổi (ancestor chung). Điều này giúp hiểu context: bạn thấy giá trị gốc là gì, HEAD thay đổi thế nào, và feature branch thay đổi thế nào — dễ quyết định resolve hơn chỉ thấy 2 versions.

  1. git rerere giải quyết vấn đề gì trong long-running feature branches?
Xem đáp án

Long-running feature branches phải rebase thường xuyên với main. Nếu cùng một conflict xuất hiện nhiều lần (ví dụ file config bị cả hai branches sửa), bạn phải resolve thủ công mỗi lần rebase. rerere (Reuse Recorded Resolution) ghi nhớ cách bạn resolve lần đầu và tự động áp dụng lại những lần sau — tiết kiệm thời gian và tránh sai nhất quán.

  1. Sự khác biệt giữa merge commit (--no-ff) và squash merge?
Xem đáp án

Merge commit (--no-ff): giữ tất cả commits của feature branch trong lịch sử, tạo một merge commit với 2 parents — lịch sử có nhánh rẽ rõ ràng, audit trail đầy đủ. Squash merge: gộp tất cả commits của feature thành 1 commit duy nhất trên main — lịch sử main rất clean (mỗi entry = một feature), nhưng mất detail của quá trình phát triển feature. GitHub PR squash merge dùng cách này.

  1. Lệnh nào liệt kê tất cả files có conflict chưa resolve?
Xem đáp án

git diff --name-only --diff-filter=U (U = Unmerged). Hoặc git status | grep "both modified". Trong khi merge đang in-progress, git status cũng hiện "Unmerged paths" rõ ràng. Sau khi resolve từng file phải git add <file> để đánh dấu resolved trước khi git commit hoặc git rebase --continue.

Bài tập thực hành

Phần 1: Workflow Models — Chọn Chiến Lược Đúng Cho Team

# Mô phỏng Git Flow cho một feature nhỏ
mkdir workflow-lab && cd workflow-lab
git init -b main
git config user.name "Test" && git config user.email "test@test.com"

# Setup: tạo main và develop
echo "v1.0.0" > version.txt
git add . && git commit -m "chore: initial commit"
git switch -c develop
echo "develop" > develop.txt
git add . && git commit -m "chore: setup develop branch"

# Feature branch
git switch -c feature/user-search
echo "search feature" > search.js
git add . && git commit -m "feat: add user search"

# Merge về develop (--no-ff như Git Flow)
git switch develop
git merge --no-ff feature/user-search -m "feat: merge user search feature"
git branch -d feature/user-search

# Release branch
git switch -c release/1.1.0
echo "1.1.0" > version.txt
git add . && git commit -m "chore: bump version to 1.1.0"

# Merge vào main
git switch main
git merge --no-ff release/1.1.0 -m "release: version 1.1.0"
git tag -a v1.1.0 -m "Release 1.1.0"

# Merge về develop
git switch develop
git merge --no-ff release/1.1.0
git branch -d release/1.1.0

# Xem lịch sử
git log --oneline --graph --all

Phần 2: Pull Request, Code Review và Interactive Rebase

mkdir pr-rebase-lab && cd pr-rebase-lab
git init -b main
git config user.name "Test" && git config user.email "test@test.com"

# Setup
echo "app" > app.js && git add . && git commit -m "chore: init"
git switch -c feature/notifications

# Tạo "messy" commit history như thực tế
echo "// notification" > notification.js
git add . && git commit -m "WIP: start notifications"
echo "const bell = () => {}" >> notification.js
git add . && git commit -m "feat: add bell component"
echo "// typo fix" >> notification.js
git add . && git commit -m "fix typo"
echo "const badge = () => {}" >> notification.js
git add . && git commit -m "feat: add badge"
echo "const dropdown = () => {}" >> notification.js
git add . && git commit -m "WIP: dropdown"
echo "export { bell, badge, dropdown }" >> notification.js
git add . && git commit -m "feat: complete notification module"

git log --oneline
# 6 commits, messy

# Interactive rebase: squash WIP và fixups thành 2 clean commits
git rebase -i HEAD~6
# Cố gắng đạt:
# pick XXX feat: add notification bell and badge
# pick YYY feat: add notification dropdown and exports

git log --oneline
# → 2 commits gọn gàng

# Thực hành --fixup
echo "// additional comment" >> notification.js
git add . && git commit --fixup HEAD~1  # fixup cho commit TRƯỚC commit gần nhất (HEAD~1)

git log --oneline
# thấy "fixup! feat: ..."

git rebase -i --autosquash HEAD~3
# Xem autosquash tự sắp xếp thế nào

Phần 3: Conflict Resolution Nâng Cao

mkdir conflict-advanced-lab && cd conflict-advanced-lab
git init -b main
git config user.name "Test" && git config user.email "test@test.com"

# Bật rerere
git config rerere.enabled true
git config merge.conflictstyle diff3

# 1. Tạo conflict tái lặp (để test rerere)
echo "timeout: 30" > config.yml
git add . && git commit -m "chore: init config"

git switch -c feature/retry
echo "timeout: 60" > config.yml
git add . && git commit -m "feat: increase timeout"

git switch main
echo "timeout: 45" > config.yml
git add . && git commit -m "feat: medium timeout for main"

# 2. Lần 1: resolve thủ công
git merge feature/retry
# → CONFLICT in config.yml với diff3 markers
# → "Recorded preimage for 'config.yml'" — rerere ghi nhớ conflict
# Resolve: timeout: 60
echo "timeout: 60" > config.yml
git add config.yml && git commit
# → "Recorded resolution for 'config.yml'." — rerere ghi nhớ cách resolve

# 3. Hủy merge commit để tái lặp đúng conflict cũ
# (dữ liệu rerere nằm ở .git/rr-cache, không mất khi reset)
git reset --hard HEAD~1

# 4. Merge lần 2 — rerere tự apply
git merge feature/retry
# Git thông báo: "Resolved 'config.yml' using previous resolution."
# Merge vẫn dừng ở trạng thái conflict, nhưng file đã được điền sẵn resolution
cat config.yml   # → timeout: 60 (không còn conflict markers)
git add config.yml && git commit

# 5. Test --no-ff
git switch -c feature/no-ff-test
echo "new feature" >> config.yml
git add . && git commit -m "feat: no-ff test"

git switch main
git merge --no-ff feature/no-ff-test -m "feat: merge no-ff-test"
git log --oneline --graph
# Thấy merge commit với 2 parents

Tài liệu tham khảo


Bài tiếp theo →