How to stage and commit all changes with Git in Python
Run git add -A and git commit from Python using subprocess to automate staging and committing all file changes in one step.
Python code
20 linesimport subprocess
from pathlib import Path
def stage_and_commit_all(commit_message: str) -> None:
"""Stage all changes and create a commit with the given message."""
repo_root = Path.cwd()
if not (repo_root / ".git").exists():
raise RuntimeError("Not inside a Git repository")
subprocess.run(["git", "add", "-A"], check=True, cwd=repo_root)
subprocess.run(
["git", "commit", "-m", commit_message],
check=True,
cwd=repo_root
)
print(f"Committed all changes with message: '{commit_message}'")
if __name__ == "__main__":
# Example usage
stage_and_commit_all("Auto-commit: staged all changes")
Output
$ python stage_commit.py
Committed all changes with message: 'Auto-commit: staged all changes'
$ git log --oneline -1
abc1234 Auto-commit: staged all changes
How it works
The subprocess.run call executes Git commands in the shell with check=True, which raises CalledProcessError if any command fails — giving you immediate feedback. The cwd=repo_root argument ensures commands run from the repository root even if the script is invoked from a subdirectory. Checking for the .git directory first prevents a confusing Git error when the script runs outside a repo. Using git add -A stages new, modified, and deleted files, so the commit captures the full working tree state.
Common mistakes
- Running `git add` without the `-A` flag, which misses deleted files
- Forgetting `cwd=repo_root` when the script runs from a different directory
- Not checking for `cwd` validity or `.git` existence before invoking Git
Variations
- Use `git commit -a -m` to commit all tracked changes without staging, but new files are not included
- Add `--allow-empty` to the commit command to allow commits when nothing changed
Real-world use cases
- Automating daily checkpoints in a data pipeline by committing processed outputs to a repo.
- Creating a pre-deploy hook that stages and commits config changes before release.
- Building a team onboarding script that commits an initial project scaffold automatically.
Sponsored
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.