Git + Python
Automate Git from Python — diffs, hooks, release tags, and repo housekeeping.
Find the Commit That Introduced a String in Git History Using Python
Use git log -S with Python subprocess to find the earliest commit that introduced a specific string across your repository history.
import subprocess
import sys
def find_introducing_commit(repo_path: str, search_string: str, file_glob: str = "*") -> str:
"""Find the first commit that introduced a given string in a git repository."""
result = subprocess.run(
["git", "-C", repo_path, "log", "--all", "--oneline", "-S", search_string…
Generate CHANGELOG from Conventional Commits in Python
Parse your git log for conventional commits (feat, fix) and produce a simple Markdown CHANGELOG with grouped features and bug fixes.
import subprocess
import re
import sys
from collections import OrderedDict
CONVENTIONAL_COMMIT = re.compile(
r"^(?P<type>feat|fix|chore|docs|refactor|perf|test|build|ci|style)(?:\((?P<scope>[^)]+)\))?: (?P<description>.+)"
)
def get_git_log():
return subprocess.run(
["git", "log", "--format=%s"],
…
Generate Release Notes Markdown from PR Titles in Python
Generate structured Markdown release notes from a list of pull request titles using conventional commit types.
import json
from datetime import datetime, timezone
PRS = [
{"title": "feat: add user login", "number": 12, "merged_at": "2025-01-10"},
{"title": "fix: resolve payment timeout", "number": 13, "merged_at": "2025-01-11"},
{"title": "chore: bump dependencies", "number": 14, "merged_at": "2025-01-12"},
{"…
How to Archive a Repository as a ZIP in Python
Create a ZIP archive of a repository directory with a mock export, skipping hidden files and __pycache__ folders.
import zipfile
import io
import os
from pathlib import Path
def archive_repo_mock(repo_path, output_path="repo_archive.zip"):
"""Create a zip archive of a repository directory (mock export)."""
repo = Path(repo_path)
if not repo.exists():
raise FileNotFoundError(f"Repository not found: {repo}")
…
How to Build a Branch Protection Audit Mock API in Python
A mock HTTP API that serves branch protection rules for repositories and audits them for compliance, built with Python's standard library.
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs
REPOSITORIES = {
"alpha": {
"default_branch": "main",
"branches": ["main", "develop", "feature-x"],
"protection_rules": {
"main": {"required_reviews": 2, "dismiss_…
How to Format Git Patch Series as an MBOX File in Python
Generate a patch-series mbox file from commit metadata with numbered [PATCH nnn/nnn] subjects and a Git-style footer.
import re
from pathlib import Path
def format_patch_series_mbox(commits, output_path="series.mbox"):
entries = []
for idx, commit in enumerate(commits, start=1):
subject = commit["subject"]
author = commit["author"]
email = commit["email"]
date = commit["date"]
body = …
How to Generate Release Notes from Git Commit Messages in Python
This script fetches recent Git commit messages using conventional commit prefixes (feat, fix, etc.), categorizes them, and prints formatted release notes with today's date.
import subprocess
import re
from datetime import datetime
def get_git_log(since_tag="HEAD~10", format_str="%s"):
"""Retrieve commit messages from git log."""
try:
result = subprocess.run(
["git", "log", f"--since={since_tag}", f"--format={format_str}"],
capture_output=True,
…
How to Get Current Git Branch Name in Python with Mock Subprocess
Mocks the subprocess call to reliably test the current git branch name retrieval using GitPython.
import subprocess
from unittest.mock import patch, MagicMock
from git import Repo
import os
def get_current_branch(repo_path="."):
"""Get the current branch name of a git repository."""
repo = Repo(repo_path)
return repo.active_branch.name
if __name__ == "__main__":
# Mock subprocess to control the…
How to Make a Git Commit Heatmap by Hour in Python
Parse a git log output and count commits by weekday and hour, then print a compact heatmap table.
import re
from collections import Counter
from datetime import datetime
def parse_commits(log_text):
"""Parse git log lines and count commits by (weekday, hour)."""
pattern = re.compile(r"^Date:\s+(.+)$")
counts = Counter()
for line in log_text.splitlines():
match = pattern.match(line)
…
How to Mock Git Cherry-Pick in Python for Tests
Mock the `repo.git.cherry_pick` method with `unittest.mock` to test a Git cherry-pick helper without a real repository.
from unittest.mock import patch, MagicMock
class GitCherryPicker:
def __init__(self):
self.applied_commits = []
def cherry_pick(self, commit_hash, repo):
try:
result = repo.git.cherry_pick(commit_hash)
self.applied_commits.append(commit_hash)
return f"A…
How to Mock Git Pre-commit Hooks (black and ruff) in Python
Mock subprocess to test black and ruff pre-commit commands without actually running them, verifying exit codes.
import sys
import subprocess
from unittest.mock import patch
def run_hook(command: list[str]) -> int:
with patch("subprocess.run") as mock_run:
mock_run.return_value.returncode = 0
mock_run.return_value.stdout = f"Mocked: {' '.join(command)}"
result = subprocess.run(command, capture_output…
How to Mock Git Stash and Pop in Python
Mock Git stash, apply, and pop operations using unittest.mock so you can test Git automation without touching a real repository.
import git
from unittest.mock import Mock, patch
def stash_and_pop(repo):
"""Mock a stash operation and then pop it back."""
repo.git.stash("save", "WIP: temp changes")
stashed_output = repo.git.stash("list")
# Simulate the stash was applied, then pop
repo.git.stash("apply", "stash@{0}")
…
How to Mock open() in Python Using unittest.mock.patch
This code shows how to use unittest.mock.patch with mock_open to test a function that checks if a Git patch can be reverse-applied by reading file content.
import unittest
from unittest.mock import patch, mock_open
def apply_reverse_check(file_path, expected_patch):
"""
Check if a patch can be reverse-applied by comparing file content
with the expected patch's reverse result.
"""
try:
with open(file_path, "r") as f:
content = f.r…
How to generate and parse an interactive rebase TODO list in Python
Generate a Git interactive rebase TODO list from commit data and parse it back into structured records.
import re
from collections import namedtuple
Commit = namedtuple("Commit", ["hash", "subject"])
def generate_rebase_todo(commits, action="pick"):
todo_lines = []
for i, commit in enumerate(commits):
if i == 0 and action == "reword":
todo_lines.append(f"reword {commit.hash} {commit.subject…
Mock smtplib to Test Patch Email Series in Python
Simulate sending a numbered series of patch emails with smtplib and verify the calls using unittest.mock without a real mail server.
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from unittest.mock import patch, Mock
def send_patch_series(subject_prefix, patches, smtp_host="localhost", smtp_port=25):
"""Simulate sending a series of patch emails."""
for i, patch_content in enumerate(patch…
Python Script to Rotate a Leaked API Key
A checklist-driven Python script that scans a codebase for a leaked API key, replaces it with a new one, and prints a step-by-step rotation checklist.
#!/usr/bin/env python3
"""Checklist for rotating a leaked API key across a codebase."""
import re
from pathlib import Path
CHECKLIST = [
"Identify all files containing the leaked key",
"Generate a new key with sufficient entropy",
"Update the secret storage/CI environment variables",
"Replace the ol…
Browse by section
Each section groups closely related Python snippets.
Git + Python — Python code examples
What you will find here
This page collects git + python snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.