Created
February 21, 2025 07:44
-
-
Save xoelop/56dda64623ff43d0e53553531fc47e4f to your computer and use it in GitHub Desktop.
Generates a commit message for the staged changes in git, allowing us to pass custom instructions on how the message should look like and copies the commit message to the clipboard
This file contains 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
# import pyperclip | |
import argparse | |
import os | |
import subprocess | |
import openai | |
from dotenv import load_dotenv | |
load_dotenv() | |
def get_staged_diff(): | |
"""Gets the git diff of staged files.""" | |
try: | |
result = subprocess.run( | |
["git", "diff", "--cached"], capture_output=True, text=True, check=True | |
) | |
return result.stdout.strip() | |
except subprocess.CalledProcessError: | |
return None | |
def generate_commit_message(diff: str, model: str = "gpt-4o-mini") -> str: | |
"""Generates a commit message using OpenAI's GPT API.""" | |
openai.api_key = os.getenv("OPENAI_API_KEY_CURSOR") | |
response = openai.chat.completions.create( | |
model=model, | |
messages=[ | |
{ | |
"role": "system", | |
"content": "You are an assistant that generates concise and meaningful Git commit messages.", | |
}, | |
{ | |
"role": "user", | |
"content": f"""Generate a commit message for the following diff:\n{diff} | |
Follow these instructions to generate the commit message: | |
The commit message should be structured as follows: | |
``` | |
<type>[optional scope]: <description> | |
[optional body] | |
[optional footer(s)] | |
``` | |
The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. | |
Commits MUST be prefixed with a type, which consists of a noun, feat, fix, etc., followed by the OPTIONAL scope, OPTIONAL !, and REQUIRED terminal colon and space. | |
The type feat MUST be used when a commit adds a new feature to your application or library. | |
The type fix MUST be used when a commit represents a bug fix for your application. | |
A scope MAY be provided after a type. A scope MUST consist of a noun describing a section of the codebase surrounded by parenthesis, e.g., fix(parser): | |
A description MUST immediately follow the colon and space after the type/scope prefix. The description is a short summary of the code changes, e.g., fix: array parsing issue when multiple spaces were contained in string. | |
A longer commit body MAY be provided after the short description, providing additional contextual information about the code changes. The body MUST begin one blank line after the description. | |
A commit body is free-form and MAY consist of any number of newline separated paragraphs. | |
One or more footers MAY be provided one blank line after the body. Each footer MUST consist of a word token, followed by either a :<space> or <space># separator, followed by a string value (this is inspired by the git trailer convention). | |
A footer’s token MUST use - in place of whitespace characters, e.g., Acked-by (this helps differentiate the footer section from a multi-paragraph body). An exception is made for BREAKING CHANGE, which MAY also be used as a token. | |
A footer’s value MAY contain spaces and newlines, and parsing MUST terminate when the next valid footer token/separator pair is observed. | |
Breaking changes MUST be indicated in the type/scope prefix of a commit, or as an entry in the footer. | |
If included as a footer, a breaking change MUST consist of the uppercase text BREAKING CHANGE, followed by a colon, space, and description, e.g., BREAKING CHANGE: environment variables now take precedence over config files. | |
If included in the type/scope prefix, breaking changes MUST be indicated by a ! immediately before the :. If ! is used, BREAKING CHANGE: MAY be omitted from the footer section, and the commit description SHALL be used to describe the breaking change. | |
Types other than feat and fix MAY be used in your commit messages, e.g., docs: update ref docs. | |
The units of information that make up Conventional Commits MUST NOT be treated as case sensitive by implementors, with the exception of BREAKING CHANGE which MUST be uppercase. | |
BREAKING-CHANGE MUST be synonymous with BREAKING CHANGE, when used as a token in a footer. | |
In the body of the commit message, use bullet points to describe the changes made. | |
Prioritize the bullets points putting first the most important and significant changes, the ones that have the most impact. | |
In the description is should also be clear what the most impactful changes are. | |
""", | |
}, | |
], | |
) | |
result = response.choices[0].message.content.strip() | |
result = result.strip("```") | |
result = result.strip() | |
return result | |
def main(): | |
parser = argparse.ArgumentParser( | |
description="Generate Git commit messages using an LLM." | |
) | |
parser.add_argument( | |
"--apply", | |
action="store_true", | |
help="Apply the generated commit message automatically.", | |
) | |
args = parser.parse_args() | |
diff = get_staged_diff() | |
if not diff: | |
print("No staged changes found.") | |
return | |
commit_message = generate_commit_message(diff) | |
print("\nGenerated Commit Message and copied to clipboard:\n") | |
print(commit_message) | |
subprocess.run("pbcopy", text=True, input=commit_message) | |
if args.apply: | |
subprocess.run(["git", "commit", "-m", commit_message]) | |
print("\nCommit applied.") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment