커밋메시지에 자동으로 지라 이슈번호 넣기(with Python)

·2023년 1월 11일
0

기타

목록 보기
2/2

set git hook prepare-commit-msg with Python

이 작업은 동료가 만들었던 쉘스크립트로 된 비슷한 작업과 도움 덕분에 가능했습니다.

삽질의 시작

동료가 설명/설정해준 방법을 이용해 커밋메시지에 자동으로 지라 이슈번호를 잘 넣고 있던 어느날, 제가 맥북을 포맷하는 사태가 일어났습니다.

(당연히) 로컬에 설정돼있던 파일이 다 날아갔고, 이 참에 제가 쓰는 커밋메시지 양식에 맞춰서 다시 git hook을 세팅하려고 마음 먹었습니다. 그렇게 삽질을 하게 될 줄은 꿈에도 모른 채…

에디터(VSCode 등)로 prepare-commit-msg 편집하기

저는 vi에 익숙하지 않아서 에디터로 열었습니다.

터미널 로컬 imweb 레포에서 cd .git/hooks : .git/hooks 폴더로 들어갑니다.

cp prepare-commit-msg.sample prepare-commit-msg : prepare-commit-msg.sample의 내용을 복사하여 실제 동작할 prepare-commit-msg 파일을 만들어줍니다.

에디터를 열고 File > open… > imweb 폴더

숨겨진 파일폴더들이 노출시킵니다. → Shift + Command + .

.git/hooks 에 있는 prepare-commit-msg 클릭!

파이썬으로 작성하기

샘플에서 복사한 파일 맨 윗줄에 #!/bin/sh 가 보일 겁니다.

#!/usr/bin/env python3 로 수정합니다. (M1 맥북프로, macOS Ventura 13.1 버전 기준입니다.)
이제 이 파일은 파이썬 코드로 동작하게 됩니다. 나머지 내용은 전부 삭제합니다.

의도하는 동작

저는 feat, fix, hotfix, chore, refactor 등을 통해 커밋을 구분하는 방식의 커밋메시지를 선호합니다.

ex) fix: getBillingList parameter type error

위와 같은 커밋메시지를 작성하고 커밋했을 때, 작업하고 있는 브랜치 이름에 “IES-1294” 같은 지라 이슈번호가 존재하면 아래와 같이 자동으로 변경되길 원했습니다.

fix: [IES-1294] getBillingList parameter type error

아래는 이것을 구현한 파이썬 코드입니다.(여기저기 구글링과 복붙을 통해 만든 데다 평소 파이썬을 사용하지 않아 제가 코드에서 아직 이해하지 못한 부분도 많고, 분명히 더 나아질 여지가 많을 코드입니다. 조언댓글 환영합니다.)

코드

#!/usr/bin/env python3
import sys, re
import subprocess

def get_branch_name():
    branch = subprocess.run(["git", "rev-parse", "--abbrev-ref", "HEAD"], capture_output=True, text=True).stdout.strip()
    return branch

def add_jira_issue_number(project_list):
    branch_name = get_branch_name()
    is_jira_project = False

    for project_name in project_list:
        regex = project_name+"-[0-9]+"
        compiled_regex = re.compile(regex)
        jira_issue_number = compiled_regex.match(branch_name)
        if (jira_issue_number != None):
            commit_msg_filepath = sys.argv[1]   
            with open(commit_msg_filepath, 'r+') as fh:
                commit_msg = fh.read()
                if (commit_msg.find(':') == -1):
                    print("':'를 넣지 않은 커밋메시지를 작성하셨습니다.")
                    break
                prefix, msg_details = commit_msg.split(":")
                fh.seek(0, 0)
                fh.write('%s: [%s] %s' % (prefix, jira_issue_number.group(), msg_details))
                is_jira_project = True
            break

    if (is_jira_project == False):
        print("브랜치명에서 지라프로젝트명을 찾지 못했습니다.")
    else:
        print("Jira Issue ID 입력되었습니다.")


print("Commit message에 Jira Issue ID 자동 입력 중입니다. - .git/hooks/prepare-commit-msg")
project_list = ["ISMS", "WASTMS", "PJTREFAC"]
add_jira_issue_number(project_list)

reference

Here is an example of how to get the current branch name in a prepare-commit-msg git hook using Python:

import subprocess

def get_branch_name():
    branch = subprocess.run(["git", "rev-parse", "--abbrev-ref", "HEAD"], capture_output=True, text=True).stdout.strip()
    return branch

print(get_branch_name())

This code uses the subprocess module to run the git command git rev-parse --abbrev-ref HEAD, which returns the name of the current branch. The capture_output=True argument captures the output of the command as a string, which is then stripped of leading and trailing whitespace using the strip() method.

You can use this function within your prepare-commit-msg hook script to get the branch name and use it as per your requirement.

profile
백엔드 개발자. 공동의 목표를 함께 이해한 상태에서 솔직하게 소통하며 일하는 게 가장 즐겁고 효율적이라고 믿는 사람.

0개의 댓글