본문 바로가기

기타

[GIT] git hook commit-msg 적용하기

git hook을 적용하려고 한다

우선 나의 경우 git hook을 적용하려고 하는 목적은 정적분석 툴이나, Test code 들을 git에 push 하기전에 미리 자동으로 확인해서 push된 코드에 quality를 보장하려고 하는것이다.

이번 포스팅에서는 먼저 commit message rule을 적용해 보도록 하겠다

음 .. 이유는? commit message는 협업에 있어서 중요하고, rule을 정하고 지키며 일관되고 보기좋은 commit message를 유지하고 싶어서 ..

 

1. git hook 의 공식 docs확인

link - https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks

 

Git - Git Hooks

If you’re writing a script/hook that others will need to read, prefer the long versions of command-line flags; six months from now you’ll thank us.

git-scm.com

 

2. 개념 정리

일단 기본적인 hook에 개념과 원리에 대하여 간단히 정리해본다.

cd .git/hooks/
ls
 
// 결과 
applypatch-msg.sample        fsmonitor-watchman.sample    pre-commit.sample        pre-receive.sample        update.sample
commit-msg            post-update.sample        pre-push.sample            prepare-commit-msg.sample
commit-msg.sample        pre-applypatch.sample        pre-rebase.sample
cs

terminal 에서 해당 명령을 실행하면 여러가지 sample file이 들어있는것을 확인할 수 있다.

각 파일들은 각 파일명에 해당하는 상황에 실행되어진다 - 자세한 설명은 docs를 참고

해당 sample file들은 기본적으로 작성되어져있는 예시이며 .sample 을 제거하면 자동으로 적용된다

.sample file은 Perl과 Bash로 작성되어있는 예제이고, git 공식 docs는 ruby로 되어있다.

스크립트는 언어를 가리지 않아서 사용하고 싶은걸 사용하면 된다.

셋다모름..망할.. 그래도 예제있는걸로 보고 하려고한다..

 

commit message에 대한 rule등을 지정하려고 하면 commit-msg file을 사용한다.

commit-msg
: 훅은 커밋 메시지가 들어 있는 임시 파일의 경로를 아규먼트로 받는다. 그리고 이 스크립트가 0이 아닌 값을 반환하면 커밋되지 않는다. 이 훅에서 최종적으로 커밋이 완료되기 전에 프로젝트 상태나 커밋 메시지를 검증한다

 

3. 적용하기

그럼 이제 목표는 명확해졌다.

입력된 commit message가 내가 원하는 포맷(정규식)과 일치하는지 확인하여 push를 막거나 commit을 허용하는 코드를 commit-msg file에 작성하면 된다.

// file 경로로 이동
$ cd .git/hooks/
 
// commit-msg file 생성 : .sample은 가만히 두고싶다 혹시모르니
$ touch commit-msg
 
// 코드 작성
$ vi commit-msg
cs

예시코드 및 설명

#!/usr/bin/env ruby
  
$regex =  /^\[MLA-[0-9]+\][\d\D]*refs[\s]?-[\s]?.*/
 
# enforced custom commit message format
def check_message_format
  message_file = ARGV[0]
  message = File.read(message_file)
  if !$regex.match(message)
    puts "[POLICY] Your message is not formatted correctly"
    puts "[RULE] [MLA-{issueTicketNumber}] \n\n /* message */ \n\n refs - {issueLink}"
    exit 1
  end
end
check_message_format
cs
  • ARGV[0]는 문서의 설명에서 나오듯이 커밋 메시지가 들어 있는 임시 파일의 경로에 해당한다
  • message에 file을 읽어서 commit message를 받아온다
  • commit message를 정규식과 비교하여 처리한다 .

 

4. 확인하기

잘 동작하는지 확인을 합니다

$git add .
$git commit
 
// 커밋 메세지 작성
cs
  • 오류 테스트
  • 성공 테스트

 

5. repository에 적용하기..!

흠.. 처음에는 git repository에 올려서 프로젝트에 참여하는 모든 팀원들이 같은 hook을 사용할수 있도록 하고싶었는데.. dot file은 어떻게 올리는지.. commit이 안돼서..좀 고민이다

그냥 hook res를 따로 만들어서 공유를 할지 .. 일단 여기까지

 

6. 삽질 원인 ! 꼭 점검하기

  • $chmod +x .git/hooks
  • hook file에 #!/usr/bin/env ruby 해당구문을 추가하지 않으면 실행가능하지 않은 파일로 인식된다
  • 정규식에서 삽질을 많이했다

 

[참조]

https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks

https://git-scm.com/book/ko/v2/Git맞춤-정책-구현하기

https://webcache.googleusercontent.com/search?q=cache:4hv_gcmbc44J:https://techblog.woowahan.com/2530/+&cd=2&hl=ko&ct=clnk&gl=kr

https://systemdesigner.tistory.com/33

https://dev.to/imshakthi/git-validate-commit-message-git-hooks-5aho

'기타' 카테고리의 다른 글

터미널 명령어 alias 설정하기 - git 명령어 쉽게 쓰기  (0) 2021.12.01