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…
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…
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…
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"},
{"…
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,…
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 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 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 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 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 Parse git status --porcelain Output in Python
This code runs `git status --porcelain` and parses its output into a list of dictionaries with file paths and status descriptions.
import subprocess
def parse_git_status_porcelain():
try:
output = subprocess.check_output(
["git", "status", "--porcelain"],
text=True,
stderr=subprocess.DEVNULL
)
except (subprocess.CalledProcessError, FileNotFoundError):
return []
entries = …
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 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 Stage All Modified Files with git add -u in Python
Runs git add -u from Python to stage all modified and deleted tracked files, then prints the short status.
import subprocess
def stage_all_modified_files(repo_path="."):
"""Run git add -u to stage all modified and deleted tracked files."""
result = subprocess.run(
["git", "add", "-u"],
cwd=repo_path,
capture_output=True,
text=True,
)
if result.returncode != 0:
print…
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…
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.