Husky And Friends
เป็นตัวช่วยที่เอาไว้ทำ Git Hook
Git Hook คืออะไร
Git Hook คือ script ที่ใช้ในดักจับ Git event เช่น pre-commit หรือ pre-push แล้วจากนั้นเราจะทำอะไรหลังจากนั้นก็ขึ้นอยู่กับเรา
Husky คืออะไร
Husky เป็นตัวที่เอาไว้ช่วยทำ git hook Pre-commit และ Pre-push เพื่อให้มั่นใจได้ว่า Code ที่เรา push ขึ้นๆทุกๆครั้งจะผ่านมาตรฐานเบื้องต้นเสียก่อน เช่น
การใช้ Pre-commit เอาไว้สำหรับตรวจสอบ lint กับ run test
การใช้ ใช้ Pre-push เอาไว้สำหรับ scan for sonarqube


Install
#install
npm install husky --save-dev
# create .husky
## NPM
npx husky-init && npm install
## Yarn2
### pinst for postinstall hook in yarn2
yarn add pinst --dev
yarn dlx husky-init --yarn2 && yarn
# addscript
## git message syntax
## NPM
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit'
## Yarn 2
yarn husky add .husky/commit-msg 'yarn dlx commitlint --edit'
## pre commit command
## NPM
npx husky add .husky/pre-commit 'npm run pre-commit'
## Yarn 2
yarn husky add .husky/pre-commit 'yarn pre-commit'
npm install @commitlint/config-conventional @commitlint/cli --dev
touch .commitlintrc.json
touch .lintstagedrc
กรณีที่ใช้ sonarqube
#pre-push for sonarqube
npx husky add .husky/pre-push 'npx gulp default' or 'npx sonar-scanner'
git commit message setting
#.commitlintrc.json
{
"extends": ["@commitlint/config-conventional"],
"rules": {
"type-enum": [2, "always", ["ci", "chore", "docs", "feat", "fix", "perf", "refactor", "revert", "style", "test"]]
}
}
lint stage setting
#.lintstagedrc
{
"*.{ts, tsx}": ["tslint --fix --config tslint.json --project tsconfig.json"]
}
การเรียกใช้
git add.
git commit -m "docs: correct spelling of CHANGELOG"

Git Commit Message
หน้าตาของ Git Commit Message แบบ
[type](optional scope): [subject] [optional body]
** (scope): ==> (scope) และ : ต้องห้ามมีช่องว่าง : [subject] ==> : และ [subject] ต้องมีช่องว่าง 1 เคาะ
Type
build: อะไรก็ตามที่มันเกี่ยวกับการ Build (เช่น คำสั่ง npm หรือการเพิ่ม External Dependencies หรืออาจจะเป็นการปรับ Dockerfile ก็ได้)
chore: อะไรก็ตามที่ไม่เห็นจากข้างนอก (เช่น การปรับ .gitignore หรือ .prettierrc file เป็นต้น)
feat: A new feature 😏
fix: A bug fix 😎
docs: อะไรก็ตาม ที่เกี่ยวกับการปรับเอกสาร
refactor: ก็คือทำ Refactor อ่ะ ตรง ๆ
perf: อะไรก็ตาม ที่เกี่ยวกับการปรับปรุงประสิทธิภาพของตัว Application
test: อะไรก็ตาม ที่เกี่ยวกับการทดสอบ (อาจจะเป็นการทำ Test Case เพิ่ม หรือปรับปรุงก็ได้)
Scope
จะมีหรือไม่มีก็ได้ ควรเป็นคำนาม ที่สามารถบอกได้ว่า Commit นี้ไปโดนอะไรบ้าง เช่น
init
runner
watcher
config
controller
middleware
web-server
proxy
frontend
backend
Subject
บอกตรง ๆ เลยว่า Commit นี้ทำอะไร 1 อย่างก็พอ ถ้าสิ่งที่อยากบอก มันมีมากกว่า 1 อย่าง ก็น่าจะแปลว่า Commit นี้ ใหญ่เกินไปแล้ว
ตัวอย่าง
ปรับ Document
docs: correct spelling of CHANGELOG
ปรับแก้ปัญหา Code (ในส่วน Controller)
fix(controller): correct minor typos
ปรับแก้ปัญหา Code (ในส่วน View)
fix(view): correct image loading behaviourfrom auto to lazy
เพิ่ม Feature (ในส่วน Middleware)
feat(middleware): add authen for users resource
Last updated