본문 바로가기
JS

엄격하게 commit 하기 (husky, commitlint, lint-staged)

by 사과넹 2024. 4. 15.
반응형

Conventional Commit

  • commit 메시지의 규칙
  • 모두 같은 규칙을 사용하며 커밋의 변경 및 수정사항, 기능 구현 등을 명시적으로 표현할 수 있다
  • 커밋을 통한 히스토리도 파악할 수 있다
  • conventional commit 문서에서 커밋 규칙을 더 자세하게 알 수 있다

 

husky

  • convential commit을 따르기 위해 node.js 패키지 중 하나인 husky를 사용해 git hooks를 관리할 수 있다

 

방법

1. husky 설치

npm install --save-dev husky

 

 

2. husky 초기화(추천)

  • ./husky/pre-commit을 생성하고, package.jsonprepare 명령어를 추가한다
npx husky init

 

 

3. lint-staged 설치

linting 도구에 대한 설정이 우선되어야 한다. (ex. eslint)

  • add한 파일에 한해(staging된 파일) pre-commit하기 위한 라이브러리
  • 커밋을 할 파일에 대해 linting 한다
npm install lint-staged --save-dev

 

 

4. pre-commit시에 진행할 명령어들을 package.json에 추가

// package.json

"devDependencies": {...},
"lint-staged": {
  "*.{js,jsx,ts,tsx}": [
    "prettier --cache --write",
    "eslint --cache --fix --max-warnings=0"
  ]
}

 

 

5. 새로운 hook 추가

  • 커밋 전 linting하기 위한 명령어 hook을 추가한다
  • 예를 들어 package.jsonlint 명령어가 lint면 아래의 npm testnpm run lint로 변경해야 한다.
// .husky/pre-commit 파일에 npm test를 입력

echo "npm test" > .husky/pre-commit

 

 

6. lint-staged와 husky 테스트

  • 아래 메시지가 성공적으로 커밋된다면 세팅 완료
git commit -m "Keep calm and commit"

 


commitlint

방법

1. commitlint 설치

npm install --save-dev @commitlint/{cli,config-conventional}

 

 

2. commitlint 설정파일 생성 - 최상위에 commitlint.config.js 를 생성하고, 기본 컨벤션을 사용한다

echo "export default { extends: ['@commitlint/config-conventional'] };" > commitlint.config.js

 

 

3. commit linting 명령어 추가

  • ./husky/commit-msg를 생성한다
echo "npx --no -- commitlint --edit $1" > .husky/commit-msg

 

 

4. 가장 마지막 커밋메시지를 lint test

npx commitlint --from HEAD~1 --to HEAD --verbose

 

  • 규칙에 맞는 commit이면 `v8.0` 부터 아무런 메시지를 반환하지 않는다
    규칙에 맞지 않으면 아래와 같은 결과를 출력한다
git commit -m "foo: this will fail"

husky > commit-msg
No staged files match any of provided globs.
⧗ input: foo: this will fail
✖ type must be one of [build, chore, ci, docs, feat, fix, perf, refactor, revert, style, test] [type-enum]

✖ found 1 problems, 0 warnings
ⓘ Get help: https://github.com/conventional-changelog/commitlint/#what-is-commitlint

husky - commit-msg script failed (code 1)

 

 


5. custom commit message 규칙 설정하기

  • commitlint.config.js가 생성되면서 commitlint default로 적용된 부분을 삭제한다(아래)
extends: ['@commitlint/config-conventional']

 

 

728x90
반응형