Ravindra BagaleCourses & study guides Track your progress
AI CODING ASSISTANTS · CHAPTER 5 · WORKFLOWS

How to Use AI for Git (Commits, Branches, Conflicts)

AI can draft commit messages, suggest branch names and explain a conflict hunk. You still run git yourself. Never let an agent force-push or rewrite shared history without a clear OK.

In short: show the staged diff for messages, ask for conventional commits, use AI to explain conflict markers, and keep destructive git commands on manual approval.

Why AI helps with Git

WHY

Blank commit messages waste review time. Conflict markers are scary the first hundred times. AI drafts clear subjects and explains both sides of a hunk. You decide what to keep and you type the git commands you understand.

What AI can help with

WHAT
  • Commit messages: from git diff --staged — subject + short body.
  • Branch names: short, kebab-case, tied to the ticket or intent.
  • Explain a conflict: what each side changed; you still choose.
  • PR summary: from the commit list or full PR diff.

How AI + Git flows

1 · Stage what you mean git add -p if needed 2 · Diff → commit message conventional style 3 · Push feature branch no force on main 4 · On conflict explain hunks, you edit 5 · Test then commit merge/rebase carefully
COMMIT MESSAGE PROMPT (COPY)

Write a conventional commit for this staged diff. One subject ≤72 chars (feat/fix/docs/refactor/test/chore). Then a 1–3 line body explaining why. No fluff. No secrets.

sample message shape
# After: git diff --staged
# Prompt the AI: "Write a conventional commit message for this staged diff. One subject line under 72 chars, then a short body."

feat(billing): use Decimal for GST totals

Avoid float rounding surprises on prices like 99.99.
Add pytest cases for 18%, zero rate, and negatives.

How to use AI with Git step by step

HOW
  1. Stage deliberately (git add -p) so the message matches the change.
  2. Paste git diff --staged (or use Copilot / Cursor commit helpers if your plan has them).
  3. Edit the subject if the AI is vague (“fix stuff” → real intent).
  4. On conflicts: paste one hunk with markers; ask “explain both sides; recommend a merge keeping X behaviour.” Then you edit the file.
  5. Re-run tests after resolving conflicts before you commit.
SafeDangerous without explicit OK
Draft commit message / PR summarygit push --force to shared main
Suggest branch namegit reset --hard on uncommitted work you need
Explain conflict markersgit clean -fdx wiping local files
Summarise recent commitsRewriting published history on a shared branch
Rule: agent mode can run git. Keep approval on for push, reset, clean and rebase onto shared branches. Prefer you typing destructive commands.

Settings / tool tips

  1. GitHub Copilot and Cursor can suggest commit messages from the staged diff (UI labels change — look for the commit message sparkle / generate action in the Source Control view).
  2. Claude Code CLI: you can ask it to draft a message from the staged diff; still run git commit yourself unless you knowingly allow it.
  3. Project rules: “conventional commits; never commit .env; never force-push main.”
  4. Conflicts: resolve in the IDE merge UI; use AI only to explain, then test.

Try this yourself: review an AI commit message, then prove the helper rules

Hello friends. In this practice you keep a small Python helper that reviews what an AI might draft for Git. The helper checks conventional commit subjects, rejects a subject that claims a file was added when that path is not staged, and refuses a clearly fictional SECRET_TOKEN line. You ask an AI for a commit subject for a Lumen Bay packing change, then you prove the rules with pytest. The live chapter already covered how to prompt for messages and how to treat conflicts. Here you practise automated guardrails you can keep beside your workflow. The token strings are labeled fictional teaching placeholders, not real credentials.

Ravindra Bagale's Tip

Never commit a line that looks like SECRET_TOKEN or an API key, even in a demo repo. Ask the AI for a commit message from the staged diff, then run a helper or checklist that rejects secrets and mismatched file claims before you type git commit.

