📑 Table des matières

Git + IA : automatiser ses commits et reviews

Automatisation 🟡 Intermédiaire ⏱️ 13 min de lecture 📅 2026-02-24

Git + AI: Automate Your Commits and Reviews

You code for 3 hours. You make a commit with the message "fix stuff." Two weeks later, you're trying to figure out when you broke authentication. Good luck with your Git history.

This scenario is familiar to every developer. And it's exactly the kind of problem AI solves perfectly: repetitive, important tasks that no one does correctly because they're boring.

In this guide, we'll transform your Git workflow with AI: automatic commits with smart messages, agent-powered code reviews, and flawless Git discipline—without any effort.


🤯 The Problem: Why Git Is Misused

Let's be honest. Most developers:

Bad Habit Consequence
git commit -m "fix" Unreadable history
500-line commits Impossible to review
No commits for 3 days Potential work loss
No review before merge Bugs in production
Forgetting to push "But it was on my PC!"
.env in the repo Secret leaks

This isn't laziness—it's human nature. Commit messages, reviews, discipline... these are tasks with low immediate gratification. The human brain naturally avoids them.

AI, on the other hand, finds nothing boring.


🏷️ Pre-commit Hooks with AI

What Is a Pre-commit Hook?

A Git hook is a script that runs automatically at certain stages. The pre-commit hook runs before each commit. If the script fails (exit code ≠ 0), the commit is blocked.

# View available hooks
ls .git/hooks/

# Hooks are scripts with specific names
# pre-commit, pre-push, commit-msg, etc.

Hook 1: Automatic Commit Message

Instead of writing your commit messages, let AI do it:

#!/bin/bash
# .git/hooks/prepare-commit-msg
# Generates a smart commit message from the diff

COMMIT_MSG_FILE=$1
COMMIT_SOURCE=$2

# Don't modify merge commits or amends
if [ "$COMMIT_SOURCE" = "merge" ] || [ "$COMMIT_SOURCE" = "squash" ]; then
    exit 0
fi

# Get the staged diff
DIFF=$(git diff --cached --stat)
DIFF_CONTENT=$(git diff --cached -- . ':!*.lock' ':!package-lock.json' | head -200)

if [ -z "$DIFF" ]; then
    exit 0
fi

# Generate the message with AI (via API)
MESSAGE=$(curl -s https://openrouter.ai/api/v1/chat/completions \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{
    \"model\": \"anthropic/claude-sonnet-4\",
    \"messages\": [{
      \"role\": \"user\",
      \"content\": \"Generate a concise git commit message (max 72 chars for title, optional body) for this diff. Use conventional commits format (feat/fix/docs/refactor/chore). Be specific. Respond with ONLY the commit message, nothing else.\n\nFiles changed:\n${DIFF}\n\nDiff:\n${DIFF_CONTENT}\"
    }],
    \"max_tokens\": 200
  }" | jq -r '.choices[0].message.content')

if [ -n "$MESSAGE" ] && [ "$MESSAGE" != "null" ]; then
    echo "$MESSAGE" > "$COMMIT_MSG_FILE"
fi

Result: Instead of typing git commit -m "fix login", you just run git commit, and the AI writes:

fix(auth): handle expired JWT tokens in middleware

- Add token expiry check before route handler
- Return 401 with clear error message
- Add unit test for expired token scenario

Hook 2: Automatic Linting and Checks

#!/bin/bash
# .git/hooks/pre-commit
# Checks the code before committing

set -e

echo "🔍 Pre-commit checks..."

# 1. No secrets in the code
echo "  Checking for secrets..."
if git diff --cached --diff-filter=ACM | grep -iE "(api_key|password|secret|token)\s*=\s*[\"'][^\"']+[\"']" | grep -v "example\|placeholder\|xxx\|your_"; then
    echo "❌ ERROR: Possible secret detected in the code!"
    echo "   Use environment variables (.env)"
    exit 1
fi

