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
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
- 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
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.
# 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
- Stage deliberately (
git add -p) so the message matches the change. - Paste
git diff --staged(or use Copilot / Cursor commit helpers if your plan has them). - Edit the subject if the AI is vague (“fix stuff” → real intent).
- On conflicts: paste one hunk with markers; ask “explain both sides; recommend a merge keeping X behaviour.” Then you edit the file.
- Re-run tests after resolving conflicts before you commit.
| Safe | Dangerous without explicit OK |
|---|---|
| Draft commit message / PR summary | git push --force to shared main |
| Suggest branch name | git reset --hard on uncommitted work you need |
| Explain conflict markers | git clean -fdx wiping local files |
| Summarise recent commits | Rewriting published history on a shared branch |
Settings / tool tips
- 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).
- Claude Code CLI: you can ask it to draft a message from the staged diff; still run
git commityourself unless you knowingly allow it. - Project rules: “conventional commits; never commit .env; never force-push main.”
- 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.
नमस्कार मित्रांनो. या सरावात तुम्ही एक छोटा Python helper ठेवता जो AI Git साठी काय draft करेल ते तपासतो. Helper conventional commit subjects तपासतो, staged नसलेल्या file बद्दल add असा दावा करणारा subject नाकारतो, आणि स्पष्टपणे काल्पनिक SECRET_TOKEN ओळ नाकारतो. तुम्ही Lumen Bay packing बदलासाठी AI कडून commit subject मागता, आणि नंतर pytest ने नियम सिद्ध करता. Live chapter मध्ये messages साठी prompt कसे द्यायचे आणि conflicts कसे हाताळायचे ते आले आहे. इथे तुम्ही workflow शेजारी ठेवता येणारे automated guardrails सरावता. Token strings काल्पनिक teaching placeholders म्हणून चिन्हांकित आहेत, खरे credentials नाहीत.
नमस्ते दोस्तों. इस अभ्यास में आप एक छोटा Python helper रखते हो जो देखता है कि AI Git के लिए क्या draft कर सकती है. Helper conventional commit subjects जांचता है, जो subject किसी बिना-staged file के बारे में add का दावा करे उसे अस्वीकार करता है, और साफ़ काल्पनिक SECRET_TOKEN पंक्ति को रोकता है. आप Lumen Bay packing बदलाव के लिए AI से commit subject मांगते हो, फिर pytest से नियम साबित करते हो. Live chapter में messages के लिए prompt और conflicts पहले आ चुके हैं. यहां आप workflow के साथ रखने लायक automated guardrails का अभ्यास करते हो. Token strings काल्पनिक teaching placeholders हैं, असली 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.
Ravindra Bagale's Tip – मराठी
SECRET_TOKEN किंवा API key सारखी दिसणारी ओळ demo repo मध्येही commit करू नका. Staged diff वरून AI कडून commit message मागा, आणि git commit टाइप करण्याआधी secrets आणि चुकीचे file दावे नाकारणारा helper किंवा checklist चालवा.
Ravindra Bagale's Tip – हिंदी
SECRET_TOKEN या API key जैसी दिखने वाली पंक्ति को demo repo में भी commit मत करो. Staged diff से AI से commit message मांगो, और git commit टाइप करने से पहले secrets और गलत file दावों को रोकने वाला helper या checklist चलाओ।
SECRET_TOKEN= and FICTIONAL_API_KEY= are labeled practice placeholders, not real credentials. Passing these tests proves only the listed helper rules.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
- Create a project folder and open a terminal inside it.
- Create a virtual environment: on macOS or Linux run
python3 -m venv .venv. On Windows runpy -3 -m venv .venv. - 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. - Install pytest inside the virtual environment:
python -m pip install pytest.
Starter git_msg_check.py (behaviour stubs fail several tests on purpose):
"""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):
"""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.txtImplement 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
- Save
git_msg_check.pyandtest_git_msg_check.pyin the same folder. - Run
python -m pytest -q test_git_msg_check.py. Expect 4 failed, 2 passed on the starter stubs. - Ask your AI assistant to implement the helpers using the prompt above.
- Paste the implementation carefully. Keep the fictional marker names unchanged.
- Run pytest again. Expect 6 passed.
- Optional: ask an AI for a conventional commit subject for staged file
packing.py, then callshould_block_commityourself with a clean diff and with a fictionalSECRET_TOKEN=line to feel the guardrail.
Real output before the helper works:
pytest-before.txt4 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
- Problem: a long subject still passes. Fix: reject any subject longer than 72 characters after strip.
- Problem:
feat: add secrets.envis allowed when onlypacking.pyis staged. Fix: parse simple add or added path phrases and require the path in the staged list. - Problem: secret blocking never triggers. Fix: search the raw diff text for the exact fictional markers
SECRET_TOKEN=andFICTIONAL_API_KEY=. - 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.
AI drafts, you still gate secrets
Claims must match the staged list
AI draft करते, secrets तुम्हीच रोखता
दावे staged list शी जुळले पाहिजेत
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
One staged diff → one message. Do not paste entire repo history into chat to “write better commits.”