Practice label: every name, number and token string in this exercise is fictional teaching data. The markers SECRET_TOKEN= and FICTIONAL_API_KEY= are labeled practice placeholders, not real credentials. Passing these tests proves only the listed helper rules.
Environment (tested): this exercise was run on 6 November 2026 and re-run on 16 November 2026 with Python 3.13.5 and pytest 9.1.1. Use Python 3.10 or newer. A temporary git repo is not required for these unit tests.

Your task: save the starter git_msg_check.py and the tests. The starter stubs are too trusting or too strict in the wrong places. Ask an AI to implement the four helpers so conventional subjects pass, mismatched add claims fail, fictional secret markers block a commit, and should_block_commit returns the exact reason strings the tests expect.

Setup

HOW
  1. Create a project folder and open a terminal inside it.
  2. Create a virtual environment: on macOS or Linux run python3 -m venv .venv. On Windows run py -3 -m venv .venv.
  3. Activate it: on macOS or Linux run source .venv/bin/activate. In Windows Command Prompt run .venv\Scripts\activate.bat, and in Windows PowerShell run .venv\Scripts\Activate.ps1.
  4. Install pytest inside the virtual environment: python -m pip install pytest.

Starter git_msg_check.py (behaviour stubs fail several tests on purpose):

git_msg_check.py
"""Review helpers for AI-drafted Git commit text (fictional practice only).

Students ask an AI for a conventional commit subject, then prove the helper rules
with pytest. SECRET_TOKEN examples are clearly fictional placeholders, not real keys.
"""
from __future__ import annotations

import re

ALLOWED_TYPES = ("feat", "fix", "docs", "refactor", "test", "chore")
# Fictional teaching marker only — not a real credential.
FICTIONAL_SECRET_MARKERS = ("SECRET_TOKEN=", "FICTIONAL_API_KEY=")


def is_valid_conventional_subject(subject: str) -> bool:
    """Return True when subject looks like 'type: short summary' and length is 1..72.

    Starter: always returns False so you must ask an AI (or write) the real checks.
    """
    _ = subject
    return False


def message_matches_staged(subject: str, staged_files: list[str]) -> bool:
    """Return False when the subject claims a file was added but that path is not staged.

    Looks for a simple 'add <path>' or 'added <path>' phrase (case-insensitive).
    Starter always returns True (too trusting).
    """
    _ = (subject, staged_files)
    return True


def diff_looks_safe_to_commit(diff_text: str) -> bool:
    """Return False when the staged diff text contains a fictional secret marker.

    Starter always returns True (too trusting).
    """
    _ = diff_text
    return True


def should_block_commit(subject: str, staged_files: list[str], diff_text: str) -> str | None:
    """Return a short reason string when the commit should be blocked, else None."""
    if not is_valid_conventional_subject(subject):
        return "subject must be a conventional commit under 73 characters"
    if not message_matches_staged(subject, staged_files):
        return "subject claims a file that is not in the staged list"
    if not diff_looks_safe_to_commit(diff_text):
        return "diff contains a fictional secret marker; do not commit it"
    return None

Tests test_git_msg_check.py (do not weaken these checks):

test_git_msg_check.py
"""pytest checks for the fictional AI-for-Git commit review helper."""
import pytest
from git_msg_check import (
    diff_looks_safe_to_commit,
    is_valid_conventional_subject,
    message_matches_staged,
    should_block_commit,
)


def test_valid_conventional_subjects():
    assert is_valid_conventional_subject("feat: add moss cart badge helper")
    assert is_valid_conventional_subject("fix: correct bay label on packing slip")
    assert is_valid_conventional_subject("docs: explain fictional SECRET_TOKEN marker")


def test_rejects_bad_subjects():
    assert is_valid_conventional_subject("") is False
    assert is_valid_conventional_subject("fixed stuff") is False
    assert is_valid_conventional_subject("feat:") is False
    long_ok_prefix = "feat: " + ("x" * 70)
    assert len(long_ok_prefix) > 72
    assert is_valid_conventional_subject(long_ok_prefix) is False


def test_message_matches_staged_when_claim_is_true():
    subject = "feat: add packing.py for Lumen Bay demo"
    assert message_matches_staged(subject, ["packing.py", "README.md"]) is True


