wan의 개발일기
Git Hooks 활용하기 본문
들어가며
Git Hooks는 알고는 있었는데 직접 설정해본 적이 없었다.
commit, push 같은 Git 이벤트 전후에 스크립트를 자동으로 실행할 수 있어서 코드 품질 관리에 유용하다.
핵심 훅과 실전 활용법을 정리해둔다.
Git Hooks란?
Git 이벤트가 발생할 때 자동으로 실행되는 스크립트다.
.git/hooks/ 디렉토리에 저장된다.
ls .git/hooks/
# applypatch-msg.sample
# commit-msg.sample
# pre-commit.sample
# pre-push.sample
# prepare-commit-msg.sample
# ...
.sample 확장자를 제거하면 활성화된다.
주요 훅 종류
| 훅 | 실행 시점 | 주요 용도 |
|---|---|---|
pre-commit |
git commit 실행 직전 |
린트, 포맷팅 검사 |
commit-msg |
커밋 메시지 작성 후 | 커밋 메시지 규칙 검사 |
pre-push |
git push 실행 직전 |
테스트 실행 |
post-commit |
커밋 완료 후 | 알림, 로깅 |
post-merge |
merge 완료 후 | 의존성 자동 설치 |
직접 작성하기
pre-commit 훅 (ESLint 검사)
# .git/hooks/pre-commit 파일 생성
cat > .git/hooks/pre-commit << 'EOF'
#!/bin/sh
echo "ESLint 검사 중..."
npm run lint
if [ $? -ne 0 ]; then
echo "ESLint 오류가 있습니다. 커밋이 중단됩니다."
exit 1
fi
echo "ESLint 통과"
exit 0
EOF
# 실행 권한 부여
chmod +x .git/hooks/pre-commit
commit-msg 훅 (커밋 메시지 검사)
cat > .git/hooks/commit-msg << 'EOF'
#!/bin/sh
COMMIT_MSG=$(cat "$1")
PATTERN="^(feat|fix|docs|style|refactor|test|chore)(\(.+\))?: .{1,50}"
if ! echo "$COMMIT_MSG" | grep -qE "$PATTERN"; then
echo "커밋 메시지 형식이 올바르지 않습니다."
echo "올바른 형식: feat(scope): 메시지"
exit 1
fi
exit 0
EOF
chmod +x .git/hooks/commit-msg
pre-push 훅 (테스트 실행)
cat > .git/hooks/pre-push << 'EOF'
#!/bin/sh
echo "테스트 실행 중..."
npm test
if [ $? -ne 0 ]; then
echo "테스트 실패. push가 중단됩니다."
exit 1
fi
exit 0
EOF
chmod +x .git/hooks/pre-push
Husky로 팀 전체에 적용하기
.git/hooks/는 Git 추적 대상이 아니라 팀원과 공유되지 않는다.
Husky를 사용하면 훅을 저장소에 포함시켜 팀 전체에 동일하게 적용할 수 있다.
설치
npm install --save-dev husky
npx husky init
훅 추가
# pre-commit 훅
echo "npm run lint" > .husky/pre-commit
# commit-msg 훅 (commitlint 연동)
echo "npx --no -- commitlint --edit \$1" > .husky/commit-msg
# pre-push 훅
echo "npm test" > .husky/pre-push
package.json 설정
{
"scripts": {
"prepare": "husky"
}
}
npm install 시 자동으로 Husky가 설정된다.
lint-staged와 함께 사용하기
pre-commit에서 전체 파일을 린트하면 느리다.
lint-staged를 사용하면 스테이징된 파일만 검사한다.
npm install --save-dev lint-staged
// package.json
{
"lint-staged": {
"*.{js,jsx,ts,tsx}": [
"eslint --fix",
"prettier --write"
],
"*.{css,scss}": [
"prettier --write"
]
}
}
# .husky/pre-commit
npx lint-staged
훅 임시 건너뛰기
급할 때 훅을 건너뛰어야 하는 경우:
# 훅 무시하고 커밋
git commit --no-verify -m "fix: 긴급 수정"
# 훅 무시하고 push
git push --no-verify
--no-verify는 꼭 필요한 경우에만 사용한다. 습관적으로 사용하면 훅을 설정한 의미가 없어진다.
정리
| 항목 | 설명 |
|---|---|
pre-commit |
커밋 전 린트, 포맷 검사 |
commit-msg |
커밋 메시지 규칙 검사 |
pre-push |
push 전 테스트 실행 |
| Husky | 훅을 저장소에 포함해 팀 공유 |
| lint-staged | 스테이징된 파일만 선택적 검사 |
--no-verify |
훅 임시 건너뛰기 |
'Git, Github > Github 심화' 카테고리의 다른 글
| GitHub Security (Secrets, Dependabot) (0) | 2026.05.04 |
|---|---|
| Submodule & Monorepo 개념 (0) | 2026.05.04 |
| 오픈소스 기여하기 (fork, PR) (0) | 2026.05.03 |
| GitHub Pages로 정적 사이트 배포 (0) | 2026.05.03 |
| GitHub Issues & Projects로 일감 관리 (0) | 2026.05.03 |