#!/usr/bin/env python3
"""
Git Automator: A simple Python script to automate common Git operations like staging, committing, and pushing.
Usage:
python git_automator.py "Your commit message" [--branch main] [--push] [--pull-first]
Features:
- Stages all changes (git add .)
- Commits with the provided message
- Optionally pulls first (git pull origin <branch>)
- Optionally pushes (git push origin <branch>)
- Checks if in a Git repository
- Handles errors gracefully
Author: Sherlock, built by Trailblazer Labs
"""
import subprocess
import sys
import argparse
import os
def run_git(*args, check_repo=True):
"""
Run a Git command and handle output/errors.
"""
if check_repo:
repo_check = subprocess.run(["git", "rev-parse", "--git-dir"], capture_output=True)
if repo_check.returncode != 0:
print("Error: Not inside a Git repository!")
sys.exit(1)
try:
result = subprocess.run(["git"] + list(args), capture_output=True, text=True, check=True)
if result.stdout.strip():
print(result.stdout.strip())
return result.stdout
except subprocess.CalledProcessError as e:
print(f"Git error (exit code {e.returncode}): {e.stderr.strip()}")
sys.exit(1)
def main():
parser = argparse.ArgumentParser(description="Automate Git commit and push operations.")
parser.add_argument("message", nargs="?", help="Commit message (quoted if multi-word)")
parser.add_argument("--branch", "-b", default="main", help="Branch name (default: main)")
parser.add_argument("--push", "-p", action="store_true", help="Push after commit")
parser.add_argument("--pull-first", action="store_true", help="Pull before committing")
parser.add_argument("--no-stage", action="store_true", help="Skip staging (git add .)")
args = parser.parse_args()
if not args.message:
args.message = input("Enter commit message: ").strip()
if not args.message:
print("No commit message provided. Exiting.")
sys.exit(1)
print(f"🔍 Preparing Git operations for branch: {args.branch}")
print(f"📝 Commit message: {args.message}")
# Optional pull first
if args.pull_first:
print("📥 Pulling latest changes...")
run_git("pull", "origin", args.branch, check_repo=False)
# Stage changes (unless skipped)
if not args.no_stage:
print("📂 Staging all changes...")
run_git("add", ".", check_repo=False)
# Commit
print("✅ Committing...")
run_git("commit", "-m", args.message, check_repo=False)
# Optional push
if args.push:
print("🚀 Pushing to origin...")
run_git("push", "origin", args.branch, check_repo=False)
print("✨ All operations completed successfully!")
if __name__ == "__main__":
main()
Quick Start
- Save as
git_automator.py and make executable: chmod +x git_automator.py
- Run examples:
./git_automator.py "Fix typos and update docs"
./git_automator.py "Add new feature" --push --branch develop --pull-first
./git_automator.py "Quick fix" --no-stage # Skip staging
Notes:
- Safety: Always stages all changes (
git add .). Use --no-stage if you staged manually.
- Interactive mode: If no message provided, it prompts you.
- Error handling: Checks for Git repo and command failures.
- Customization: Edit defaults or extend as needed (e.g., add
git status preview).
Elementary, my dear coder—your Git workflow is now automated! 🕵️♂️