def test_message_rejects_claim_for_missing_file():
    subject = "feat: add secrets.env for local demo"
    assert message_matches_staged(subject, ["packing.py"]) is False


def test_diff_blocks_fictional_secret_token():
    dirty = "diff --git a/config.py b/config.py\n+SECRET_TOKEN=fictional-practice-token-not-real\n"
    clean = "diff --git a/packing.py b/packing.py\n+print('hello lumen bay')\n"
    assert diff_looks_safe_to_commit(dirty) is False
    assert diff_looks_safe_to_commit(clean) is True


def test_should_block_commit_reasons():
    assert should_block_commit("messy", ["a.py"], "") == (
        "subject must be a conventional commit under 73 characters"
    )
    assert should_block_commit(
        "feat: add missing.py",
        ["other.py"],
        "",
    ) == "subject claims a file that is not in the staged list"
    assert should_block_commit(
        "chore: refresh demo config",
        ["config.py"],
        "+FICTIONAL_API_KEY=demo-only-not-a-real-key\n",
    ) == "diff contains a fictional secret marker; do not commit it"
    assert (
        should_block_commit(
            "feat: add packing.py for Lumen Bay demo",
            ["packing.py"],
            "+print('ok')\n",
        )
        is None
    )

Suggested AI ask (copy and adapt):

git-prompt.txt
Implement is_valid_conventional_subject, message_matches_staged, diff_looks_safe_to_commit, and should_block_commit in git_msg_check.py. Subjects must start with feat/fix/docs/refactor/test/chore plus a colon and a non-empty summary, length 1..72, single line. If the subject says add or added with a path, that path must appear in staged_files. If diff_text contains SECRET_TOKEN= or FICTIONAL_API_KEY=, treat it as unsafe. should_block_commit must return the exact reason strings already used in the tests, or None when allowed. Fictional practice only. Do not invent real credentials.

HOW to finish

HOW
  1. Save git_msg_check.py and test_git_msg_check.py in the same folder.
  2. Run python -m pytest -q test_git_msg_check.py. Expect 4 failed, 2 passed on the starter stubs.
  3. Ask your AI assistant to implement the helpers using the prompt above.
  4. Paste the implementation carefully. Keep the fictional marker names unchanged.
  5. Run pytest again. Expect 6 passed.
  6. Optional: ask an AI for a conventional commit subject for staged file packing.py, then call should_block_commit yourself with a clean diff and with a fictional SECRET_TOKEN= line to feel the guardrail.

Real output before the helper works:

pytest-before.txt
4 failed, 2 passed in 0.02s

Real output after a good helper (seconds can differ slightly):

pytest-after.txt
......                                                                   [100%]
6 passed in 0.01s
Optional completed git_msg_check.py (try it yourself first)

Your AI assistant may structure the regex differently. Any version is fine if all 6 tests pass and the reason strings stay exact.

git_msg_check.py
"""Review helpers for AI-drafted Git commit text (fictional practice only).

Students ask an AI for a conventional commit subject, then prove the helper rules
with pytest. SECRET_TOKEN examples are clearly fictional placeholders, not real keys.
"""
from __future__ import annotations

import re

ALLOWED_TYPES = ("feat", "fix", "docs", "refactor", "test", "chore")
# Fictional teaching marker only — not a real credential.
FICTIONAL_SECRET_MARKERS = ("SECRET_TOKEN=", "FICTIONAL_API_KEY=")

_ADD_FILE = re.compile(r"\badd(?:ed)?\s+([A-Za-z0-9_./-]+)", re.IGNORECASE)


def is_valid_conventional_subject(subject: str) -> bool:
    """Return True when subject looks like 'type: short summary' and length is 1..72."""
    if not isinstance(subject, str):
        return False
    text = subject.strip()
    if not text or len(text) > 72:
        return False
    if "\n" in text:
        return False
    lower = text.lower()
    for prefix in ALLOWED_TYPES:
        head = prefix + ":"
        if lower.startswith(head):
            rest = text[len(head):].strip()
            return bool(rest)
    return False


