How to Squash Commits Range into One in Python

A mock script that displays the last N git commits as a single squashed commit, showing original commit subjects.

Easy Python 3.9+ Aug 9, 2026 Git + Python 16 views 0 copies

Python code

21 lines
Python 3.9+
import subprocess
import re

def squash_last_commits(count):
    """Mock squashing the last N commits into one by display."""
    git_log = subprocess.run(
        ["git", "log", f"-{count}", "--pretty=format:%h %s"],
        capture_output=True, text=True
    )
    if git_log.returncode != 0:
        return "Git command failed. Is this a git repo?"

    commits = git_log.stdout.strip().split("\n")
    if not commits:
        return "No commits found."

    squashed = f"{commits[-1].split()[0]} (squashed of {count}) {commits[-1].split(maxsplit=1)[1]}"
    return "\n".join([squashed, "  + " + "\n  + ".join(c.split(maxsplit=1)[1] for c in commits[1:])])

if __name__ == "__main__":
    print(squash_last_commits(3))

Output

stdout
abc1234 (squashed of 3) Initial commit
  + Add feature
  + Fix bug

How it works

The script uses subprocess.run to call git log with a count and pretty format to capture the last N commit hashes and subjects. It checks the return code and empty output to handle errors gracefully. The first commit (oldest in the range) becomes the squashed commit's subject, and the other commit subjects are listed as bullet points. This is a display-only mock; actual Git squashing requires interactive rebase or other Git commands.

Common mistakes

  • Not checking `returncode` before parsing output.
  • Assuming `git log` output is non-empty, causing index errors.
  • Confusing `git log -n` with `git log` range syntax; this mock uses `-n`.
  • Using `split()` on commit subjects that contain spaces.

Variations

  1. Use `git log -n N --oneline` and parse the output instead of `--pretty=format`.
  2. Actually perform the squash with `git reset --soft HEAD~N` and a new commit.

Real-world use cases

  • Clean up a feature branch before a pull request by squashing WIP commits.
  • Generate a summary of changes for release notes from a commit range.
  • Automate commit hygiene in CI by checking commit count and warning developers.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Git + Python

Related tutorials and quizzes for this topic.