dongjoon-hyun commented on code in PR #60472:
URL: https://github.com/apache/spark/pull/60472#discussion_r4620879968
##########
dev/merge_spark_pr.py:
##########
@@ -948,9 +991,88 @@ def comment(self, pr_num, body):
print_error("Failed to comment on PR #%s: HTTP %s %s" % (pr_num,
e.code, e.reason))
return None
+ def _api(self, url, method="GET", payload=None):
+ data = None if payload is None else json.dumps(payload).encode("utf-8")
+ request = Request(url, data=data, method=method)
+ request.add_header("Content-Type", "application/json")
+ request.add_header("Accept", "application/vnd.github+json")
+ if GITHUB_OAUTH_KEY:
+ request.add_header("Authorization", "token %s" % GITHUB_OAUTH_KEY)
+ return json.load(urlopen(request))
+
+ def open_pr(self, base, head):
+ """The open PR from `head` against `base`, or None -- also when the
lookup fails.
+
+ >>> from contextlib import redirect_stdout
+ >>> from io import StringIO
+ >>> from unittest.mock import patch
+ >>> gh = GitHub()
+ >>> with patch.object(gh, "_api", return_value=[{"n": 1}, {"n": 2}])
as api:
+ ... gh.open_pr("branch-4.2", "me:b")
+ {'n': 1}
+ >>> api.call_args.args[0].split("?")[1]
+ 'state=open&base=branch-4.2&head=me%3Ab'
+ >>> with patch.object(gh, "_api", side_effect=OSError("down")),
redirect_stdout(StringIO()):
+ ... found = gh.open_pr("branch-4.2", "me:b")
+ >>> found is None
+ True
+ """
+ query = urlencode({"state": "open", "base": base, "head": head})
+ try:
+ found = self._api("%s/pulls?%s" % (GITHUB_API_BASE, query))
+ except Exception as e:
+ print_error("Could not look up open PRs from %s: %s" % (head, e))
+ return None
+ return found[0] if found else None
+
+ def create_pr(self, base, head, title, body):
+ """Open a draft PR from `head`, or refresh the open one; None on
failure or no token.
+
+ >>> from contextlib import redirect_stdout
+ >>> from io import StringIO
+ >>> from unittest.mock import patch
+ >>> def create(found, fails=False, token="t"):
+ ... calls = []
+ ... def api(url, method="GET", payload=None):
+ ... calls.append((url.split("/")[-1], method, payload))
+ ... if fails and method != "GET":
+ ... raise OSError("HTTP 422")
+ ... return found if method == "GET" else {"html_url": "pr"}
+ ... gh = GitHub()
+ ... with (
+ ... patch.object(gh, "_api", side_effect=api),
+ ... patch.dict(GitHub.create_pr.__globals__,
GITHUB_OAUTH_KEY=token),
+ ... redirect_stdout(StringIO()),
+ ... ):
+ ... return gh.create_pr("branch-4.2", "me:b", "T", "B"), calls
+ >>> url, method, payload = create([])[1][1]
+ >>> url, method, payload["draft"], payload["head"], payload["base"]
+ ('pulls', 'POST', True, 'me:b', 'branch-4.2')
+ >>> create([{"url": "u/pulls/5", "html_url": "h"}])[1][1]
+ ('5', 'PATCH', {'title': 'T', 'body': 'B'})
+ >>> create([], fails=True)[0], create([], token="")
+ (None, (None, []))
+ """
+ # Opening a PR is a write and needs auth; without a token, skip rather
than 401.
+ if not GITHUB_OAUTH_KEY:
+ print_error("GITHUB_OAUTH_KEY is not set; skipping the backport
PR.")
+ return None
+ existing = self.open_pr(base, head)
+ try:
+ if existing:
+ # A retry force-pushed the branch. Refresh the PR too:
merge_pr turns its body
+ # into the commit message.
+ print("Updating the open backport PR %s." %
existing["html_url"])
+ return self._api(existing["url"], "PATCH", {"title": title,
"body": body})
+ payload = {"title": title, "head": head, "base": base, "body":
body, "draft": True}
Review Comment:
**[1] A backport PR opened by `[p]` cannot be merged by this script until
someone marks it ready.**
`create_pr` always opens the PR with `"draft": True`, but `main()` stops on
any draft PR before it reads the body (`fail("Cannot merge a draft PR #%s: %s"
% ...)` at L5179). So the flow in the description, where the backport PR "is
later merged with this script", needs a manual "Ready for review" click first,
and nothing tells the committer: not the `Backport PR for #%s against %s` line,
not `_manual_backport_pr` (which also asks for a draft), and not the PR
description. CI already runs on the push to the fork (`build_main.yml` runs on
every pushed branch), so the draft state is not what triggers it. Could the PR
be opened as a regular one? Otherwise, could those messages say so, or `main()`
accept a draft that `_backport_of` recognizes?
##########
dev/merge_spark_pr.py:
##########
@@ -2027,10 +3140,17 @@ def cherry_pick(
f"Valid branches: {valid_branches}. Please try again."
)
- def pick(ref):
- return _do_cherry_pick(pr_num, merge_hash, ref, record)
+ def pick(ref, pending_sibling=None):
+ return _do_cherry_pick(
+ pr_num, merge_hash, ref, title=title,
pending_sibling=pending_sibling, record=record
+ )
sibling_x = _upstream_first_sibling(target_ref, pick_ref, branch_names,
already_picked)
+ if sibling_x in pending:
Review Comment:
**[3] Landing a branch with `[d]` leaves its open backport PR behind.**
`pending` is consulted here only for `sibling_x`. When the typed `pick_ref`
itself has an open backport PR from an earlier run, nothing mentions it, and
answering `[d]` pushes the pick to apache. `_PickLedger.record` then moves the
branch to landed and the merge summary says "merged into branch-4.2", but the
backport PR stays open with the same change, and whoever merges it later with
this script merges a change that is already on the branch. Could the pick name
the open backport PR when `pick_ref in pending`, and `[d]` then close it, or at
least print that it should be closed?
##########
dev/merge_spark_pr.py:
##########
@@ -948,9 +991,88 @@ def comment(self, pr_num, body):
print_error("Failed to comment on PR #%s: HTTP %s %s" % (pr_num,
e.code, e.reason))
return None
+ def _api(self, url, method="GET", payload=None):
Review Comment:
**[6] nit: `close_pr` and `comment` could use `_api`.**
`_api` builds the same `Request` with the same `Content-Type`, `Accept` and
`Authorization` headers that `close_pr` and `comment` still build inline, so a
change to the auth header now has three places to go. `close_pr` and `comment`
could call `self._api(...)` inside their existing `try`/`except HTTPError`.
##########
dev/merge_spark_pr.py:
##########
@@ -1573,6 +1787,45 @@ def maybe_binding_policy_warning(ref: str, base_head:
str) -> None:
continue_maybe("Push to %s anyway? (experts only!)" % ref, True)
+# First line of a backport PR body opened by _land_via_fork; the rest is the
pick's message.
+_BACKPORT_MARKER_RE = re.compile(r"^Backport-of: #(\d+)\n\n")
+
+
+def _backport_of(body, head_ref, target_ref):
+ """(original PR, original message, primary author) if this is a backport
PR, else None.
+
+ Needs the marker, a merge footer for that same PR, and the script's own
head branch for
+ this target, so a body that merely quotes a footer, or pastes one into a
PR against
+ master, is not taken for a backport. Mentions are stripped as merge_pr
does for any
+ body, keeping the @ inside the footer's e-mail addresses.
+
+ >>> footer = "Closes #7 from a/b.\\n\\nAuthored-by: A
<[email protected]>\\nSigned-off-by: C <[email protected]>"
+ >>> message = "Fix it.\\n\\n" + footer + "\\n(cherry picked from commit
abc)"
+ >>> crlf = "Backport-of: #7\\r\\n\\r\\n" + message.replace("\\n", "\\r\\n")
+ >>> _backport_of(crlf, "backport-pr7-branch-4.2", "branch-4.2")[::2]
+ (7, 'A <[email protected]>')
+ >>> _backport_of("Backport-of: #7\\n\\nHi @bob.\\n\\n" + message,
"backport-pr7-branch-4.2",
+ ... "branch-4.2")[1].splitlines()[0]
+ 'Hi bob.'
+ >>> [_backport_of(b, h, "branch-4.2") for b, h in (
+ ... ("Backport-of: #8\\n\\n" + message, "backport-pr8-branch-4.2"), #
footer is #7's
+ ... ("Backport-of: #7\\n\\n" + message, "my-feature"), # not the
script's branch
+ ... (message, "backport-pr7-branch-4.2"),
+ ... (None, "backport-pr7-branch-4.2"),
+ ... )]
+ [None, None, None, None]
+ """
+ body = (body or "").replace("\r\n", "\n")
+ m = _BACKPORT_MARKER_RE.match(body)
+ if not m or head_ref != _backport_pr_branch(m.group(1), target_ref):
+ return None
+ message = re.sub(r"(?<![\w.+-])@", "", body[m.end() :]).strip()
Review Comment:
**[7] nit: the mention-stripping regex is written twice, and the soft check
depends on both copies matching.**
`(?<![\w.+-])@` appears here and in `_pick_message` (L2154), and the soft
check in `merge_pr` (L2041) compares the outputs of the two. If one copy
changes and the other does not, every backport merge hits the "matches none of
its commits" prompt. A module-level compiled regex, or a small helper used by
both, would keep them in sync.
##########
dev/merge_spark_pr.py:
##########
@@ -4177,56 +5305,53 @@ def record(pair):
print("title\t%s\nsource\t%s\ntarget\t%s\nurl\t%s" % (title, pr_repo_desc,
target_ref, url))
continue_maybe("Proceed with merging pull request #%s?" % pr_num)
- merged_refs = [target_ref]
-
merge_hash = merge_pr(pr_num, target_ref, title, body, pr_repo_desc,
pr_author, co_authors)
- # Ordered (branch, commit_hash) pairs for the merge comment: the merge
sink first,
- # then each cherry-pick target as it is picked.
- merged_commits = [(target_ref, merge_hash)]
-
- # merged_refs drives both the next prompt default and the already_picked
set passed to
- # cherry_pick, so each grows with every cherry-pick -- including branches
consumed by the
- # Upstream-First two-branch path inside cherry_pick (e.g. picking
branch-M.x + branch-M.N
- # in a single prompt). It starts with target_ref, the merge sink, never to
be re-picked.
- def record(pair):
- merged_refs.append(pair[0])
- merged_commits.append(pair)
-
+ # target_ref, the merge sink, is never to be re-picked.
+ picks = _PickLedger([target_ref])
pick_prompt = "Would you like to pick %s into another branch?" % merge_hash
# Always record the merge summary for what actually landed, even if a later
# cherry-pick is aborted or cancelled: the merge into the target branch has
# already been pushed, so cancelling a backport must not drop that line.
try:
+ # Seeded inside the try: the fork lookups can stall, and the merge is
already pushed.
+ # A merged backport PR inherits the original's branches: the default
skips them, and
+ # [p] on a typed pending one updates its PR.
+ if backport:
+ picks = _seed_picks(backport[0], target_ref, branch_names)
while get_input(f"\n{pick_prompt} (y/N): ", ["y", "n", ""]) == "y":
- default = default_pick_branch(branch_names, tuple(merged_refs))
+ default = default_pick_branch(branch_names, picks.seen())
if default is None:
- print("Every known release branch already contains #%s;
nothing to pick." % pr_num)
+ print(
+ "Every release branch has #%s or a backport PR of it;
nothing to pick." % pr_num
+ )
break
cherry_pick(
pr_num,
merge_hash,
default,
branch_names,
target_ref,
- already_picked=tuple(merged_refs),
- record=record,
+ already_picked=tuple(picks.landed),
+ title=title,
+ pending=picks.pending,
+ record=lambda pair: picks.record([pair]),
)
finally:
- if merged_commits:
- # The "Closes #N" keyword in the commit message only auto-closes
the PR when the
- # commit lands on the default branch. For merges into other
branches (e.g.
- # branch-X.Y backport PRs), GitHub leaves the PR open, so close it
through the API.
- pr_state = get_json("%s/pulls/%s" % (GITHUB_API_BASE,
pr_num)).get("state")
- if pr_state != "closed":
- close_message = "PR #%s is still open after push; closing it
explicitly." % pr_num
- print("\n%s\n" % bold(close_message))
- github.close_pr(pr_num)
- # Record every branch that successfully received the change on the
PR.
- post_merge_comment(pr_num, merged_commits)
+ # The "Closes #N" keyword in the commit message only auto-closes the
PR when the
+ # commit lands on the default branch. For merges into other branches
(e.g.
+ # branch-X.Y backport PRs), GitHub leaves the PR open, so close it
through the API.
+ pr_state = get_json("%s/pulls/%s" % (GITHUB_API_BASE,
pr_num)).get("state")
+ if pr_state != "closed":
+ close_message = "PR #%s is still open after push; closing it
explicitly." % pr_num
+ print("\n%s\n" % bold(close_message))
+ github.close_pr(pr_num)
+ # Record every branch that received the change, or has a backport PR,
on the PR:
+ # the merge sink first, then each cherry-pick as it was picked.
+ post_merge_comment(pr_num, [(target_ref, merge_hash)] + picks.commits)
Review Comment:
**[5] The original PR's merge summary keeps showing a merged backport as
pending.**
When `[p]` opens a backport PR, the summary on the original PR records `-
backport PR against branch-4.2 <url>`. When that backport PR is later merged
with this script, this call posts the `merged into branch-4.2` line only on the
backport PR. So the original PR's page, which `post_merge_comment` is meant to
make the merge traceable from, never shows that the change landed on
branch-4.2. When `backport` is set, could the merge also post a short line on
the original PR, `backport[0]`?
##########
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", ""]},
Review Comment:
**[4] Without the flag, answering N at the push prompt no longer stops the
run.**
With `--prompt-for-branches-during-backport` off, the prompt reads as
before, but its answers changed:
- before this PR, `Push to apache?` was a `continue_maybe` without `cherry`,
so N exited the run through `fail("Okay, exiting")`. Now N maps to `"s"`: the
pick is discarded and the run moves on to "Would you like to pick ... into
another branch?";
- a failed push used to exit through `fail("Exception while pushing: ...")`.
Now it asks the same question again.
So the default path changes too, although the flag keeps the new prompts
opt-in. If skipping is the intended new default, could the PR description
mention it? Otherwise, the flag-off branch here could keep `continue_maybe` and
`fail`.
##########
dev/merge_spark_pr.py:
##########
@@ -960,25 +1082,104 @@ def comment(self, pr_num, body):
print("DRY-RUN: would post the following comment on PR #%s:\n%s" %
(pr_num, body))
return None
+ def create_pr(self, base, head, title, body):
+ # Return a fake PR so the 'p' path takes its success branch in a dry
run (and the
+ # merge comment logs a backport-PR line rather than the "PR not
opened" fallback).
+ fake_url = "https://github.com/apache/spark/pull/DRY-RUN"
+ print(
+ "DRY-RUN: would open a draft backport PR against %s from %s:\n
title: %s\n body: %s"
+ % (base, head, title, body)
+ )
+ return {"html_url": fake_url, "number": 0}
+
# Set in main(): GitHub() normally, DryRunGitHub() for a dry run. Module-level
default so the
# top-level except handler and any early failure path have a usable client.
github = GitHub()
def post_merge_comment(pr_num, merged_commits):
- """Post a comment on the PR recording every branch the change landed on
and a
- link to the resulting commit, so the merge is traceable from the PR page.
+ """Post a comment on the PR recording every branch the change landed on
(with a
+ commit link) or has a pending backport for, so the merge is traceable from
the PR page.
+
+ ``merged_commits`` is an ordered list of (branch, marker) pairs, the merge
sink
+ first followed by each cherry-pick target, markers as in _do_cherry_pick:
a pushed
+ commit hash, a backport PR URL, or a `fork:<owner>:<branch>` marker.
+
+ >>> from contextlib import redirect_stdout
+ >>> from io import StringIO
+ >>> from unittest.mock import patch
+ >>> captured = {}
+ >>> def fake_comment(num, body):
+ ... captured["num"] = num
+ ... captured["body"] = body
+ >>> with (
+ ... patch.object(github, "comment", side_effect=fake_comment),
+ ... redirect_stdout(StringIO()),
+ ... ):
+ ... post_merge_comment(42, [("master", "abc123"), ("branch-4.2",
"def456")])
+ >>> captured["num"]
+ 42
+ >>> "- merged into master https://github.com/apache/spark/commit/abc123"
in captured["body"]
+ True
+ >>> "- merged into branch-4.2
https://github.com/apache/spark/commit/def456" in captured["body"]
+ True
+
+ A backport-PR marker (a URL) renders as a PR link, not a commit link:
+
+ >>> with (
+ ... patch.object(github, "comment", side_effect=fake_comment),
+ ... redirect_stdout(StringIO()),
+ ... ):
+ ... post_merge_comment(
+ ... 42, [("master", "abc123"), ("branch-4.2",
"https://github.com/apache/spark/pull/99")])
Review Comment:
**[8] nit: two new doctest lines are over 100 characters.**
L1135 and L1136 are 102 characters long. `ruff check` passes because the
repository's ruff configuration does not select E501, but the other new lines
keep to 100 columns. For example:
```python
... post_merge_comment(42, [("master", "abc123"),
... ("branch-4.2",
"https://github.com/apache/spark/pull/99")])
>>> url = "https://github.com/apache/spark/pull/99"
>>> "- backport PR against branch-4.2 " + url in captured["body"]
```
##########
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:
**[2] `[p]` on a branch that already has a backport PR force-pushes over the
commits pushed to that PR.**
The earlier
[discussion](https://github.com/apache/spark/pull/60472#discussion_r4577039816)
settled that `[p]` on a typed pending branch updates its open PR. That update
also drops any commit pushed to the PR after it opened, such as the conflict
fixups that the new `Co-authored-by` crediting in `merge_pr` is meant for. For
example:
- an earlier run opened the branch-4.2 backport PR of `#7`;
- its opener pushed a fixup to `backport-pr7-branch-4.2` after CI failed;
- a later run on `#7` types branch-4.2 and answers `[p]`.
This line then force-pushes a fresh pick over the branch, the fixup
disappears from the open PR without any message, and `create_pr` only PATCHes
the title and body. Could `[p]` ask before overwriting when `pick_ref` is
already in `pending`, or fetch that fork branch first and refuse when it has
commits other than an earlier pick?
--
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]