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

Category: tool

Git Worktree — ทำงานหลาย Branch พร้อมกันโดยไม่ต้อง stash

git worktree ให้ checkout หลาย branch ออกมาเป็น folder แยกกันได้พร้อมกัน แก้ปัญหา "ต้องรีบ hotfix แต่ feature branch ยังไม่เสร็จ" อย่างถาวร

· อ่านประมาณ 1 นาที

สารบัญ

ปัญหาที่ Git Worktree แก้

ทำงานอยู่ใน feature branch ครึ่งทาง มีไฟล์ที่แก้แล้วยังไม่ commit พอได้รับ “ต้องแก้ production bug ด่วน” ก็ต้องเลือก:

  • git stash แล้วย้าย branch (เสี่ยง conflict)
  • commit งานค้างที่ยังไม่พร้อม (commit ไม่สะอาด)
  • clone repo ใหม่อีกชุด (เปลือง disk + ต้องติดตั้ง deps ใหม่)

Git Worktree แก้ปัญหานี้ได้โดยให้ checkout หลาย branch ออกมาเป็น folder แยกกัน โดยใช้ .git ชุดเดียวกัน

คำสั่งพื้นฐาน

# สร้าง worktree ใหม่ใน folder ../hotfix จาก branch main
git worktree add ../hotfix main

# สร้าง worktree + สร้าง branch ใหม่พร้อมกัน
git worktree add -b hotfix/auth-crash ../hotfix-auth main

# ดูรายการ worktree ที่มีอยู่
git worktree list

# ลบ worktree เมื่อเสร็จงาน
git worktree remove ../hotfix

ตัวอย่าง Workflow จริง

# สถานการณ์: กำลังทำ feat/new-dashboard อยู่
git branch
# * feat/new-dashboard
#   main

# ได้รับแจ้ง: มี bug ใน auth บน production
git worktree add ../fix-auth main

# แก้ bug ในโฟลเดอร์ ../fix-auth โดยไม่กระทบ feature ที่ทำอยู่
cd ../fix-auth
# ... แก้ไข, test, commit ...
git push origin HEAD:hotfix/auth

# กลับมาทำ feature ต่อ (ไม่มีอะไรหาย)
cd ../panupong-creative-space

ใช้กับ Multi-Agent Workflow

Worktree เหมาะมากสำหรับระบบ multi-agent เพราะแต่ละ agent ทำงานใน folder แยกกันได้โดยไม่ชน:

# สร้าง worktree สำหรับ frontend agent
git worktree add ../workspace-frontend feat/frontend

# สร้าง worktree สำหรับ content agent
git worktree add ../workspace-content feat/content

แต่ละ agent แก้ไฟล์ของตัวเองใน folder ของตัวเอง → merge กลับ main เมื่อเสร็จ

ข้อควรระวัง

  • ไม่สามารถ checkout branch เดิมใน worktree 2 อันพร้อมกัน (จะ error)
  • git worktree remove จะ fail ถ้า working tree ไม่ clean → ต้อง --force
  • node_modules ไม่ถูก share → ต้องรัน npm install แยกในแต่ละ worktree

คำสั่งที่ใช้บ่อย

# prune worktree ที่ folder ถูกลบแล้ว
git worktree prune

# lock worktree ไว้ (ป้องกันการลบโดยบังเอิญ)
git worktree lock ../hotfix --reason "รอ QA ตรวจ"

# unlock
git worktree unlock ../hotfix

สรุป

Git Worktree เป็น feature ที่คนรู้จักน้อยกว่าที่ควร ใช้แทน git stash ในเกือบทุกกรณีที่ต้องสลับ context เร็ว และไม่มี overhead เหมือนการ clone ใหม่