Git Handbook

07 · Debugging & Inspection

Dùng Git để điều tra lịch sử, tìm context code, tìm regression và query commit graph.

1. Tìm context của dòng code

git-blame

Hiển thị commit/author liên quan đến từng dòng file.
Official docs ↗
Cú pháp
git blame [options] <file>
Hiểu đơn giản
Mục tiêu tốt nhất là tìm context lịch sử, không phải “đổ lỗi”.
git blame src/payment.js
git blame -L 40,80 src/payment.js

2. Tìm text trong tracked content

git-grep

Tìm pattern trong work tree hoặc tree/commit Git.
Official docs ↗
Cú pháp
git grep [options] <pattern>
Hiểu đơn giản
Nhanh và tiện trong repository.
git grep -n "calculateTotal"
git grep "TODO" HEAD~5

3. Binary search commit gây regression

git-bisect

Dùng binary search để tìm commit đầu tiên good→bad.
Official docs ↗
Cú pháp
git bisect start; git bisect bad; git bisect good <commit>
Hiểu đơn giản
Thay vì kiểm tra tuần tự N commit, bisect cần xấp xỉ log2(N) vòng.
git bisect start
git bisect bad
git bisect good v1.0.0
# test commit Git chọn
git bisect good   # hoặc bad
# lặp đến khi Git tìm culprit
git bisect reset

Tự động hóa

git bisect start HEAD v1.0.0
git bisect run npm test
Script/test command phải trả exit code 0 cho “good” và non-zero cho “bad” theo semantics của bisect.

4. Query lịch sử như một database

# commit chạm tới file
git log -- src/auth.js

# thay đổi nội dung theo từng commit
git log -p -- src/auth.js

# tìm commit làm số lần xuất hiện string tăng/giảm
git log -S"legacyFunction" --oneline

# tìm patch match regex
git log -G"payment.*timeout" --oneline

# ai sửa file gần đây
git log --format="%h %an %ad %s" --date=short -- src/payment.js

Official git-log docs ↗