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.
Python code
16 linesimport 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:
print(f"Commit failed: {e}")
sys.exit(1)
if __name__ == "__main__":
commit_with_template("feat", "add commit message template script")
Output
Committed: feat: add commit message template script
How it works
This script uses subprocess.run to execute the git commit command in the shell. The check=True argument makes the call raise a CalledProcessError if the commit fails, which is caught and printed before exiting with a non-zero status. F-strings build the commit message template as type: description, enforcing a consistent conventional commit style. The if __name__ == "__main__" guard ensures the function only runs when invoked as a script, keeping it reusable as a module.
Common mistakes
- Forgetting `check=True`, so failures are silent and the script exits 0
- Using `git commit -am` with untracked new files, which won't be included
- Not handling the case where there's nothing to commit, causing a CalledProcessError
Variations
- Add `-a` flag to auto-stage modified files with `git commit -am`
- Prompt for the commit type interactively with `input()` for flexibility
Real-world use cases
- Enforce a consistent commit convention across a team by wrapping git commit in a standardized script.
- Automate release commits that follow a version bump pattern, such as 'release: 1.2.0'.
- Build a pre-commit hook that validates or formats commit messages generated by CI tools.
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.