commitizen-tools / commitizen

Create committing rules for projects :rocket: auto bump versions :arrow_up: and auto changelog generation :open_file_folder:
https://commitizen-tools.github.io/commitizen/
MIT License
2.51k stars 268 forks source link

Writes git commit messages with AI #670

Closed chihsuan closed 1 year ago

chihsuan commented 1 year ago

Description

Use open AI to write commit message automatically

Possible Solution

Add an option to the commit command to write a commitizen-style commit message using Open AI API.

Additional context

There is an AI commit tool: https://github.com/Nutlope/aicommits

Additional context

Ask ChatGPT to write a Python script to write a commit message based on git diff using open API in the conventional Commits style with characters limits < 8000:

import openai
import subprocess

# Authenticate with OpenAI API
openai.api_key = "YOUR_API_KEY_HERE"

git_diff = subprocess.check_output(["git", "diff"])

# Check if diff length is too large
if len(git_diff) > 8000:
  print("The diff is too large to write a commit message.")
  exit()

# Prepare prompt for OpenAI in Conventional Commits style
prompt = f"Please generate a commit message in Conventional Commits style for the following changes:\n\n{git_diff.decode('utf-8')}\n\nType 'feat' for a new feature, 'fix' for a bug fix, 'docs' for documentation updates, 'style' for code style changes, 'refactor' for code refactoring, 'test' for test updates, 'chore' for build and tooling updates, or 'other' for any other changes:"

# Generate text with OpenAI's GPT-3
response = openai.Completion.create(
  engine="text-davinci-002",
  prompt=prompt,
  max_tokens=64,
  n=1,
  stop=None,
  temperature=0.7,
)

# Extract the generated text from the OpenAI response
commit_type = response.choices[0].text.strip()

# Format the commit message using the commit type and the diff
commit_message = f"{commit_type}: {git_diff.decode('utf-8').splitlines()[0]}"

# Add and commit changes with formatted message
subprocess.call(["git", "add", "."])
subprocess.call(["git", "commit", "-m", commit_message])
Lee-W commented 1 year ago

Thanks @chihsuan ! This is an interesting proposal. I think we probably won't add it to the core of commitizen, but we could add it as a plugin.

woile commented 1 year ago

I agree with Lee, you could have a custom cz package. Where the prompt instead of asking for the questions, it generates the commit. It's too much overhead for us. You can find the template for a new cz here: https://github.com/commitizen-tools/commitizen_cz_template

chihsuan commented 1 year ago

Thanks for the quick reply! @Lee-W @woile That sounds good to me. 🙂

woile commented 1 year ago

Closing this, if you create a custom plugin do not hesitate to add it to our docs in the Third Part section