def message_matches_staged(subject: str, staged_files: list[str]) -> bool:
    """Return False when the subject claims a file was added but that path is not staged."""
    if not isinstance(subject, str) or not isinstance(staged_files, list):
        return False
    staged = set(staged_files)
    for match in _ADD_FILE.finditer(subject):
        claimed = match.group(1)
        if claimed not in staged:
            return False
    return True


def diff_looks_safe_to_commit(diff_text: str) -> bool:
    """Return False when the staged diff text contains a fictional secret marker."""
    if not isinstance(diff_text, str):
        return False
    for marker in FICTIONAL_SECRET_MARKERS:
        if marker in diff_text:
            return False
    return True


def should_block_commit(subject: str, staged_files: list[str], diff_text: str) -> str | None:
    """Return a short reason string when the commit should be blocked, else None."""
    if not is_valid_conventional_subject(subject):
        return "subject must be a conventional commit under 73 characters"
    if not message_matches_staged(subject, staged_files):
        return "subject claims a file that is not in the staged list"
    if not diff_looks_safe_to_commit(diff_text):
        return "diff contains a fictional secret marker; do not commit it"
    return None

Troubleshooting

HOW
  1. Problem: a long subject still passes. Fix: reject any subject longer than 72 characters after strip.
  2. Problem: feat: add secrets.env is allowed when only packing.py is staged. Fix: parse simple add or added path phrases and require the path in the staged list.
  3. Problem: secret blocking never triggers. Fix: search the raw diff text for the exact fictional markers SECRET_TOKEN= and FICTIONAL_API_KEY=.
  4. Error: reason string assertion fails. Fix: copy the three reason strings from the tests exactly, including punctuation.

Practice cards: English and spoken Marathi

Each card below explains one idea on its own, so you can save or revise a single card without reading the whole chapter.

PRACTICE CARDAI Coding

AI drafts, you still gate secrets

Ask the AI for a conventional subject from the staged diff.
Run a helper that blocks fictional SECRET_TOKEN lines before you commit.
Ravindra Bagale · ravindrabagale.com/ai-coding
PRACTICE CARDAI Coding

Claims must match the staged list

If the subject says add packing.py, that path must actually be staged.
A mismatched claim is a signal to edit the message, not to force the commit.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

AI draft करते, secrets तुम्हीच रोखता

Staged diff वरून AI कडून conventional subject मागा.
Commit करण्याआधी काल्पनिक SECRET_TOKEN ओळी रोखणारा helper चालवा.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

दावे staged list शी जुळले पाहिजेत

Subject मध्ये add packing.py असेल, तर तो path खरोखर staged असला पाहिजे.
जुळत नसलेला दावा म्हणजे message संपादित करण्याचा संकेत, जबरदस्तीने commit नाही.
Ravindra Bagale · ravindrabagale.com/ai-coding

Quick quiz

1. What should you paste for a commit message?

The staged diff (git diff --staged), not unrelated files.

2. Who resolves merge conflicts?

You — AI can explain hunks; you edit and test.

3. Name one dangerous command to keep gated

force-push to shared main, hard reset, or clean -fdx.

4. What style of commit subject works well?

Conventional commits: feat/fix/docs/… plus a clear why.

Save tokens and money

SMART AI USE

One staged diff → one message. Do not paste entire repo history into chat to “write better commits.”

Save these cards

INTERVIEW CARDAI Coding

How do you use AI with Git?

Staged diff → conventional commit message.
AI explains conflicts; human edits, tests, and owns push.
Ravindra Bagale · ravindrabagale.com/ai-coding
COMPARISON CARDAI Coding

Message help vs history rewrite

Safe: draft messages and PR summaries.
Risky: force-push / hard reset without explicit OK.
Ravindra Bagale · ravindrabagale.com/ai-coding
REVISION CARDAI Coding

Git + AI in 3

Stage with intent.
Draft message from diff.
You own push and conflict edits.
Ravindra Bagale · ravindrabagale.com/ai-coding