Git + Python
Automate Git from Python — diffs, hooks, release tags, and repo housekeeping.
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 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 sparse-checkout Paths in Python
Simulates git sparse-checkout configuration by writing desired paths to the sparse-checkout file without running git commands.
import subprocess
from pathlib import Path
import tempfile
def configure_sparse_checkout(repo_dir: Path, paths: list[str]) -> list[str]:
"""Simulate sparse checkout configuration by returning the paths that would be set."""
sparse_checkout_file = repo_dir / ".git" / "info" / "sparse-checkout"
sparse_chec…
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…
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…
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.