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.
Python code
21 linesimport 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
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
- Use `git log -n N --oneline` and parse the output instead of `--pretty=format`.
- 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
More from Git + Python
- Amend Last Commit Message in Python easy
- Bisect Good Bad Automation Script in Python easy
- Build a Simple Log Graph in Python easy
- Bump Semantic Version Git Tag in Python easy
- Count Unique Contributors from Git Shortlog in Python easy
- Create a Mock GitHub Release API in Python for Testing gh CLI easy
Keep learning
Related tutorials and quizzes for this topic.