ข้ามไปเนื้อหาหลัก

git reflog — กู้ commit ที่หายไปแล้ว

git reflog บันทึกทุกครั้งที่ HEAD เคลื่อน — reset, rebase, checkout, merge ใช้กู้ commit ที่หายหลัง reset --hard หรือ branch ที่ลบไปแล้ว

git reflog
# HEAD@{0}: reset: moving to HEAD~2
# HEAD@{1}: commit: add feature X         ← commit ที่ต้องการ
# HEAD@{2}: commit: update styles
# HEAD@{3}: commit: initial setup

# กู้ commit กลับมา
git checkout HEAD@{1}        # detached HEAD ดูก่อน
git checkout -b recovered    # สร้าง branch ใหม่จาก commit นั้น

# หรือ reset กลับตรงๆ
git reset --hard HEAD@{1}

กู้ branch ที่ถูก git branch -D ลบ:

git reflog | grep 'feature/login'
# HEAD@{5}: checkout: moving from feature/login to main

git checkout -b feature/login HEAD@{5}

ข้อจำกัด: reflog อยู่ใน local repo เท่านั้น ไม่ได้ push ขึ้น remote และ entry จะหมดอายุใน 90 วัน (configurable ด้วย gc.reflogExpire)

กฎทอง: ก่อน reset --hard ควร git stash หรือจดเลข commit hash ไว้ก่อน