Fetch Pull Rebase Workflow Script in Python
A Python script that automates the git fetch, checkout, and pull with rebase workflow using subprocess.
Python code
35 linesimport subprocess
import sys
def run_git_command(args: list[str]) -> str:
"""Run a git command and return its stdout, or raise on failure."""
result = subprocess.run(
["git", *args],
capture_output=True,
text=True,
check=False,
)
if result.returncode != 0:
print(f"Error: git {' '.join(args)} failed:\n{result.stderr}", file=sys.stderr)
sys.exit(1)
return result.stdout.strip()
def fetch_pull_rebase(remote: str = "origin", branch: str = "main") -> None:
"""Mock a fetch-and-rebase workflow using real git commands."""
print(f"Fetching from {remote}...")
run_git_command(["fetch", remote])
print(f"Checking out {branch}...")
run_git_command(["checkout", branch])
print(f"Pulling with rebase from {remote}/{branch}...")
run_git_command(["pull", "--rebase", remote, branch])
print("Workflow completed successfully.")
if __name__ == "__main__":
# Example invocation — replace with your actual remote/branch as needed
fetch_pull_rebase("origin", "main")
Output
Fetching from origin...
Checking out main...
Pulling with rebase from origin/main...
Workflow completed successfully.
How it works
The script uses subprocess.run to execute git commands and captures stdout/stderr. It checks the return code and exits with an error message if any command fails. The strip() method cleans trailing newlines from output, and the script is structured as reusable functions for clarity.
Common mistakes
- Forgetting to include check=False, which can cause unexpected exceptions.
- Hardcoding remote and branch names instead of making them parameters.
- Not capturing stderr, making it hard to debug failures.
Variations
- Use subprocess.call for simpler cases without capturing output.
- Add a --dry-run flag to print commands without executing them.
Real-world use cases
- Automating daily sync of a local feature branch with upstream changes before starting work.
- Running a rebase-based pull as part of a CI/CD pipeline to ensure clean history before tests.
- Syncing multiple repositories with a single script in a monorepo environment.
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.