holdenk commented on code in PR #60472:
URL: https://github.com/apache/spark/pull/60472#discussion_r4620977917
##########
dev/merge_spark_pr.py:
##########
@@ -1747,67 +2130,581 @@ def merge_pr(pr_num, target_ref, title, body,
pr_repo_desc, pr_author, co_author
return merge_hash
-def _do_cherry_pick(pr_num, merge_hash, pick_ref, record=None):
- """Cherry-pick `merge_hash` onto `pick_ref` and push.
+def _set_skip_trailer(skip):
+ """Amend HEAD so it carries the skip trailer exactly when `skip`; leave it
be otherwise,
+ so a retried push sends the same commit. Reads HEAD afresh, keeping any
amend made since.
+ """
+ current = git.run(["git", "log", "-1", "--format=%B"])
+ wanted = remove_inherited_post_merge_ci_skip(current)
+ if skip:
+ wanted = append_post_merge_ci_skip(wanted)
+ # %B ends in one more newline than the helpers return.
+ if wanted.rstrip("\n") != current.rstrip("\n"):
+ amend_commit_message(wanted)
+
+
+def _pick_message(commit_body):
+ """A commit body as _backport_of reads it from the PR body: no
skip-checks, mentions, or
+ edge whitespace.
+
+ >>> _pick_message("Fix @bob\\n\\n\\nskip-checks: true\\n")
+ 'Fix bob'
+ """
+ body = remove_inherited_post_merge_ci_skip(commit_body.replace("\r\n",
"\n").strip() + "\n")
+ return re.sub(r"(?<![\w.+-])@", "", body).strip()
+
+
+def _backport_pr_branch(pr_num, pick_ref):
+ """Fork branch name for a backport PR: stable, PR-traceable,
branch-suffixed.
+
+ >>> _backport_pr_branch(123, "branch-4.2")
+ 'backport-pr123-branch-4.2'
+ >>> _backport_pr_branch(9, "branch-3.5")
+ 'backport-pr9-branch-3.5'
+ """
+ return "backport-pr%s-%s" % (pr_num, pick_ref)
+
+
+def _backport_pr_title(pick_ref, title):
+ """PR title for a backport PR: the merged title with its version tag set
to the target.
+
+ The tag goes where Title.parse expects one, so the script can still merge
the result.
+ Revert/Reapply and other unparseable titles stay verbatim.
+
+ >>> _backport_pr_title("branch-4.2", "[SPARK-1234][SQL] Fix a thing")
+ '[SPARK-1234][4.2][SQL] Fix a thing'
+ >>> _backport_pr_title("branch-4.x", "[SPARK-1234][4.X][SQL] Fix a thing")
+ '[SPARK-1234][4.X][SQL] Fix a thing'
+ >>> _backport_pr_title("branch-4.2", "[SPARK-1234][4.X][SQL] Fix a thing")
+ '[SPARK-1234][4.2][SQL] Fix a thing'
+ >>> _backport_pr_title("branch-4.2", "[MINOR] Fix typo")
+ '[MINOR][4.2] Fix typo'
+ >>> _backport_pr_title("branch-4.2-preview", "[MINOR] Fix typo")
+ '[MINOR] Fix typo'
+ >>> _backport_pr_title("branch-4.2", 'Revert "[SPARK-1234][SQL] Fix"')
+ 'Revert "[SPARK-1234][SQL] Fix"'
+ >>> all(
+ ... Title.parse(_backport_pr_title("branch-4.2", t))
+ ... for t in ("[SPARK-1234][SQL] Fix", "[MINOR] Fix typo")
+ ... )
+ True
+ """
+ try:
+ parsed = Title.parse(title)
+ except ValueError:
+ return title
+ version = pick_ref[len("branch-") :].upper()
+ if not _VERSION_TAG_RE.match(version):
+ return title
+ others = [c for c in parsed.components if not _VERSION_TAG_RE.match(c)]
+ return str(Title(parsed.leading, [version] + others, parsed.text))
+
+
+def _remote_repo(url):
+ """`owner/repo` named by a git remote URL, or None.
+
+ >>> _remote_repo("[email protected]:me/spark.git")
+ 'me/spark'
+ >>> _remote_repo("https://github.com/apache/spark.git")
+ 'apache/spark'
+ >>> _remote_repo("ssh://[email protected]:443/me/spark.git")
+ 'me/spark'
+ >>> _remote_repo("git@github-work:me/spark")
+ 'me/spark'
+ >>> _remote_repo("https://gitbox.apache.org/repos/asf/spark.git")
+ 'asf/spark'
+ >>> _remote_repo("") is None
+ True
+ """
+ m = re.search(r"[:/]([^/:]+)/([^/:]+?)(?:\.git)?/?$", url)
+ return "%s/%s" % m.groups() if m else None
+
+
+def _remote_url(name):
+ try:
+ return git.run(["git", "remote", "get-url", name]).strip()
+ except Exception:
+ return ""
+
+
+def _remote_push_urls(name):
+ # Where `git push <name>` really goes: pushurl and pushInsteadOf apply.
+ try:
+ return git.run(["git", "remote", "get-url", "--push", "--all",
name]).split()
+ except Exception:
+ return []
+
+
+def _fork_owner(pushing=True):
+ """GitHub owner of the fork remote, for a backport PR's `head`. ValueError
if unusable.
+
+ The fork is checked by the repository its URL names, not the remote name:
an `origin` that
+ was never repointed off apache/spark would otherwise get the backport
branch and the PR.
+ A read-only caller passes pushing=False to skip the push-URL check.
+
+ The env knobs are pinned so a committer's own settings cannot fail these
at startup:
+
+ >>> from unittest.mock import patch
+ >>> def remotes(fork, owner=""):
+ ... urls = {"apache": "https://gitbox.apache.org/repos/asf/spark.git",
+ ... "apache-github": "https://github.com/apache/spark.git",
"origin": fork}
+ ... return patch.multiple(sys.modules[__name__], _remote_url=urls.get,
FORK_OWNER=owner,
+ ... FORK_REMOTE_NAME="origin",
PUSH_REMOTE_NAME="apache",
+ ... PR_REMOTE_NAME="apache-github")
+ >>> def owner_of(fork, owner="", push=None):
+ ... pushes = patch.object(sys.modules[__name__], "_remote_push_urls",
+ ... lambda name: [fork] if push is None else
push)
+ ... with remotes(fork, owner), pushes:
+ ... try:
+ ... return _fork_owner()
+ ... except ValueError as e:
+ ... return "refused" if "is the Apache repo" in str(e) else
str(e)
+ >>> owner_of("ssh://[email protected]:443/me/spark.git")
+ 'me'
+ >>> [owner_of(f, owner="me") for f in (
+ ... "[email protected]:apache/spark.git",
+ ... "https://gitbox.apache.org/repos/asf/spark.git",
+ ... "git@gh:Apache/Spark",
+ ... )]
+ ['refused', 'refused', 'refused']
+
+ The branch goes to the push URLs, so they must name the fork too:
+
+ >>> apache = "[email protected]:apache/spark.git"
+ >>> "pushes to " + apache in owner_of("[email protected]:me/spark.git",
push=[apache])
+ True
+ >>> owner_of("[email protected]:me/spark.git",
push=["https://github.com/Me/spark.git"])
+ 'me'
+
+ A github.com URL names its owner; FORK_OWNER only fills in for a host
alias:
+
+ >>> owner_of("[email protected]:me/spark.git", owner="someone-else")
+ 'me'
+ >>> owner_of("git@gh-alias:me/spark.git", owner="Me")
+ 'Me'
+ >>> owner_of("git@gh-alias:me/spark.git").startswith("Cannot tell the
GitHub owner")
+ True
+ """
+ url = _remote_url(FORK_REMOTE_NAME)
+ repo = _remote_repo(url)
+ if repo is None:
+ raise ValueError(
+ "No usable %s remote (%r). Set FORK_REMOTE_NAME to your fork's
remote."
+ % (FORK_REMOTE_NAME, url)
+ )
+ apache = {"apache/spark"} | {
+ (_remote_repo(_remote_url(r)) or "").lower() for r in
(PUSH_REMOTE_NAME, PR_REMOTE_NAME)
+ }
+ if repo.lower() in apache:
+ raise ValueError(
+ "%s remote (%s) is the Apache repo, not a fork. Set
FORK_REMOTE_NAME to your "
+ "fork's remote." % (FORK_REMOTE_NAME, url)
+ )
+ for push_url in _remote_push_urls(FORK_REMOTE_NAME) if pushing else []:
+ if (_remote_repo(push_url) or "").lower() != repo.lower():
+ raise ValueError(
+ "%s remote fetches from %s but pushes to %s. Point both at
your fork."
+ % (FORK_REMOTE_NAME, url, push_url)
+ )
+ if "github.com" in url:
+ return repo.split("/")[0]
+ if FORK_OWNER:
+ return FORK_OWNER
+ raise ValueError(
+ "Cannot tell the GitHub owner of %s remote (%s); set FORK_OWNER to
your GitHub login."
+ % (FORK_REMOTE_NAME, url)
+ )
+
+
+def _landing_choice(pick_branch_name, pick_ref):
+ """Ask how a finished pick lands: [d]irect push, [p] fork + draft PR, or
[s]kip (default).
+
+ [p] is offered only with --prompt-for-branches-during-backport; without it
the question is
+ the plain push-or-skip one, whose y/n answers map to "d"/"s".
+
+ >>> from contextlib import redirect_stdout
+ >>> from io import StringIO
+ >>> from unittest.mock import patch
+ >>> def choose(answers, enabled):
+ ... out = StringIO()
+ ... with (
+ ... patch.dict(_landing_choice.__globals__,
+ ... PROMPT_FOR_BRANCHES_DURING_BACKPORT=enabled),
+ ... patch("builtins.input", side_effect=answers),
redirect_stdout(out),
+ ... ):
+ ... return _landing_choice("PR_TOOL_PICK_PR_1_BRANCH-4.2",
"branch-4.2")
+ >>> choose([""], True), choose(["p"], True), choose([""], False),
choose(["y"], False)
+ ('s', 'p', 's', 'd')
+
+ Without the flag, [p] is not accepted:
+
+ >>> choose(["p", "n"], False)
+ 's'
+ """
+ if not PROMPT_FOR_BRANCHES_DURING_BACKPORT:
+ return get_input(
+ "Pick complete (local ref %s). Push to %s/%s? (y/N): "
+ % (pick_branch_name, PUSH_REMOTE_NAME, pick_ref),
+ {"d": ["y", "yes"], "s": ["n", "no", ""]},
+ )
+ return get_input(
+ "Pick complete (local ref %s). How should it land?\n"
+ " [d] Push directly to %s/%s\n"
+ " [p] Push to your fork (%s) and open a draft backport PR against %s
(for CI)\n"
+ " [s] Skip this branch (default)\n"
+ "Choose [d/p/s]: "
+ % (pick_branch_name, PUSH_REMOTE_NAME, pick_ref, FORK_REMOTE_NAME,
pick_ref),
+ {"d": ["d", "direct"], "p": ["p", "pr"], "s": ["s", "skip", ""]},
+ )
- Returns the (pushed ref, pushed commit hash) pair, which `record` also
gets, right after
- the push and before the cleanup that can raise. Raises `SkipCherryPick`
when the
- committer declines to resolve a conflict, after aborting the pick, or
declines a pre-push
- check. The pick is committed by then, so nothing is aborted: it and its
temporary branch
- are discarded, and uncommitted edits must be stashed first (see
continue_maybe).
- Both pre-push checks run once, in order, before the push prompt; the
binding-policy one
- gets the target branch and its tip from before the pick. A declined check
pushes nothing:
+def _land_via_fork(pr_num, pick_ref, pick_branch_name, title):
+ """Push the pick to the fork and open a draft backport PR against
`pick_ref`.
+
+ Returns the PR URL, or a `fork:<owner>:<branch>` marker if the push worked
but the PR did
+ not open. Either failure offers _manual_backport_pr, whose pasted URL
wins. Returns None,
+ having pushed nothing, when the fork is unusable or the push fails and no
URL was pasted,
+ so the caller can retry, push directly, or skip. The fork branch is
script-owned and
+ force-pushed (only after _fork_owner vetted the destination), so a retry
updates it.
+
+ >>> from contextlib import redirect_stdout
+ >>> from io import StringIO
+ >>> from unittest.mock import Mock, patch
+ >>> def land(owner, created, push_error=None, pasted="", pr=7,
body="body\\n"):
+ ... with (
+ ... patch("builtins.input", return_value=pasted),
+ ... patch.multiple(
+ ... sys.modules[__name__],
_fork_owner=Mock(side_effect=[owner]),
+ ... FORK_REMOTE_NAME="origin",
+ ... ),
+ ... patch.object(git, "push", side_effect=push_error) as push,
+ ... patch.object(git, "run", return_value=body),
+ ... patch.object(github, "create_pr", return_value=created) as
create,
+ ... redirect_stdout(StringIO()),
+ ... ):
+ ... marker = _land_via_fork(pr, "branch-4.2", "PICK",
"[SPARK-1][SQL] Fix")
+ ... return marker, push.call_args_list, create.call_args_list
+ >>> marker, pushes, creates = land("me", {"html_url":
"https://github.com/apache/spark/pull/9"})
+ >>> marker
+ 'https://github.com/apache/spark/pull/9'
+ >>> pushes
+ [call('origin', 'PICK', 'backport-pr7-branch-4.2', force=True)]
+ >>> creates[0].args[:3]
+ ('branch-4.2', 'me:backport-pr7-branch-4.2', '[SPARK-1][4.2][SQL] Fix')
+ >>> creates[0].args[3]
+ 'Backport-of: #7\\n\\nbody'
+ >>> land("me", None)[0]
+ 'fork:me:backport-pr7-branch-4.2'
+ >>> land("me", None, push_error=OSError("rejected"))
+ (None, [call('origin', 'PICK', 'backport-pr7-branch-4.2', force=True)], [])
+ >>> land(ValueError("origin is the Apache repo"), None)
+ (None, [], [])
+ >>> land("me", None, pasted="https://github.com/apache/spark/pull/10")[0]
+ 'https://github.com/apache/spark/pull/10'
+
+ From a run on #9, itself a merged backport of #7, the new PR still names
#7:
+
+ >>> footer = "Closes #7 from a/b.\\n\\nAuthored-by: A
<[email protected]>\\nBackport-PR: #9\\n"
+ >>> _, pushes, creates = land("me", None, pr=9, body=footer)
+ >>> pushes[0].args[2], creates[0].args[3].splitlines()[0]
+ ('backport-pr7-branch-4.2', 'Backport-of: #7')
+ >>> _backport_of(creates[0].args[3], "backport-pr7-branch-4.2",
"branch-4.2")[::2]
+ (7, 'A <[email protected]>')
+
+ The pick's skip-checks trailer is not carried into the PR body:
+
+ >>> land("me", None, body="body\\n\\n\\nskip-checks:
true\\n")[2][0].args[3]
+ 'Backport-of: #7\\n\\nbody'
+
+ The dry-run seam fakes both effects, so a dry run takes the success branch:
+
+ >>> with redirect_stdout(StringIO()) as out:
+ ... DryRunGit().push("origin", "PICK", "backport-pr7-branch-4.2",
force=True)
+ ... created = DryRunGitHub().create_pr("branch-4.2", "me:b", "t", "b")
+ >>> created["html_url"]
+ 'https://github.com/apache/spark/pull/DRY-RUN'
+ >>> "would push PICK to origin:backport-pr7-branch-4.2 (forced)" in
out.getvalue()
+ True
+ """
+ # The pick's own message is what GitHub would prefill for a single-commit
branch. Its @s
+ # were stripped when the merge commit was built, so it fires no mention
mails. The marker
+ # lets merge_pr keep the original message, footer and author when this PR
is merged.
+ # merge_pr adds the skip trailer afresh, per the commit count when the PR
merges.
+ pr_body = remove_inherited_post_merge_ci_skip(
+ git.run(["git", "log", "-1", "--format=%b", pick_branch_name])
+ ).strip()
+ # A run on a merged backport PR picks a commit whose footer names the
original PR, and
+ # _backport_of only accepts a marker naming that one.
+ pr_num = merge_footer_pr(pr_body) or pr_num
+ pr_body = "Backport-of: #%s\n\n%s" % (pr_num, pr_body)
+ backport_branch = _backport_pr_branch(pr_num, pick_ref)
+ pr_title = _backport_pr_title(pick_ref, title)
+ try:
+ owner = _fork_owner()
+ git.push(FORK_REMOTE_NAME, pick_branch_name, backport_branch,
force=True)
Review Comment:
Sounds reasonable
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]