-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauto_commit.py
More file actions
117 lines (103 loc) · 4.11 KB
/
auto_commit.py
File metadata and controls
117 lines (103 loc) · 4.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import subprocess
import openai # Ensure you have the `openai` library installed
import os
import sys # 추가: sys 모듈 임포트
# OpenAI API key 설정
openai.api_key = os.getenv("OPENAI_API_KEY") # 환경 변수에서 가져오기
def get_staged_diff():
"""Get the staged diff from git."""
try:
result = subprocess.run(
["git", "diff", "--cached"],
capture_output=True,
text=True,
encoding='utf-8',
check=True
)
return result.stdout.strip()
except subprocess.CalledProcessError as e:
print("Failed to get staged diff:", e)
return None
def generate_commit_message(diff):
"""Send the git diff to GPT-4 Mini API and get a commit message."""
try:
# GPT 요청
response = openai.ChatCompletion.create(
model="gpt-4o-mini",
messages=[
{
"role": "system",
"content": "You are a helpful assistant that generates git commit messages in Korean based on changes.",
},
{
"role": "user",
"content": "다음 변경사항에 대해 커밋 메시지를 작성해 주세요:\n\n"
+ diff
+ "\n\n"
"커밋 메시지는 한국어로 작성하되, 아래 prefix 중 하나를 사용하세요:\n"
"- build: 시스템 또는 외부 종속성 영향을 미치는 변경사항 (npm, gulp, yarn 레벨)\n"
"- ci: CI 구성파일 및 스크립트 변경\n"
"- chore: 패키지 매니저 설정 변경 (코드 수정 없이 설정만 변경)\n"
"- docs: 문서 변경\n"
"- feat: 새로운 기능 추가\n"
"- fix: 버그 수정\n"
"- perf: 성능 개선\n"
"- refactor: 버그 수정 없이 리팩토링\n"
"- style: 코드 스타일 변경 (공백, 포맷팅 등)\n"
"- test: 테스트 추가 또는 수정\n"
"- revert: 작업 되돌리기\n\n"
"예: 'fix: 잘못된 변수 초기화 수정'\n\n"
"그리고 한줄 띄고 변경사항에 대한 요약을 전달해줘\n"
"변경사항 요약에 대해서 '변경사항 요약'이라고 안줘도 되고 그냥 변경사항 요약만 전달해줘. 변경사항에 대해서 - 리스트 형태로 줘. 짧게 끊어서\n",
},
],
)
# 메시지 추출
message = response.choices[0].message["content"].strip()
return message
except Exception as e:
print("Failed to generate commit message:", e)
return None
def commit_changes(message):
"""Commit changes with the generated message."""
message = (
message.replace("`", "")
.replace("'", "")
.replace('"""', "")
.replace("'''", "")
.strip()
)
try:
subprocess.run(
["git", "commit", "-m", message],
encoding='utf-8',
check=True
)
print("Changes committed successfully!")
except subprocess.CalledProcessError as e:
print("Failed to commit changes:", e)
def main():
# --no-input 인자 처리
no_input = "--no-input" in sys.argv # 추가: 인자 확인
diff = get_staged_diff()
if not diff:
print("No staged changes found.")
return
print("Generating commit message...")
commit_message = generate_commit_message(diff)
if not commit_message:
print("Failed to generate commit message.")
return
print(f"Generated commit message: {commit_message}")
if no_input: # 추가: --no-input 인자일 경우
commit_changes(commit_message)
else:
confirm = (
input("Do you want to commit with this message? (y/n): ").strip().lower()
)
if confirm == "y":
commit_changes(commit_message)
else:
print("Commit aborted.")
if __name__ == "__main__":
main()