Reference library

Git + Python

Automate Git from Python — diffs, hooks, release tags, and repo housekeeping.

34 matches
Git + Python easy

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.

git subprocess automation
Python
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.…
15 0 Open
Git + Python easy

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.

bisect binary-search git
Python
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…
17 0 Open
Git + Python easy

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.

git semver versioning
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…
14 0 Open
Git + Python easy

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.

git parsing collections
Python
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):
    "…
14 0 Open
Git + Python easy

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.

mock-api github testing
Python
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…
16 0 Open
Git + Python easy

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.

git merge-conflict file-scanning
Python
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…
14 0 Open
Git + Python easy

Fetch Pull Rebase Workflow Script in Python

A Python script that automates the git fetch, checkout, and pull with rebase workflow using subprocess.

git subprocess automation
Python
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…
16 0 Open
Git + Python easy

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.

git subprocess automation
Python
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,…
11 0 Open
Git + Python easy

Git Signing in Python

Sign and verify Git commits with a mock GPG implementation using HMAC and SHA-256.

git signing hmac
Python
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…
13 0 Open
Git + Python easy

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.

semver git automation
Python
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
       …
13 0 Open
Git + Python easy

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.

git subprocess automation
Python
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,…
12 0 Open
Git + Python easy

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.

git subprocess branch
Python
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,
         …
10 0 Open
Git + Python easy

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.

git subprocess automation
Python
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:
        …
12 0 Open
Git + Python easy

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.

git secrets history
Python
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": …
10 0 Open
Git + Python easy

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.

git lfs geospatial
Python
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 …
11 0 Open
Git + Python easy

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.

git subprocess cli
Python
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…
14 0 Open
Git + Python easy

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.

git subprocess automation
Python
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…
14 0 Open
Git + Python easy

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.

git backup subprocess
Python
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…
12 0 Open
Git + Python easy

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.

git clean dry-run
Python
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…
14 0 Open
Git + Python easy

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.

git worktree mock
Python
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…
14 0 Open
Git + Python easy

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.

git sparse-checkout mocking
Python
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…
10 0 Open
Git + Python easy

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.

unittest.mock subprocess git
Python
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…
13 0 Open
Git + Python easy

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.

git subprocess parsing
Python
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 = …
14 0 Open
Git + Python easy

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.

git subprocess automation
Python
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:
     …
11 0 Open

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.