Created
February 8, 2025 00:32
-
-
Save mgsloan/1c8624e854cc6a0744ec94b1f88d410d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# https://claude.site/artifacts/39d84a1a-23fa-498d-a31b-7ada990a85db | |
# https://claude.ai/chat/097db2b0-18a9-4845-9586-f2f4bb10ac8b | |
# | |
# > Please write a python script that git fetches only main without | |
# > switching to it. Then rebase the current branch atop main. All | |
# > the commits after the merge-base w.r.t main should get rebased. | |
# | |
# > Oh, on further thought explicitly querying the merge-base is | |
# > unnecessary, it can just be git rebase main. Also, this should | |
# > check if a main branch exists, and use that, otherwise check if a | |
# > master branch and instead use that. | |
import subprocess | |
import sys | |
def run_git_command(command): | |
"""Execute a git command and return its output""" | |
try: | |
result = subprocess.run(command, | |
check=True, | |
capture_output=True, | |
text=True) | |
return result.stdout.strip() | |
except subprocess.CalledProcessError as e: | |
print(f"Error executing command {' '.join(command)}: {e.stderr}") | |
sys.exit(1) | |
def branch_exists(branch_name): | |
"""Check if a branch exists locally or remotely""" | |
try: | |
run_git_command(['git', 'rev-parse', '--verify', branch_name]) | |
return True | |
except: | |
try: | |
run_git_command(['git', 'rev-parse', '--verify', f'origin/{branch_name}']) | |
return True | |
except: | |
return False | |
def main(): | |
# Determine which default branch to use | |
default_branch = 'main' if branch_exists('main') else 'master' | |
if not branch_exists(default_branch): | |
print(f"Neither 'main' nor 'master' branch found") | |
sys.exit(1) | |
print(f"Using {default_branch} as the default branch") | |
# Fetch the default branch | |
print(f"Fetching {default_branch} branch...") | |
run_git_command(['git', 'fetch', 'origin', f'{default_branch}:{default_branch}']) | |
# Get current branch name | |
current_branch = run_git_command(['git', 'rev-parse', '--abbrev-ref', 'HEAD']) | |
print(f"Current branch: {current_branch}") | |
if current_branch == default_branch: | |
print(f"Already on {default_branch} branch. Nothing to rebase.") | |
return | |
# Perform the rebase | |
print(f"Rebasing {current_branch} onto {default_branch}...") | |
try: | |
run_git_command(['git', 'rebase', default_branch]) | |
print("Rebase completed successfully!") | |
except: | |
print("Rebase encountered conflicts. Please resolve them manually.") | |
sys.exit(1) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment