|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import logging |
| 4 | +import re |
| 5 | + |
| 6 | +import ghstack.github |
| 7 | +import ghstack.github_utils |
| 8 | +import ghstack.shell |
| 9 | + |
| 10 | + |
| 11 | +def main( |
| 12 | + pull_request: str, |
| 13 | + github: ghstack.github.GitHubEndpoint, |
| 14 | + sh: ghstack.shell.Shell, |
| 15 | + remote_name: str, |
| 16 | + stack: bool = False, |
| 17 | +) -> None: |
| 18 | + |
| 19 | + params = ghstack.github_utils.parse_pull_request( |
| 20 | + pull_request, sh=sh, remote_name=remote_name |
| 21 | + ) |
| 22 | + head_ref = github.get_head_ref(**params) |
| 23 | + orig_ref = re.sub(r"/head$", "/orig", head_ref) |
| 24 | + if orig_ref == head_ref: |
| 25 | + logging.warning( |
| 26 | + "The ref {} doesn't look like a ghstack reference".format(head_ref) |
| 27 | + ) |
| 28 | + |
| 29 | + sh.git("fetch", "--prune", remote_name) |
| 30 | + |
| 31 | + if stack: |
| 32 | + # Cherry-pick the entire stack from merge-base to the commit |
| 33 | + remote_orig_ref = remote_name + "/" + orig_ref |
| 34 | + |
| 35 | + # Find the merge-base with the main branch |
| 36 | + repo_info = ghstack.github_utils.get_github_repo_info( |
| 37 | + github=github, |
| 38 | + sh=sh, |
| 39 | + github_url=params["github_url"], |
| 40 | + remote_name=remote_name, |
| 41 | + ) |
| 42 | + main_branch = f"{remote_name}/{repo_info['default_branch']}" |
| 43 | + |
| 44 | + # Get merge-base between the commit and main branch |
| 45 | + merge_base = sh.git("merge-base", main_branch, remote_orig_ref).strip() |
| 46 | + |
| 47 | + # Get all commits from merge-base to the target commit |
| 48 | + commit_list = ( |
| 49 | + sh.git("rev-list", "--reverse", f"{merge_base}..{remote_orig_ref}") |
| 50 | + .strip() |
| 51 | + .split("\n") |
| 52 | + ) |
| 53 | + |
| 54 | + if not commit_list or commit_list == [""]: |
| 55 | + raise RuntimeError("No commits found to cherry-pick in the specified range") |
| 56 | + |
| 57 | + logging.info(f"Cherry-picking {len(commit_list)} commits from stack") |
| 58 | + for commit in commit_list: |
| 59 | + sh.git("cherry-pick", commit) |
| 60 | + logging.info(f"Cherry-picked {commit}") |
| 61 | + else: |
| 62 | + # Cherry-pick just the single commit |
| 63 | + remote_orig_ref = remote_name + "/" + orig_ref |
| 64 | + sh.git("cherry-pick", remote_orig_ref) |
| 65 | + logging.info(f"Cherry-picked {orig_ref}") |
0 commit comments