# 2. No sensitive files
SENSITIVE_FILES=(".env" "id_rsa" ".pem" "credentials.json")
for pattern in "${SENSITIVE_FILES[@]}"; do
    if git diff --cached --name-only | grep -q "$pattern"; then
        echo "❌ ERROR: Sensitive file detected: $pattern"
        echo "   Add it to .gitignore"
        exit 1
    fi
done

# 3. No console.log / debug prints
if git diff --cached --diff-filter=ACM -- "*.py" | grep -E "^\+" | grep -q "print("; then
    echo "⚠️  WARNING: print() detected. Debug forgotten?"
fi

if git diff --cached --diff-filter=ACM -- "*.js" "*.ts" | grep -E "^\+" | grep -q "console.log"; then
    echo "⚠️  WARNING: console.log detected. Debug forgotten?"
fi

# 4. Oversized files
MAX_SIZE=1048576  # 1MB
for file in $(git diff --cached --name-only --diff-filter=ACM); do
    if [ -f "$file" ]; then
        SIZE=$(wc -c < "$file")
        if [ "$SIZE" -gt "$MAX_SIZE" ]; then
            echo "❌ ERROR: $file is $(($SIZE/1024))KB (max 1MB)"
            exit 1
        fi
    fi
done

echo "✅ All checks passed"

Installing Hooks

# Make hooks executable
chmod +x .git/hooks/pre-commit
chmod +x .git/hooks/prepare-commit-msg

# To share hooks with the team
mkdir -p .githooks
cp .git/hooks/pre-commit .githooks/
cp .git/hooks/prepare-commit-msg .githooks/

# Configure Git to use the shared folder
git config core.hooksPath .githooks

🔎 Automatic Code Review by Agent

The Concept

Before each merge (or even each push), an AI agent reviews the code and flags:
- Potential bugs
- Security issues
- Possible improvements
- Inconsistencies with project style

Automatic Review Script

#!/bin/bash
# /root/scripts/ai-code-review.sh
# Runs an AI review on the latest changes

BRANCH=${1:-$(git branch --show-current)}
BASE=${2:-main}

echo "🔍 AI Code Review: $BRANCH vs $BASE"
echo "=================================="

# Get the diff
DIFF=$(git diff "$BASE"..."$BRANCH" -- . ':!*.lock' ':!*.min.*' ':!dist/' | head -500)

if [ -z "$DIFF" ]; then
    echo "No changes to review."
    exit 0
fi

# Modified files
FILES=$(git diff --name-only "$BASE"..."$BRANCH")
echo "Modified files:"
echo "$FILES"
echo ""

# Review via API
REVIEW=$(curl -s https://openrouter.ai/api/v1/chat/completions \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{
    \"model\": \"anthropic/claude-sonnet-4\",
    \"messages\": [{
      \"role\": \"user\",
      \"content\": \"Review this code diff. Focus on:\n1. Bugs and logical errors\n2. Security issues\n3. Performance concerns\n4. Code quality\n\nBe specific. Reference line numbers. If the code looks good, say so briefly.\n\nFiles: ${FILES}\n\nDiff:\n${DIFF}\"
    }],
    \"max_tokens\": 1000
  }" | jq -r '.choices[0].message.content')

echo "$REVIEW"

Integrating Review into the Workflow

# Option 1: Pre-push Hook
#!/bin/bash
# .git/hooks/pre-push
echo "🤖 Running AI code review before push..."
/root/scripts/ai-code-review.sh
echo ""
echo "Push will continue in 5 seconds. Ctrl+C to cancel."
sleep 5

# Option 2: Git Alias
git config --global alias.review '!/bin/bash /root/scripts/ai-code-review.sh'
# Usage: git review
# Or: git review feature-branch main

Review with OpenClaw

If you use OpenClaw, you can request a review directly:

# In Telegram, simply send:
Review the code in /root/projects/my-app,
compare the feature/auth branch with main

