All Toolsโ€บAI Commit Quality Guard
๐Ÿ”ง AI-Powered Code Review ToolsMay 21, 2026โœ… Tests passing

AI Commit Quality Guard

A pre-commit hook that uses an AI model to automatically review staged Python files before committing. It assesses the code for bugs, stylistic issues, and adherence to best practices, ensuring higher quality code is pushed to the repository.

What It Does

  • Automatically reviews staged Python files in a Git repository.
  • Provides feedback on potential bugs, stylistic issues, and best practices.
  • Blocks commits if issues are found in the code.

Installation

1. Install the required Python packages:

pip install openai pyyaml

2. Save the ai_commit_quality_guard.py script in your repository.

3. Create a configuration file named .ai_commit_quality_guard.yaml in the root of your repository (optional):

rules:
     max_line_length: 80

4. Add the script as a pre-commit hook by creating a .git/hooks/pre-commit file with the following content:

#!/bin/sh
   python3 path/to/ai_commit_quality_guard.py --config .ai_commit_quality_guard.yaml

5. Make the pre-commit hook executable:

chmod +x .git/hooks/pre-commit

Usage

When you attempt to commit Python files, the pre-commit hook will automatically review the staged files. If any issues are found, the commit will be blocked, and the issues will be displayed in the terminal.

Source Code

import os
import sys
import subprocess
import yaml
import argparse
from openai import ChatCompletion

def load_config(config_path):
    """Load configuration from a YAML file."""
    if not os.path.exists(config_path):
        return {}
    try:
        with open(config_path, 'r') as file:
            return yaml.safe_load(file) or {}
    except yaml.YAMLError as e:
        print(f"Error loading configuration file: {e}", file=sys.stderr)
        return {}

def get_staged_files():
    """Retrieve a list of staged Python files."""
    try:
        result = subprocess.run(
            ['git', 'diff', '--cached', '--name-only', '--diff-filter=ACM'],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        result.check_returncode()
        files = result.stdout.splitlines()
        return [f for f in files if f.endswith('.py')]
    except subprocess.CalledProcessError as e:
        print(f"Error retrieving staged files: {e.stderr}", file=sys.stderr)
        sys.exit(1)

def review_code(file_content, openai_api_key):
    """Use OpenAI's API to review the code for quality issues."""
    try:
        response = ChatCompletion.create(
            model="gpt-4",
            messages=[
                {"role": "system", "content": "You are a code quality reviewer."},
                {"role": "user", "content": f"Please review the following Python code for bugs, stylistic issues, and adherence to best practices:\n\n{file_content}"}
            ],
            api_key=openai_api_key
        )
        return response['choices'][0]['message']['content']
    except Exception as e:
        return f"Error during code review: {e}"

def main():
    parser = argparse.ArgumentParser(description="AI Commit Quality Guard")
    parser.add_argument('--config', type=str, default='.ai_commit_quality_guard.yaml', help="Path to configuration file")
    args = parser.parse_args()

    config = load_config(args.config)
    openai_api_key = os.getenv('OPENAI_API_KEY')

    if not openai_api_key:
        print("Error: OPENAI_API_KEY environment variable is not set.", file=sys.stderr)
        sys.exit(1)

    staged_files = get_staged_files()

    if not staged_files:
        print("No staged Python files to review.")
        sys.exit(0)

    block_commit = False

    for file_path in staged_files:
        print(f"Reviewing {file_path}...")
        try:
            with open(file_path, 'r') as file:
                file_content = file.read()
            review_result = review_code(file_content, openai_api_key)
            print(f"Review for {file_path}:")
            print(review_result)

            if 'issue' in review_result.lower():
                block_commit = True
        except FileNotFoundError:
            print(f"Error: File {file_path} not found.", file=sys.stderr)
            block_commit = True

    if block_commit:
        print("Commit blocked due to issues found in the code.", file=sys.stderr)
        sys.exit(1)

if __name__ == "__main__":
    main()

Community

Downloads

ยทยทยท

Rate this tool

No ratings yet โ€” be the first!

Details

Tool Name
ai_commit_quality_guard
Category
AI-Powered Code Review Tools
Generated
May 21, 2026
Tests
Passing โœ…
Fix Loops
2

Quick Install

Clone just this tool:

git clone --depth 1 --filter=blob:none --sparse \
  https://github.com/ptulin/autoaiforge.git
cd autoaiforge
git sparse-checkout set generated_tools/2026-05-21/ai_commit_quality_guard
cd generated_tools/2026-05-21/ai_commit_quality_guard
pip install -r requirements.txt 2>/dev/null || true
python ai_commit_quality_guard.py