├── .gitignore ├── .pre-commit-hooks.yaml ├── LICENSE ├── README.md ├── commit_msg_generator.py ├── config.py ├── main.py └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | 162 | .vscode/ 163 | .python-version -------------------------------------------------------------------------------- /.pre-commit-hooks.yaml: -------------------------------------------------------------------------------- 1 | - id: auto-commit-msg 2 | name: auto-commit-msg 3 | description: "Automatically generates commit messages based on diffs" 4 | entry: auto-commit-msg 5 | language: python 6 | require_serial: true 7 | additional_dependencies: ['openai==0.27.8'] 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Daco 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # auto-commit-msg 2 | 3 | ![](https://i.imgur.com/IedULvJ.gif) 4 | Automatically generate a commit message with just the `git commit` command, without `-m`. No more time wasted on crafting commit messages. 5 | ## Automate Your Commit Messages Like Never Before! 6 | 7 | `auto-commit-msg` is a powerful pre-commit hook that auto-generates commit messages using OpenAI's API. Elevate your Git workflow by ensuring consistent and intelligent commit logs in multiple languages. Experience a seamless and efficient development process while bearing a minimal cost for API usage. 8 | 9 | ## How to use auto-commit-msg with pre-commit 10 | 11 | See [pre-commit](https://github.com/pre-commit/pre-commit) for instructions 12 | 13 | Add this to your `.pre-commit-config.yaml`: 14 | 15 | ```yaml 16 | repos: 17 | - repo: https://github.com/Daco2020/auto-commit-msg.git 18 | rev: v0.1.2 19 | hooks: 20 | - id: "auto-commit-msg" 21 | ``` 22 | 23 | ## Required Environment Variables 24 | 25 | `OPENAI_API_KEY` 26 | Please register your own OpenAI API key in the environment variables. 27 | 28 | ## Optional Environment Variables 29 | 30 | `OPENAI_MODEL` 31 | Please specify the OpenAI model you wish to use. The default is "gpt-3.5-turbo". 32 | 33 | `COMMIT_LANGUAGE` 34 | Set the desired language for the commit message. By default, it's set to 'en'(English). 'ko'(Korean), 'jp'(Japanese), and 'cn'(Chinese) are also supported. 35 | 36 | `COMMIT_CONVENTION` 37 | Please specify the desired commit message convention. If you do not provide one, the default will be left blank. 38 | 39 | The example is as below: 40 | ```sh 41 | # Example 1: 42 | COMMIT_CONVENTION="^((revert: \")?(feat|fix|docs|style|refactor|perf|test|ci|build|chore)(\(.*\))?!!?:\s.{1,50})" 43 | 44 | # Example 2: 45 | COMMIT_CONVENTION="접두어로 feat, fix, docs, style, refactor, perf, test, ci, build, chore 중 하나를 사용하세요. (예시: feat: 로그인 기능 추가)" 46 | ``` 47 | 48 | 49 | ## License 50 | 51 | MIT 52 | 53 | -------------------------------------------------------------------------------- /commit_msg_generator.py: -------------------------------------------------------------------------------- 1 | from typing import Any, Dict, List 2 | import openai 3 | 4 | from config import ( 5 | CHUNK_SIZE, 6 | COMMIT_LANGUAGE, 7 | CONTENTS, 8 | OPENAI_API_KEY, 9 | OPENAI_MODEL, 10 | ) 11 | 12 | 13 | class CommitMessageGenerator: 14 | def __init__( 15 | self, 16 | ) -> None: 17 | openai.api_key = OPENAI_API_KEY 18 | self.model = OPENAI_MODEL 19 | self.chunk_size = CHUNK_SIZE 20 | self.content = CONTENTS.get(COMMIT_LANGUAGE, CONTENTS["en"]) 21 | 22 | def generate_commit_message(self, diff: str) -> str: 23 | """Generates a commit message based on the diff provided.""" 24 | messages = self._build_messages(diff) 25 | return self._get_response_from_openai(messages) 26 | 27 | def _build_messages(self, diff: str) -> List[Dict[str, Any]]: 28 | """Builds a list of messages to send to the OpenAI API.""" 29 | messages = [{"role": "system", "content": self.content["instruction_request"]}] 30 | 31 | content = self._get_processed_diff(diff) 32 | content += self.content["convention_request"] + self.content["answer_language"] 33 | messages.append({"role": "user", "content": content}) 34 | 35 | return messages 36 | 37 | def _get_processed_diff(self, diff: str) -> str: 38 | """Processes the diff for OpenAI API input.""" 39 | if len(diff) > self.chunk_size: 40 | return self.content["commit_msg_request"] + self._summarize_diff(diff) 41 | return self.content["commit_msg_request"] + diff 42 | 43 | def _summarize_diff(self, diff: str) -> str: 44 | """Summarizes the diff by processing it in chunks.""" 45 | max_size = self.chunk_size * 5 46 | summaries = [ 47 | self._get_response_from_openai( 48 | [ 49 | { 50 | "role": "user", 51 | "content": self.content["summarize_request"] 52 | + diff[i : i + self.chunk_size], 53 | } 54 | ] 55 | ) 56 | for i in range(0, len(diff[:max_size]), self.chunk_size) 57 | ] 58 | return " ".join(summaries) 59 | 60 | def _get_response_from_openai(self, messages: List[Dict[str, Any]]) -> str: 61 | """Fetches response from OpenAI API.""" 62 | response = openai.ChatCompletion.create( 63 | model=self.model, 64 | messages=messages, 65 | max_tokens=500, 66 | temperature=0.5, 67 | top_p=0.5, 68 | ) 69 | return response.choices[0].message.content 70 | 71 | 72 | openai.api_key = OPENAI_API_KEY 73 | -------------------------------------------------------------------------------- /config.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | # openai 4 | OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY") 5 | OPENAI_MODEL = os.environ.get("OPENAI_MODEL", "gpt-3.5-turbo") 6 | CHUNK_SIZE = 5000 7 | 8 | # language 9 | COMMIT_LANGUAGE = os.environ.get("COMMIT_LANGUAGE", "en") 10 | 11 | # convention 12 | COMMIT_CONVENTION = os.environ.get("COMMIT_CONVENTION", "") 13 | 14 | # prepare-commit-msg hook script that runs before commit 15 | PREPARE_COMMIT_MSG = """#!/bin/bash 16 | commit_msg_file=$1 17 | commit_source=$2 18 | commit_msg=$(cat $commit_msg_file) 19 | 20 | if [ "$commit_source" == "message" ] || [ "$commit_source" == "template" ] || [ "$commit_source" == "merge" ] || [ "$commit_source" == "squash" ] || [ "$commit_source" == "commit" ]; then 21 | exit 0 22 | fi 23 | 24 | echo $(cat .git/temp_commit_msg) > $commit_msg_file 25 | rm .git/temp_commit_msg 26 | 27 | echo -n > "$0" 28 | """ 29 | 30 | # These are contents used for the OpenAI API. 31 | CONTENTS = { 32 | "en": { 33 | "code_diff": "Below is the modified code:\n", 34 | "instruction_request": "You are an expert in writing commit messages. Please review the modified code I'm providing, and answer with just the commit message title\n", 35 | "summarize_request": "Please summarize the following text in 3 lines:\n", 36 | "commit_msg_request": "Please write a commit message title based on the following summary:\n", 37 | "convention_request": f"following the format {COMMIT_CONVENTION}" 38 | if COMMIT_CONVENTION 39 | else "", 40 | "answer_language": "Please answer in English.\n", 41 | }, 42 | "ko": { 43 | "code_diff": "아래는 수정된 코드입니다:\n", 44 | "instruction_request": "당신은 커밋 메시지 작성 전문가입니다. 제공하는 수정된 코드를 검토하고 커밋 메시지 제목만 답해주세요.\n", 45 | "summarize_request": "다음 텍스트를 3줄로 요약해주세요:\n", 46 | "commit_msg_request": "다음 요약을 기반으로 커밋 메시지 제목을 작성해주세요:\n", 47 | "convention_request": f"{COMMIT_CONVENTION} 형식에 맞춰 작성해주세요\n" 48 | if COMMIT_CONVENTION 49 | else "", 50 | "answer_language": "한국어로 답변해주세요.\n", 51 | }, 52 | "cn": { 53 | "code_diff": "以下是修改后的代码:\n", 54 | "instruction_request": "你是编写提交信息的专家。请审查我提供的修改后的代码,并只回答提交消息的标题\n", 55 | "summarize_request": "请在3行内总结以下文本:\n", 56 | "commit_msg_request": "请根据以下摘要编写提交消息标题:\n", 57 | "convention_request": f"遵循{COMMIT_CONVENTION}格式\n" if COMMIT_CONVENTION else "", 58 | "answer_language": "请用中文回答。\n", 59 | }, 60 | "jp": { 61 | "code_diff": "以下は修正されたコードです:\n", 62 | "instruction_request": "あなたはコミットメッセージの専門家です。提供する修正されたコードをレビューし、コミットメッセージのタイトルのみ回答してください。\n", 63 | "summarize_request": "以下のテキストを3行で要約してください:\n", 64 | "commit_msg_request": "以下の要約に基づいてコミットメッセージのタイトルを書いてください:\n", 65 | "convention_request": f"{COMMIT_CONVENTION}形式に従ってください\n" 66 | if COMMIT_CONVENTION 67 | else "", 68 | "answer_language": "日本語でお答えください。\n", 69 | }, 70 | } 71 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import subprocess 4 | import os 5 | 6 | from config import PREPARE_COMMIT_MSG 7 | from commit_msg_generator import CommitMessageGenerator 8 | 9 | 10 | def run() -> None: 11 | """Run the auto-commit-msg script.""" 12 | create_prepare_commit_msg() 13 | 14 | diff = get_diff() 15 | generator = CommitMessageGenerator() 16 | message = generator.generate_commit_message(diff) 17 | 18 | with open(".git/temp_commit_msg", "w") as file: 19 | file.write(message) 20 | 21 | 22 | def create_prepare_commit_msg() -> None: 23 | """Create a prepare-commit-msg hook that will be run before commit.""" 24 | with open(".git/hooks/prepare-commit-msg", "w") as file: 25 | file.write(PREPARE_COMMIT_MSG) 26 | os.chmod(".git/hooks/prepare-commit-msg", 0o755) 27 | 28 | 29 | def get_diff() -> str: 30 | """Get the diff of the staged files.""" 31 | cmd = ["git", "diff", "HEAD"] 32 | result = subprocess.run(cmd, capture_output=True, text=True) 33 | return result.stdout 34 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup( 4 | name="auto-commit-msg", 5 | py_modules=["main", "commit_msg_generator", "config"], 6 | entry_points={ 7 | "console_scripts": ["auto-commit-msg=main:run"], 8 | }, 9 | install_requires=["openai==0.27.8", 'subprocess32; python_version<"3.0"'], 10 | ) 11 | --------------------------------------------------------------------------------