Git Stash เป็นเครื่องมือสำคัญเมื่อต้องการสลับไป Branch อื่น หรือ Reset โค้ดเพื่อทำงานด้วยสถานะที่สะอาด ฟีเจอร์นี้ช่วยเก็บการเปลี่ยนแปลงชั่วคราวโดยไม่ต้องสร้าง Commit ซึ่งทำให้งานของนักพัฒนา VPS ใน ผู้ให้บริการโฮสติ้ง มีประสิทธิภาพ
อะไรคือ Git Stash?
Git Stash เป็นความสามารถของ Git ที่สามารถบันทึกการเปลี่ยนแปลงชั่วคราว โดยไม่ต้อง Commit เหมือนการ Save Draft ในการพัฒนา ขณะที่ Stash ยังอยู่ Working Directory ของคุณจะกลับไปสถานะก่อนหน้านั้น
เมื่อไรควรใช้ Git Stash
มีหลายสถานการณ์ที่ Git Stash มีประโยชน์:
- ต้องการเปลี่ยน Branch แต่ยังไม่เสร็จการแก้ไข
- ต้องการ Pull ส่วนนแต่มีความขัดแย้ง
- ต้องทำการ Reset Working Directory โดยเก็บการเปลี่ยนแปลง
- สลับงานอันดับสูง แต่ยังไม่เสร็จการแก้ไขงานปัจจุบัน
- ทดลองอะไรบางอย่างแล้วอยากเก็บเก่อไว้ก่อน
คำสั่ง Git Stash พื้นฐาน
# Stash การเปลี่ยนแปลงทั้งหมด
git stash
# Stash พร้อม Message
git stash save "Working on feature X"
# Stash เฉพาะ Staged Files
git stash push -m "Staged changes"
# Stash โดยรวมทั้ง Untracked Files
git stash -u
# Stash เฉพาะ Untracked Files
git stash -u -- .
ดูรายการ Stash
# ดูรายการ Stash ทั้งหมด
git stash list
# ดูรายละเอียด Stash ที่ระบุ
git stash show stash@{0}
# ดู Diff ของ Stash
git stash show -p stash@{0}
# ดู Stash พร้อม Stats
git stash show -S stash@{0}
การ Apply และ Pop Stash
Apply และ Pop มีความแตกต่างที่สำคัญ:
# Apply Stash โดยคงเก็บใน Stash List
git stash apply stash@{0}
# Apply Stash ล่าสุด
git stash apply
# Pop Stash (Apply + Delete)
git stash pop stash@{0}
# Pop Stash ล่าสุด
git stash pop
ความแตกต่าง: Apply คงเก็บ Stash ไว้ สามารถ Apply ได้หลายครั้ง ขณะที่ Pop จะลบ Stash หลังจาก Apply
การจัดการ Stash ขั้นสูง
# ลบ Stash ที่ระบุ
git stash drop stash@{0}
# ลบทั้งหมด
git stash clear
# สร้าง Branch จาก Stash
git stash branch new-branch stash@{0}
# Apply บาง Part ของ Stash
git stash show -p stash@{0} | git apply --reject
ตัวอย่าง Workflow
สถานการณ์ทั่วไป: กำลังทำงานบน Feature ใหม่ แล้วต้องเปลี่ยนไป Feature ด้วงใจก่อน
# 1. ทำงาน Feature X
# ... edit some files ...
# 2. ต้องเปลี่ยนไป Fix Bug ก่อน
git stash save "WIP: Feature X"
# 3. สลับไป develop Branch
git checkout develop
git pull
# 4. สร้าง Hotfix Branch และแก้ไข
git checkout -b hotfix/critical-bug
# ... fix bug ...
git add .
git commit -m "Fix critical bug"
git push
# 5. กลับมา Feature X
git checkout feature/feature-x
git stash pop
# 6. ทำงานต่อ Feature X
# ... continue editing ...
