|
| 1 | +import argparse |
| 2 | +import subprocess |
| 3 | +import os |
| 4 | +from git import Repo, GitCommandError |
| 5 | + |
| 6 | +def sync_fork(repo_path, remote_url, branch="main", method="merge"): |
| 7 | + try: |
| 8 | + repo = Repo(repo_path) |
| 9 | + origin = repo.remotes.origin |
| 10 | + if "upstream" not in [r.name for r in repo.remotes]: |
| 11 | + upstream_url = f"https://github.com/{remote_url}.git" |
| 12 | + repo.create_remote("upstream", upstream_url) |
| 13 | + print(f"Added upstream: {upstream_url}") |
| 14 | + |
| 15 | + upstream = repo.remotes.upstream |
| 16 | + upstream.fetch() |
| 17 | + print(f"Fetched upstream/{branch}") |
| 18 | + |
| 19 | + repo.git.checkout(branch) |
| 20 | + |
| 21 | + if method == "merge": |
| 22 | + repo.git.merge(f"upstream/{branch}") |
| 23 | + print(f"Merged upstream/{branch} into {branch}") |
| 24 | + else: |
| 25 | + repo.git.rebase(f"upstream/{branch}") |
| 26 | + print(f"Rebased {branch} with upstream/{branch}") |
| 27 | + |
| 28 | + origin.push() |
| 29 | + print("Pushed changes to origin.") |
| 30 | + |
| 31 | + except GitCommandError as e: |
| 32 | + print(f"Git error: {e}") |
| 33 | + except Exception as ex: |
| 34 | + print(f"Error: {ex}") |
| 35 | + |
| 36 | +def main(): |
| 37 | + parser = argparse.ArgumentParser(description="Sync fork with upstream") |
| 38 | + parser.add_argument("--repo", required=True, help="Repo path in format 'owner/repo'") |
| 39 | + parser.add_argument("--token", help="GitHub token (not used in local-only operations)") |
| 40 | + parser.add_argument("--branch", default="main", help="Branch to sync (default: main)") |
| 41 | + parser.add_argument("--method", choices=["merge", "rebase"], default="merge", help="Sync method (merge or rebase)") |
| 42 | + parser.add_argument("--local", default=".", help="Local path to the fork repo") |
| 43 | + args = parser.parse_args() |
| 44 | + |
| 45 | + sync_fork(args.local, args.repo, args.branch, args.method) |
| 46 | + |
| 47 | +if __name__ == "__main__": |
| 48 | + main() |
0 commit comments