Last active
August 26, 2024 06:18
-
-
Save cdinnison/c34339e59ab1b76ce885b9c0ab31103b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| import sys | |
| import os | |
| # Add the pipx OpenAI installation directory to sys.path | |
| openai_path = '/Users/YOUR-PATH-HERE/.local/pipx/venvs/openai/lib/python3.12/site-packages' | |
| sys.path.append(openai_path) | |
| from openai import OpenAI | |
| import subprocess | |
| def get_diff(): | |
| try: | |
| diff = subprocess.check_output(['git', 'diff', '--cached'], stderr=subprocess.STDOUT).decode('utf-8') | |
| return diff.strip() if diff.strip() else None | |
| except subprocess.CalledProcessError: | |
| return None | |
| def generate_commit_message(diff): | |
| client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) | |
| response = client.chat.completions.create( | |
| model="gpt-4o-mini", | |
| messages=[ | |
| {"role": "system", "content": "You are a helpful assistant that generates concise git commit messages."}, | |
| {"role": "user", "content": f"Generate a short, descriptive commit message for the following code changes:\n\n{diff}"} | |
| ], | |
| max_tokens=50 | |
| ) | |
| return response.choices[0].message.content.strip() | |
| if __name__ == "__main__": | |
| diff = get_diff() | |
| if diff is None: | |
| print("No changes to commit", file=sys.stderr) | |
| sys.exit(1) # Exit with an error code | |
| commit_message = generate_commit_message(diff) | |
| print(commit_message) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment