Git + Python
Automate Git from Python — diffs, hooks, release tags, and repo housekeeping.
Amend Last Commit Message in Python
This script uses subprocess to run `git commit --amend` and update the most recent commit's message in your repository.
import subprocess
import sys
def amend_last_commit_message(new_message: str) -> None:
"""Change the message of the most recent commit."""
result = subprocess.run(
["git", "commit", "--amend", "-m", new_message],
capture_output=True,
text=True,
check=False,
)
if result.…
Bisect Good Bad Automation Script in Python
This Python script implements a binary search to find the first bad version in a list, simulating an automation script for git bisect.
import bisect
def find_first_bad(versions):
"""Given a list of version objects with .is_bad(), find first bad version."""
lo, hi = 0, len(versions)
while lo < hi:
mid = (lo + hi) // 2
if versions[mid].is_bad():
hi = mid
else:
lo = mid + 1
return lo
clas…
Build a Simple Log Graph in Python
Create a basic one-dimensional bar chart from log lines by counting occurrences of leading numeric keys.
import heapq
def log_graph(log_lines: list[str]) -> str:
"""Build a simple per-line, one-dimensional visual graph from log entries."""
counts: dict[int, int] = {}
for line in log_lines:
tokens = line.split()
if tokens:
try:
idx = int(tokens[0])
exce…
Bump Semantic Version Git Tag in Python
Automatically find the latest Git tag and compute the next patch release using semantic versioning (semver) in Python.
from re import match
from subprocess import run
SEMVER_PATTERN = r"^v(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)(?:-(?P<prerelease>[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+(?P<buildmetadata>[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$"
def get_latest_tag() -> str:
result = run(["git", "describe…
Count Unique Contributors from Git Shortlog in Python
Parses git shortlog -sn output to count the number of unique contributors, handling duplicate entries and variable whitespace.
import subprocess
from collections import Counter
# Mock shortlog output as a list of lines (simulating git shortlog -sn output)
MOCK_SHORTLOG = """ 120 Alice Johnson
88 Bob Smith
45 Alice Johnson
30 Carol Williams
25 Bob Smith
10 Dave Brown
"""
def count_contributors_from_shortlog(text):
"…
Create a Mock GitHub Release API in Python for Testing gh CLI
Build an in-memory GitHub Releases API mock that mimics create_release and list_releases for unit testing gh CLI stubs without network calls.
import json
from unittest.mock import patch, Mock
class GitHubReleaseAPI:
"""Mock GitHub Releases API for testing gh CLI stub behavior."""
def __init__(self):
self.releases = {}
self.counter = 1
def create_release(self, repo, tag, name=None, notes=None):
release_id = self…
Detect Merge Conflict Markers in a File with Python
Scan a file line by line to detect Git merge conflict markers (<<<<<<<, =======, >>>>>>>) and report their line numbers with context.
from pathlib import Path
def detect_merge_conflicts(file_path):
conflicts = []
with open(file_path, 'r') as f:
lines = f.readlines()
for i, line in enumerate(lines, 1):
if line.startswith('<<<<<<<'):
conflict_marker = 'conflict start'
conflicts.append((i, confl…
Fetch Pull Rebase Workflow Script in Python
A Python script that automates the git fetch, checkout, and pull with rebase workflow using subprocess.
import subprocess
import sys
def run_git_command(args: list[str]) -> str:
"""Run a git command and return its stdout, or raise on failure."""
result = subprocess.run(
["git", *args],
capture_output=True,
text=True,
check=False,
)
if result.returncode != 0:
prin…
Get Git Status Info in Python
Run git commands from Python to gather branch name, number of changes, total commits, and clean status, returning them as a dict.
import subprocess
import json
from pathlib import Path
def get_git_status(repo_path="."):
"""Return basic git info about a repository as a dict."""
try:
branch = subprocess.check_output(
["git", "branch", "--show-current"],
cwd=repo_path,
stderr=subprocess.DEVNULL,…
Git Signing in Python
Sign and verify Git commits with a mock GPG implementation using HMAC and SHA-256.
import hashlib
import hmac
class GPGMock:
def __init__(self, secret_key):
self.secret_key = secret_key.encode()
def sign_commit(self, commit_message):
"""Mock GPG signing by computing an HMAC of the commit message."""
signature = hmac.new(self.secret_key, commit_message.encode(), hash…
How to Auto-Suggest a SemVer Bump From Git Commit Messages in Python
This code scans Git commit messages (recent or sample) and suggests the next Semantic Versioning bump type — major, minor, patch, or none.
import re
import subprocess
from pathlib import Path
def get_commit_messages(path="."):
"""Read commit messages from a repo or use sample messages."""
if (Path(path) / ".git").exists():
out = subprocess.run(
["git", "-C", path, "log", "--pretty=%s"], capture_output=True, text=True
…
How to Build a Git Helper Class in Python
A beginner-friendly GitHelper class that wraps common git commands (status, log, branch) into reusable Python methods with structured output.
import subprocess
import json
from pathlib import Path
class GitHelper:
def __init__(self, repo_path="."):
self.repo = Path(repo_path)
def run(self, *args):
result = subprocess.run(
["git", *args],
cwd=self.repo,
capture_output=True,
text=True,…
How to Create a Git Branch if it Doesn't Exist in Python
Utility script that checks if a Git branch exists locally and either creates it or checks it out, with error handling.
import subprocess
import sys
def ensure_branch(branch_name):
"""Create a Git branch if it doesn't exist, otherwise checkout it."""
try:
# Check if the branch exists locally
result = subprocess.run(
["git", "branch", "--list", branch_name],
capture_output=True,
…
How to Create a Git Commit with Message Template in Python
Run a git commit from Python using a standardized message template built from a commit type and description.
import subprocess
import sys
def commit_with_template(commit_type: str, description: str) -> None:
message = f"{commit_type}: {description}"
try:
subprocess.run(["git", "commit", "-m", message], check=True)
print(f"Committed: {message}")
except subprocess.CalledProcessError as e:
…
How to Filter Git History to Remove Secret File Entries in Python
A pure-Python mock that filters a repository's history to drop any commit that touched a secret file, so you can plan a cleanup before rewriting Git history.
from pathlib import Path
import json
def filter_history(history, secret_path):
"""Remove entries that touch the secret file."""
return [entry for entry in history if secret_path not in entry["files"]]
if __name__ == "__main__":
repo_history = [
{"commit": "a1b2c3", "message": "Add app", "files": …
How to Generate Git LFS Extension Patterns in Python
This script builds mock Git LFS file patterns for common geospatial extensions and filters them based on compression suffixes.
import itertools
import re
LFS_EXTENSIONS = {".csv", ".geojson", ".tif", ".shp", ".gpkg"}
def build_mock_lfs_pattern(base_name="data_usgs_lidar"):
patterns = []
for ext in sorted(LFS_EXTENSIONS):
for variant in (("", ".lz4"), (".compressed",), (".b", ".a"), ("_v1", ".zip")):
full_pattern …
How to Get Git Status and Log in Python
A beginner-friendly helper that runs git status and git log from Python using subprocess, with safe handling for non-repo directories.
import subprocess
from pathlib import Path
def git_status(path: str = ".") -> str:
"""Return the current git status as a string."""
result = subprocess.run(
["git", "status", "--short"],
cwd=path,
capture_output=True,
text=True
)
return result.stdout.strip() or "No cha…
How to List Changed Files in the Last Git Commit with Python
Runs `git diff --name-only HEAD~1 HEAD` via subprocess to list the names of files changed in the most recent commit.
import subprocess
def list_changed_files():
result = subprocess.run(
["git", "diff", "--name-only", "HEAD~1", "HEAD"],
capture_output=True,
text=True,
check=True
)
files = result.stdout.strip().splitlines()
return files
if __name__ == "__main__":
changed = list_cha…
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 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 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 subprocess.run in Python Tests
Mock subprocess.run to test a Git submodule update command without executing it in your test suite.
import subprocess
from unittest.mock import Mock, patch
def update_submodules():
subprocess.run(["git", "submodule", "update", "--init", "--recursive"], check=True)
with patch("subprocess.run") as mock_run:
mock_run.return_value = Mock(returncode=0)
update_submodules()
mock_run.assert_called_once_wit…
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.