Git + Python
Automate Git from Python — diffs, hooks, release tags, and repo housekeeping.
How to Make a Shallow Clone of an Object in Python
Demonstrates using copy.copy() to create a shallow clone of a Python object, showing how nested mutable data is shared while top-level attributes are independent.
import copy
class Config:
def __init__(self):
self.settings = {"volume": 50}
self.user = "admin"
def demonstrate_shallow_copy():
original = Config()
shallow = copy.copy(original)
# Mutating nested object is visible in both (shallow copy share it)
shallow.settings["volume"] = 90…
How to Mirror a Bare Git Repository Backup in Python
Run a git clone --bare subprocess to create a timestamped bare-repo backup folder with error handling.
import subprocess
import shlex
from pathlib import Path
from datetime import datetime
def mirror_bare_repo(source_url: str, backup_dir: str) -> str:
"""Mirror a bare git repository to a timestamped backup folder."""
backup_path = Path(backup_dir)
backup_path.mkdir(parents=True, exist_ok=True)
timest…
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 Clean Dry Run in Python
Simulate the output of `git clean -n` in Python to preview which untracked files would be removed without actually deleting them.
import subprocess
import sys
def mock_git_clean_dry_run(untracked_files):
"""Simulate `git clean -n` for a given list of untracked files."""
if not untracked_files:
print("No untracked files to remove.")
return
print("Would remove:")
for file in untracked_files:
print(f" {fil…
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 Git Worktree Creation in Python
Create a mock Git worktree setup with parallel branch directories and state files for testing or simulation.
import os
import tempfile
from pathlib import Path
def create_mock_worktree(base_dir: Path, branches: list[str]) -> dict[str, Path]:
"""
Mock Git worktree creation: creates parallel directories for each branch
under the base directory, simulating independent worktrees.
"""
worktrees = {}
for b…
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…
How to Push Git Tags to a Remote with Python
Push specified git tags (or all tags) to a remote repository using Python's subprocess module with error handling.
import subprocess
import sys
def push_tags_to_remote(remote: str = "origin", tags: list[str] | None = None) -> None:
"""
Push git tags to a remote repository.
If no tags are given, push all local tags.
"""
if tags:
subprocess.run(["git", "push", remote, *tags], check=True)
else:
…
How to Revert a Commit and Create a New Revert Commit in Python
Demonstrates a mock Git repository that creates a new revert commit on top of the current head when reverting an existing commit.
class GitCommit:
"""Minimal mock of a git commit for demonstrating revert behavior."""
def __init__(self, sha, message):
self.sha = sha
self.message = message
self.parent = None
class GitRepository:
"""Mock repository tracking a simple commit chain."""
def __init__(self):
…
How to Run Git Commands from Python with subprocess
This helper runs `git status --short` and `git log --oneline` from Python, captures their output, and returns readable strings with error handling for non-repo directories.
import subprocess
def git_status():
"""Return a short, human-readable git status."""
try:
output = subprocess.run(
["git", "status", "--short"],
capture_output=True,
text=True,
check=True,
).stdout.strip()
return output if output else "W…
How to compute diff stats (insertions, deletions) in Python
Parses a git diff text and counts the number of added and removed lines to produce insertion and deletion stats.
import re
from collections import Counter
def parse_diff(diff_text):
insertions = 0
deletions = 0
for line in diff_text.splitlines():
if line.startswith("+") and not line.startswith("+++"):
insertions += 1
elif line.startswith("-") and not line.startswith("---"):
d…
How to detect secrets in git history with Python
Scan a git history export file for common secret patterns using regex and Python.
import re
from pathlib import Path
def scan_history_for_secrets(history_file: str) -> list:
"""Scan a git history export for potential secrets using regex patterns."""
patterns = {
"AWS Access Key": r"AKIA[0-9A-Z]{16}",
"GitHub Token": r"gh[pousr]_[0-9A-Za-z]{36,255}",
"Private Key": …
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…
How to sync a fork with upstream in Python
Run git fetch and merge commands from Python with subprocess to sync a forked repository with upstream/main.
import subprocess
import sys
def sync_fork_with_upstream():
"""Simulate syncing a forked repo with upstream via git commands."""
# Mock git operations: pretend to fetch from upstream and merge into main
fetch_result = subprocess.run(
["git", "fetch", "upstream"],
capture_output=True, tex…
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…
Upload Assets to GitHub Release with Python Mock
Simulates uploading binary and text assets to a GitHub release using a mock server, returning structured metadata for each upload.
import json
import os
import tempfile
from datetime import datetime
class ReleaseUploader:
"""Simulates uploading assets to a release with a mock server."""
def __init__(self, owner: str, repo: str, tag: str):
self.owner = owner
self.repo = repo
self.tag = tag
self.uploade…
Verify Git tag signatures with HMAC in Python
Create and verify deterministic HMAC-SHA256 signatures for git tags using the Python standard library.
import hashlib
import hmac
def sign_tag(tag: str, secret_key: str) -> str:
"""Create a deterministic HMAC signature for a tag."""
message = tag.encode("utf-8")
key = secret_key.encode("utf-8")
return hmac.new(key, message, hashlib.sha256).hexdigest()
def verify_signed_tag(tag: str, signature: str, …
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.