Skip to content

Hooks

Git Hooks คือระบบ event ใน Git ที่ให้เรารัน script อัตโนมัติเมื่อเกิดเหตุการณ์บางอย่าง เช่น commit, push, merge เหมาะสำหรับ automate งาน เช่น เช็คโค้ด, run test, format code ก่อน commit

ประเภทของ Hooks ที่ใช้บ่อย

  • pre-commit: รันก่อน commit เช่น เช็ค lint/test
  • commit-msg: ตรวจสอบหรือแก้ไขข้อความ commit
  • pre-push: รันก่อน push เช่น run test
  • post-merge: ทำงานหลัง merge เช่น ติดตั้ง dependency

ตัวอย่างการใช้งาน

สร้าง pre-commit hook เช็ค lint

  1. สร้างไฟล์ .git/hooks/pre-commit (ไม่มีนามสกุล)
  2. ใส่ script เช่น
bash
#!/bin/sh
npm run lint
if [ $? -ne 0 ]; then
  echo "Lint failed!"
  exit 1
fi
  1. ให้สิทธิ์รันด้วย chmod +x .git/hooks/pre-commit

ใช้เครื่องมือช่วย (แนะนำ)

  • typicode.github.io faviconHusky (สำหรับ Node.js/JS/TS) ช่วยจัดการ hooks แบบ cross-platform

ตัวอย่างสถานการณ์จริง

"อยากให้ทุกคนในทีม run test ก่อน commit ใช้ pre-commit hook หรือ Husky ช่วยให้มั่นใจว่า code ที่ push ขึ้นไปผ่านมาตรฐาน"


Git Hooks ช่วย automate งานซ้ำๆ และลด human error ได้ดีมาก