The agent will:
1. Examine the diff
2. Read the project context (README, existing tests)
3. Provide a detailed review
4. Suggest concrete improvements

This is more powerful than a script because the agent understands the full context of the project.


🔄 Git Discipline: The Agent That Commits for You

The Discipline Problem

The best Git practice is to make small, frequent commits. In practice, no one does this because interrupting your workflow to commit is tedious.

Solution: An agent that automatically commits after each work session.

Configuration with OpenClaw

Add to your heartbeat or as a permanent instruction:

## Git Auto-Commit

After each work session on a Git project:
1. `git status` to see changes
2. If files are modified:
   a. Group changes by logic (not all in one commit)
   b. For each group: `git add` the relevant files, then `git commit` with a descriptive message
   c. `git push` if on a branch with a remote
3. NEVER commit: .env, credentials, temporary files, node_modules

### Commit Conventions
- feat: new feature
- fix: bug fix
- docs: documentation
- refactor: restructuring without functional changes
- chore: maintenance, dependencies
- test: adding/modifying tests

Smart Auto-Commit Script

#!/bin/bash
# /root/scripts/smart-commit.sh
# Smart commit: groups changes by type

cd "$1" || exit 1

# Check if we're in a Git repo
if ! git rev-parse --is-inside-work-tree &>/dev/null; then
    echo "Not a Git repo"
    exit 1
fi

# Check for changes
if git diff --quiet && git diff --cached --quiet; then
    echo "Nothing to commit"
    exit 0
fi

# Separate by file type
DOCS=$(git diff --name-only | grep -E "\.(md|txt|rst|doc)$")
PYTHON=$(git diff --name-only | grep -E "\.py$")
JS=$(git diff --name-only | grep -E "\.(js|ts|jsx|tsx)$")
CONFIG=$(git diff --name-only | grep -E "\.(yml|yaml|json|toml|ini|cfg)$")
OTHER=$(git diff --name-only | grep -vE "\.(md|txt|rst|doc|py|js|ts|jsx|tsx|yml|yaml|json|toml|ini|cfg)$")

# Commit each group
commit_group() {
    local files="$1"
    local prefix="$2"

    if [ -n "$files" ]; then
        echo "$files" | xargs git add
        COUNT=$(echo "$files" | wc -l)
        git commit -m "${prefix}: update ${COUNT} file(s)"
    fi
}

commit_group "$DOCS" "docs"
commit_group "$PYTHON" "chore(python)"
commit_group "$JS" "chore(js)"
commit_group "$CONFIG" "chore(config)"
commit_group "$OTHER" "chore"

echo "✅ Smart commit completed"
git log --oneline -5

🧰 Tools: Comparison

GitHub Copilot

Aspect Detail
Function Real-time code autocompletion
Git Integration Commit message suggestions in VS Code
Price $10/month (Individual), $19/month (Business)
Strengths IDE-integrated, fast, contextual
Limitations No full review, no Git automation

Claude Code (Anthropic)

Aspect Detail
Function Complete coding agent in CLI
Git Integration Can read, modify, commit, create branches
Price Via Anthropic API or OpenRouter
Strengths Understands entire project, can refactor, test
Limitations CLI only, no IDE integration
# Example with Claude Code
claude "Review the last 3 commits and suggest improvements"
claude "Create a feature branch for user authentication"
claude "Write unit tests for the auth module and commit them"

OpenClaw Git Integration

Aspect Detail
Function Persistent AI agent with native Git access
Git Integration Auto-commit, review, repo monitoring
Price Self-hosted (free) + LLM cost
Strengths Full automation, works autonomously, Telegram alerts
Limitations Requires a server

OpenClaw can monitor a repo and act automatically:

```markdown

Instruction for OpenClaw Agent

Git Guardian

Every hour, check repos in /root/projects/:
1. For each repo with uncommitted changes:
- Review changes
- Commit with an appropriate message
- Push if the branch has a remote
2. For each repo with open PRs:
- Review them