버튼 수집상

[git] hook 제어하기 (부제: 커밋 올리면 슬랙 알람 보내기) 본문

TIL - git

[git] hook 제어하기 (부제: 커밋 올리면 슬랙 알람 보내기)

cocokaribou 2024. 1. 9. 15:05

1. root/.git/hooks 폴더 접속.

파일 익스플로러로 접근할 경우 .git 폴더 숨김 해제할 것.

 

2. 샘플로 생성돼있는 git hook 목록.

.sample 확장자 지우면 바로 사용 가능.

 

3. git hook 종류 알기

https://git-scm.com/docs/githooks

pre-commit commit 보다 먼저 실행
Lint 적용 시점
post-commit commit 직후 실행
알림 메세지 전송 시점
post-merge 로컬 레포지토리에서 pull 할 때
merge 실패하면 실행안됨

이 밖에도 다양한 액션들에 대한 hook이 있다. 문서 참고 바람.

 

 

4. git hook 만들기

touch post-commit

텍스트 에디터 인자로 넘기면 파일을 생성하는 동시에 편집할 수도 있다.

 

5. slack webhook 플러그인 세팅하기

이 블로그를 참고했다.

 

Slack Incoming Webhook 2가지 방법

Slack Incoming Webhook(인커밍웹훅) 설정에는 2가지 방법이 있습니다. 앱 생성(추천), 앱 추가(비추) 를 각각 알아봅니다.

velog.io

위 블로그 설명대로 여차저차 따라가면 slack으로 메세지를 발송하는 api url을 받아올 수 있다.

 

포스트맨으로 api 테스트
잘 날아오는 것 확인

 

6. git hook 정의하기

텍스트 에디터로 편집하기.

vim post-commit

아래 내용으로 만들어봤다.

USERNAME=$(git log -1 --pretty=format:'%an')

COMMIT_MESSAGE=$(git log -1 --pretty=format:'%B')

CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)

PAYLOAD='{"channel": "#community_webhook", "username": "webhookbot", "text": "`'"$CURRENT_BRANCH"'`\n'"$COMMIT_MESSAGE"' - '"$USERNAME"'", "icon_emoji": ":squirrel:"}'

# Sending the POST request
curl -X POST --data-urlencode "payload=$PAYLOAD" https://hooks.slack.com/services/PATH/PATH

저장하고 exit.

 

7. 실행가능한 파일로 바꾸기

위 파일을 편집한 뒤 ls -l로 파일 목록을 호출하면 아래처럼 나온다.

total 104
-rwxr-xr-x  1 yilee  staff   478 11 17  2022 applypatch-msg.sample
-rwxr-xr-x  1 yilee  staff   896 11 17  2022 commit-msg.sample
-rwxr-xr-x  1 yilee  staff  3327 11 17  2022 fsmonitor-watchman.sample
-rw-r--r--  1 yilee  staff   436  1  9 14:57 post-commit
-rwxr-xr-x  1 yilee  staff   189 11 17  2022 post-update.sample
-rwxr-xr-x  1 yilee  staff   424 11 17  2022 pre-applypatch.sample
-rwxr-xr-x  1 yilee  staff  1638 11 17  2022 pre-commit.sample
-rwxr-xr-x  1 yilee  staff  1348 11 17  2022 pre-push.sample
-rwxr-xr-x  1 yilee  staff  4898 11 17  2022 pre-rebase.sample
-rwxr-xr-x  1 yilee  staff   544 11 17  2022 pre-receive.sample
-rwxr-xr-x  1 yilee  staff  1492 11 17  2022 prepare-commit-msg.sample
-rwxr-xr-x  1 yilee  staff  3610 11 17  2022 update.sample

post-commit 파일에 실행권한x이 없는 것을 알 수 있다.

chmod +x post-commit

이러면 실행파일로 바뀐다.

 

 

8. 액션 취하고 확인

post-commit hook을 만들었으므로 커밋을 올려본다.

그럼 위처럼 슬랙으로 메시지가 잘 온다.

 

 

주의

slack webhook api의 channel 페이로드에는 #으로 시작하는 슬랙 채널명을 입력해야 한다.
1:1 대화방이나 단체방은 지정할 수 없음.

 

728x90

'TIL - git' 카테고리의 다른 글

[git] git 일부 레포지토리의 user 수정하기  (0) 2023.06.12
[git] revert VS reset  (0) 2023.06.12