spark-test commented on code in PR #60472:
URL: https://github.com/apache/spark/pull/60472#discussion_r4576372737
##########
dev/merge_spark_pr.py:
##########
@@ -1209,12 +1872,437 @@ 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):
- """Cherry-pick `merge_hash` onto `pick_ref` and push.
+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.
- Returns the (pushed ref, pushed commit hash) pair. Raises `SkipCherryPick`
if the
- cherry-pick conflicts and the committer declines to resolve it, after
attempting to
- abort the cherry-pick and restore the working tree.
+ >>> _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).
+
+ >>> from contextlib import redirect_stdout
+ >>> from io import StringIO
+ >>> from unittest.mock import patch
+ >>> with patch("builtins.input", return_value=""),
redirect_stdout(StringIO()):
+ ... choice = _landing_choice("PR_TOOL_PICK_PR_1_BRANCH-4.2",
"branch-4.2")
+ >>> choice
+ 's'
+ """
+ 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", ""]},
+ )
+
+
+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:
**Non-blocking (P2):** This push sends the commit that `_do_cherry_pick`
already amended with `skip-checks: true`. The trailer is added before the
landing prompt whenever sampling skips post-merge CI, which for branch-4.x is
about nine picks in ten, and only the PR body drops it. With the trailer on the
head commit, GitHub skips the fork's push-triggered Build, so the draft PR
never gets the CI run `[p]` exists for. `update_build_status.js` then posts the
generic 'PR build setup requires attention' check, which points at enabling
Actions rather than at the trailer. The sampling warnings printed earlier
describe a direct push, so nothing tells you to amend and push again. The
trailer only matters for a commit pushed to apache, and `merge_pr` decides it
again when the backport PR merges. Adding it only in the `[d]` branch, right
before `git.push(PUSH_REMOTE_NAME, ...)`, would keep it off every fork head.
**Verification:**
- **Regression:** A branch-4.x pick for which sampling chooses to skip
post-merge CI, answered [p], pushes a commit whose message does not end in the
skip-checks trailer, and the backport PR body is still the pick's message
without it.
- **Behavior:** The same sampled pick answered [d] pushes a commit whose
message ends in exactly one skip-checks trailer after two empty lines,
including when an earlier [d] push failed or an earlier [p] attempt pushed
nothing before the committer chose [d].
- **Behavior:** Answering [p] after a failed [d] attempt still pushes the
pick without the trailer.
- **Compatibility:** A pick that sampling lets run post-merge CI, or a pick
into a branch with no sampling interval, pushes the same commit message with
either answer as it did before the change.
##########
dev/merge_spark_pr.py:
##########
@@ -3518,53 +4781,47 @@ def main():
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.
+ # target_ref, the merge sink, is never to be re-picked.
+ picks = _PickLedger([target_ref])
Review Comment:
**Non-blocking (P2):** Only the merged branch seeds the ledger here. Say
`merge_pr` has just merged a recognized backport of PR N into branch-4.2, and N
still has an open backport PR for branch-4.x on your fork. This loop doesn't
know about it. A run on the already-merged backport PR would find it through
`pending_fork_backports(original, ...)` and keep branch-4.x out of the default.
Here, the next-pick default is branch-4.x. If you accept it and answer `[p]`,
`_land_via_fork` names the branch after N's footer and force-pushes over
`backport-pr<N>-branch-4.x`. `create_pr` then PATCHes that open PR's title and
body, and nothing warns before the push. Any fixups pushed to the PR after CI
are gone from its branch. Answering `[d]` instead lands branch-4.x directly and
leaves its backport PR open. Seeding this ledger from the original PR the way
the already-merged path does would treat those branches as pending here too.
**Recommended change:** Factor the already-merged path's seeding into one
helper (the original PR from the merge commit's footer; that PR's footer
branches as landed; its open fork backport PRs from pending_fork_backports as
pending, minus landed ones; the printed lists) and call it from the merge path
after merge_pr when the merged PR was a recognized backport, so the merge loop
starts from the original's landed and pending branches, as a run on the merged
backport PR does. A regular PR's first merge keeps seeding only the merged
branch.
**Why this works:** main() learns that the merge was a backport from the
same inputs merge_pr used (_backport_of on the PR body, head ref and target) or
from the merge commit's footer naming another PR, and passes the original PR's
number to the shared helper; the already-merged path calls the same helper with
the found merge commit's message.
**Scope:** Seed the merge loop's ledger from the original PR after a
backport merge, sharing the already-merged path's seeding.
**Risks:** After a recognized backport merge, the next-pick default also
skips release branches where the original already landed, and the JIRA update
counts them as landed, as a run on the merged backport PR already does; this
drops only a pick that would come up empty and a fix version the original's
earlier merge already recorded. Every backport merge now makes the fork lookups
a run on the merged backport PR makes, one git ls-remote on your fork and one
GitHub read per matching branch, also when no pick follows; they are
best-effort and print one line when the fork is unusable. Removing the helper
call from the merge path restores the merged-branch-only seeding.
**Constraints:** The already-merged path keeps its seeding, printed lists
and lookups. A regular PR's first merge makes no fork or footer lookups. The
merge comment still lists only the merge and this run's picks.
**Exclusions:**
- Whether the merge of a maintenance-branch backport PR should itself ask
the maintenance-only confirmation stays your decision; this repair only makes
the original's branches available to such a check.
**Success:** After merging a recognized backport PR of #N, every branch
where #N has an open backport PR on the running committer's fork is pending in
that run and is not offered as the next-pick default. Such a branch is picked
only when the committer types it, and [p] then updates its open backport PR the
way a retry does. Branches where #N already landed are kept out of the default
and count as landed, as in a run on the merged backport PR. Merging a PR that
is not a backport makes no fork or footer lookups and offers the same default
as before.
**Verification:**
- **Regression:** Merging a recognized backport PR while its original has
open backport PRs on the running committer's fork for other release branches
keeps every such branch out of the next-pick default, and the run lists each as
having a pending backport PR.
- **Behavior:** Typing one of those branches at the pick prompt still picks
it, and answering [p] updates its open backport PR the way a retry does.
- **Behavior:** Merging a recognized backport PR whose original already
landed on another release branch keeps that branch out of the next-pick default
and passes it to the JIRA update as landed.
- **Compatibility:** Merging a PR that is not a backport makes no fork or
footer lookups and offers the same next-pick default as before the change.
##########
dev/merge_spark_pr.py:
##########
@@ -971,9 +1127,10 @@ class Git:
and local commands (fetch, checkout, merge, commit, cherry-pick,
rev-parse, config, branch
bookkeeping); those are safe even in a dry run because the merge and
cherry-picks happen on
the throwaway PR_TOOL_* branches that clean_up removes. ``push`` is the
only command that
- mutates the shared repo at PUSH_REMOTE_NAME, so it is the one method
DryRunGit overrides;
- everything else it inherits and runs for real, keeping conflict detection
and the computed
- merge hash realistic. main() constructs Git() normally and DryRunGit() for
a dry run.
+ touches a remote (PUSH_REMOTE_NAME, or the fork for a backport PR), so it
is the one method
Review Comment:
**Nit (P3):** `run` also contacts remotes. `merge_pr` and `_do_cherry_pick`
fetch from the PR and push remotes (the same docstring lists fetch among
`run`'s commands), and `pending_fork_backports` now runs `git ls-remote`
against the fork, dry runs included. What justifies overriding only `push` is
that it is the only command that writes to a remote:
```suggestion
writes to a remote (PUSH_REMOTE_NAME, or the fork for a backport PR), so
it is the one method
```
**Verification:**
- **Inspection:** The Git class docstring says push is the only command that
writes to a remote and no longer says it is the only one that touches one.
##########
dev/merge_spark_pr.py:
##########
@@ -1270,14 +2358,43 @@ def _do_cherry_pick(pr_num, merge_hash, pick_ref):
if updated_message != raw_message:
amend_commit_message(updated_message)
- continue_maybe(
- "Pick complete (local ref %s). Push to %s?" % (pick_branch_name,
PUSH_REMOTE_NAME)
- )
+ maybe_binding_policy_warning(pick_ref, pick_head)
+ maybe_compile_check(pick_branch_name)
- try:
- git.push(PUSH_REMOTE_NAME, pick_branch_name, pick_ref)
- except Exception as e:
- fail("Exception while pushing: %s" % e)
+ while True:
+ choice = _landing_choice(pick_branch_name, pick_ref)
+ if choice == "s":
+ # Restore the original checkout and drop the temp PICK_PR_*
branches, as the
+ # continue_maybe decline path does; otherwise a later pick of the
same ref fails
+ # when `git fetch` tries to update the checked-out branch.
+ print("Skipping this branch; the merge continues.")
+ clean_up()
+ raise SkipCherryPick()
+ if choice == "p":
+ marker = _land_via_fork(pr_num, pick_ref, pick_branch_name, title)
+ if marker:
+ clean_up()
+ return pick_ref, marker
+ # Nothing was pushed and the pick is intact: retry, push directly,
or skip.
+ continue
+ if pending_sibling:
+ sibling, marker = pending_sibling
+ prompt = (
+ "Upstream-First: %s has only a pending backport (%s). Push %s
directly as a "
+ "%s-only maintenance fix?" % (sibling, marker, pick_ref,
pick_ref)
+ )
+ if get_input(f"{prompt} (y/N): ", ["y", "n", ""]) != "y":
+ continue
+ try:
+ git.push(PUSH_REMOTE_NAME, pick_branch_name, pick_ref)
+ break
+ except Exception as e:
+ # Likely a race with another push during the compile. The pick is
stale then, so
+ # only [p] or [s] can get out, but neither loses it.
Review Comment:
**Nit (P3):** `[s]` calls `clean_up()`, which runs `git branch -D` on every
`PR_TOOL_*` branch. That deletes the pick along with any hand-resolved
conflict, as `_manual_backport_pr` warns ('the local ref goes away with it').
Only `[p]` keeps it:
```suggestion
# only [p] (which keeps it, on the fork) or [s] (which discards
it) can get out.
```
**Verification:**
- **Inspection:** The comment after a failed direct push says that only [p]
keeps the pick and that [s] discards it.
##########
dev/spark_merge_footer.py:
##########
@@ -193,6 +240,8 @@ def branches_with_merge_footer(pr_num, remote, run_git):
"--fixed-strings",
"--grep",
merge_footer_trailer(pr_num),
+ "--grep",
+ backport_pr_trailer(pr_num),
Review Comment:
**Nit (P3):** This second `--grep` is what finds the commit that merged
backport PR M, since that commit's footer closes the original PR. But
`branches_with_merge_footer` has no doctest, and this module's doctests only
run when the file is executed by hand. If the line were dropped,
`dev/pr_merge_status.py M` would print 'closed without merging' for a merged
backport PR, and nothing would fail. A doctest with a fake `run_git` that
checks both patterns and the branch reported for M would pin it.
**Verification:**
- **Regression:** The branch scan searches for both the Closes footer and
the Backport-PR trailer of the requested PR, and reports under backport PR #M a
branch whose commit merged it, though that commit's footer names the original
PR.
- **Behavior:** A commit that only quotes a Backport-PR line outside its
final paragraph is not reported.
##########
dev/merge_spark_pr.py:
##########
@@ -1035,6 +1240,392 @@ def clean_up():
git.run("git branch -D %s" % branch)
+def maybe_compile_check(ref_name: str) -> None:
+ """Offer to run a clean SBT compile of main and test sources before
pushing `ref_name`.
+
+ `ref_name` is the checked-out cherry-pick, so a clean compile here catches
a mis-resolved
+ conflict, or a PR that bit-rotted against the target branch, before it
lands. It is a smoke
+ test (see COMPILE_CHECK_CMD), not CI: modules behind other profiles are
not compiled.
+ Declining skips the check. A red build asks rather than aborts, because a
non-zero sbt is
+ as easily a JDK the branch rejects or a failed download as it is the
backport; declining
+ there skips this branch (see continue_maybe). Output streams so a long
compile does not
+ look like a hang.
+
+ What is compiled is the working tree, not the commit: a file re-edited
after the merge
+ commit, or an untracked source file left over from a manual conflict
resolution, compiles
+ here and is absent from the push. (A resolved-but-never-`git add`ed
conflict is NOT the
+ case -- the commit itself fails while files are unmerged, so the check is
never reached.)
+ So warn when the tree is dirty rather than report a green that is about
something else,
+ and name the remedy (`git add` + `git commit --amend`) since the fix is
the commit, not
+ the build.
+
+ Declining runs no build and no git -- the git.run mock raises if a
regression moves a
+ git call above the prompt, which otherwise would run real git in the
committer's repo on
+ every startup (doctest.testmod() runs on invocation):
+
+ >>> from contextlib import redirect_stdout
+ >>> from io import StringIO
+ >>> from unittest.mock import call, patch
+ >>> with (
+ ... patch("builtins.input", return_value=""),
+ ... patch.object(git, "run", side_effect=AssertionError("should not
run git")),
+ ... patch("subprocess.call") as run,
+ ... redirect_stdout(StringIO()),
+ ... ):
+ ... maybe_compile_check("PR_TOOL_PICK_PR_1_BRANCH-4.1")
+ >>> run.call_count
+ 0
+
+ Accepting runs the SBT compile once, from the repo root, with an explicit
-P so SparkBuild
+ does not fall back to `-Psbt`; a green build returns quietly. The two git
calls are pinned
+ too -- transposing them or dropping --porcelain would otherwise stay green:
+
+ >>> with (
+ ... patch("builtins.input", return_value="y"),
+ ... patch.object(git, "run", side_effect=["/repo\\n", ""]) as grun,
+ ... patch("subprocess.call", return_value=0) as run,
+ ... redirect_stdout(StringIO()),
+ ... ):
+ ... maybe_compile_check("PR_TOOL_PICK_PR_1_BRANCH-4.1")
+ >>> grun.call_args_list[0]
+ call(['git', 'rev-parse', '--show-toplevel'])
+ >>> grun.call_args_list[1]
+ call(['git', 'status', '--porcelain'])
+ >>> run.call_count
+ 1
+ >>> run.call_args[0][0][0], run.call_args[0][0][-1]
+ ('build/sbt', ';clean;compile;Test/compile')
+ >>> [a for a in run.call_args[0][0] if a.startswith("-P")]
+ ['-Phive']
+ >>> run.call_args[1]["cwd"]
+ '/repo'
+
+ A dirty tree still builds, but warns first -- and the warning names the
remedy
+ (`git add` + `git commit --amend`) alongside the porcelain output:
+
+ >>> with (
+ ... patch("builtins.input", return_value="y"),
+ ... patch.object(git, "run", side_effect=["/repo\\n", " M
foo.scala\\n"]),
+ ... patch("subprocess.call", return_value=0),
+ ... redirect_stdout(StringIO()) as out,
+ ... ):
+ ... maybe_compile_check("PR_TOOL_PICK_PR_1_BRANCH-4.1")
+ >>> "git commit --amend" in out.getvalue()
+ True
+ >>> "M foo.scala" in out.getvalue() # porcelain output is strip()ed
before printing
+ True
+ >>> "Compile check passed." in out.getvalue()
+ True
+
+ The experts-only override continues past a red build:
+
+ >>> with (
+ ... patch("builtins.input", side_effect=["y", "y"]),
+ ... patch.object(git, "run", side_effect=["/repo\\n", ""]),
+ ... patch("subprocess.call", return_value=1),
+ ... redirect_stdout(StringIO()),
+ ... ):
+ ... maybe_compile_check("PR_TOOL_PICK_PR_1_BRANCH-4.1")
+
+ Ctrl-C during the build, and a build/sbt that cannot be run at all, are
"did not pass" and
+ get the same override prompt -- never a traceback, which would reach the
top-level handler
+ and let clean_up() delete the unpushed pick:
+
+ >>> for boom in (KeyboardInterrupt(), OSError("no build/sbt")):
+ ... with (
+ ... patch("builtins.input", side_effect=["y", "y"]),
+ ... patch.object(git, "run", side_effect=["/repo\\n", ""]),
+ ... patch("subprocess.call", side_effect=boom),
+ ... redirect_stdout(StringIO()),
+ ... ):
+ ... maybe_compile_check("PR_TOOL_PICK_PR_1_BRANCH-4.1")
+
+ Declining the override skips just this branch instead of exiting:
+
+ >>> with (
+ ... patch("builtins.input", side_effect=["y", ""]),
+ ... patch.object(
+ ... git, "run", side_effect=["/repo\\n", "",
subprocess.CalledProcessError(1, "g")]
+ ... ),
+ ... patch("subprocess.call", return_value=1),
+ ... redirect_stdout(StringIO()),
+ ... ):
+ ... try:
+ ... maybe_compile_check("PR_TOOL_PICK_PR_1_BRANCH-4.1")
+ ... skipped = False
+ ... except SkipCherryPick:
+ ... skipped = True
+ >>> skipped
+ True
+ """
+ # The command is too long to read inside a prompt, so print it on its own
line first.
+ # shlex.join quotes the ";clean;..." argument, so the printed line can be
copy-pasted
+ # into a shell without the semicolons splitting it into four commands.
+ print("Optional pre-push check: %s" % shlex.join(COMPILE_CHECK_CMD))
+ print("Note: 'clean' deletes every module's build output, including under
--dry-run.")
+ prompt = "Run an optional clean compile on %s before pushing? (y/N): " %
ref_name
+ if get_input(prompt, ["y", "n", ""]) != "y":
+ return
+ # build/sbt is repo-relative and SPARK_HOME defaults to the cwd, which is
dev/ when the
+ # script is run as ./merge_spark_pr.py per its own usage line. Ask git for
the root instead.
+ root = git.run(["git", "rev-parse", "--show-toplevel"]).strip()
+ dirty = git.run(["git", "status", "--porcelain"]).strip()
+ if dirty:
+ print_error(
+ "Working tree is not clean, so what compiles below is not exactly
the commit that "
+ "would be pushed -- the uncommitted or untracked changes below
compile here but "
+ "are not in the push. If any of them belong in the pick, 'git add'
them and "
+ "'git commit --amend' before pushing; if they are unrelated
scratch, ignore this "
+ "and carry on:\n%s" % dirty
+ )
+ try:
+ status = subprocess.call(COMPILE_CHECK_CMD, cwd=root)
+ except KeyboardInterrupt:
+ # Interrupting the build must not unwind into the top-level handler:
clean_up() there
+ # force-deletes the PR_TOOL_* branch holding the unpushed commit and
any hand-resolved
+ # conflicts. Treat it as "the check did not finish" and let the
committer decide.
+ print_error("Compile check interrupted.")
+ except OSError as e:
+ print_error("Could not run %s in %s: %s" % (COMPILE_CHECK_CMD[0],
root, e))
+ else:
+ if status == 0:
+ print("Compile check passed.")
+ return
+ print_error(
+ "Compile check exited %d. That is the backport, or your toolchain
-- a JDK this "
+ "branch rejects and a failed dependency download look the same
here." % status
+ )
+ continue_maybe(
+ "Compile check did not pass on %s. Push anyway? (experts only!)" %
ref_name, True
+ )
+
+
+def _is_pre_binding_policy_branch(ref: str) -> bool:
+ """True if `ref` is a Spark branch that predates the ConfigBindingPolicy
API (4.2+).
+
+ master and branch-M.x (M >= 4) carry the API; branch-4.0/branch-4.1 and
any branch-3.x
+ do not. Ranking is semver_branch_rank's job -- branch-M.x sorts above
every branch-M.N,
+ and a ref it cannot classify as a maintenance branch gets its (-1, -1)
sentinel. Those
+ refs are treated as carrying the API: fail-open, so master, a tag, or a
custom ref never
+ raises a false warning -- none of them is a pre-4.2 branch anyway.
+
+ >>> _is_pre_binding_policy_branch("master")
+ False
+ >>> _is_pre_binding_policy_branch("branch-4.x")
+ False
+ >>> _is_pre_binding_policy_branch("branch-4.2")
+ False
+ >>> [_is_pre_binding_policy_branch(b) for b in ("branch-4.1",
"branch-4.0", "branch-3.x")]
+ [True, True, True]
+ >>> _is_pre_binding_policy_branch("branch-3.5")
+ True
+ >>> _is_pre_binding_policy_branch("HEAD")
+ False
+ >>> _is_pre_binding_policy_branch("my-custom-ref")
+ False
+ """
+ rank = semver_branch_rank(ref)
+ return rank != (-1, -1) and rank < (4, 2)
+
+
+def _added_binding_policy_tokens(diff: str) -> list[str]:
+ """Return the sorted subset of BINDING_POLICY_PATTERNS matched on added
(``+``) lines.
+
+ Only scans lines the diff added (a leading ``+`` that is not the ``+++ ``
file header --
+ the trailing space keeps an added line whose own text starts with ``++``
counted, apart
+ from the ``++ <space>`` case no real Scala/Java line starts with), so a
cherry-pick that
+ *removes* a stray .withBindingPolicy is not flagged. Matching uses the
+ precise patterns from BINDING_POLICY_PATTERNS, so a comment that merely
mentions
+ ``withBindingPolicy`` (no leading dot, no call) is not flagged;
``ConfigBindingPolicy`` in
+ a comment still can match, which is fine -- the prompt is advisory.
+
+ >>> _added_binding_policy_tokens(
+ ... "+++ b/foo\\n"
+ ... "+.withBindingPolicy(X)\\n"
+ ... "-.withBindingPolicy(Y)\\n"
+ ... "+import ...ConfigBindingPolicy\\n"
+ ... "+// see withBindingPolicy usage\\n"
+ ... " context\\n"
+ ... )
+ ['ConfigBindingPolicy', 'withBindingPolicy']
+ >>> _added_binding_policy_tokens("-.withBindingPolicy(X)\\n")
+ []
+ >>> _added_binding_policy_tokens("+// mentions ConfigBindingPolicy in a
comment\\n")
+ ['ConfigBindingPolicy']
+ >>> _added_binding_policy_tokens("")
+ []
+ """
+ found = set()
+ for line in diff.splitlines():
+ if line.startswith("+") and not line.startswith("+++ "):
+ for token, pattern in BINDING_POLICY_PATTERNS:
+ if pattern.search(line):
+ found.add(token)
+ return sorted(found)
+
+
+def maybe_binding_policy_warning(ref: str, base_head: str) -> None:
+ """Warn before pushing to a pre-4.2 `ref` a cherry-pick that adds
ConfigBindingPolicy.
+
+ A cherry-pick onto branch-4.1/4.0/3.x that introduces
``.withBindingPolicy(...)`` or
+ ``ConfigBindingPolicy`` will not compile there (the API arrived in
SPARK-55928, 4.2+).
+ This is a git-diff + grep pre-push check: it diffs `base_head` (the branch
tip before the
+ pick) against HEAD restricted to Scala/Java sources, scans only the added
lines for the
+ precise patterns in BINDING_POLICY_PATTERNS, and on a hit prints the
remedy and asks the
+ committer to confirm the push; declining skips this branch (see
continue_maybe). No-op on
+ branches that carry the API. Only backports are checked: a PR opened
straight against a
+ maintenance branch already ran that branch's CI.
+
+ The diff is forced plain: without --no-color a committer with ``color.ui =
always`` gets
+ added lines behind an ANSI escape, no line starts with "+", and the check
reports nothing
+ while looking like it ran. Like branches_with_merge_footer, a git failure
only warns: this
+ runs after the merge has already been pushed.
+
+ `never` below is how these tests assert "does not prompt": a bare input
mock would return a
+ MagicMock that get_input's loop never accepts, so a regressed guard would
hang the script at
+ startup -- doctest.testmod() runs on every invocation -- instead of
failing.
+
+ >>> from contextlib import redirect_stdout
+ >>> from io import StringIO
+ >>> from unittest.mock import patch
+ >>> never = AssertionError("should not prompt")
+
+ No-op on a branch that carries the API (no diff fetched, no prompt):
+
+ >>> with (
+ ... patch.object(git, "run") as run,
+ ... patch("builtins.input", side_effect=never),
+ ... redirect_stdout(StringIO()),
+ ... ):
+ ... maybe_binding_policy_warning("branch-4.2", "deadbeef")
+ >>> run.call_count
+ 0
+
+ No-op when the change added none of the tokens. The git command is pinned
here because
+ nothing else in these tests would notice it being wrong -- transposing the
two endpoints
+ inverts the whole check, and dropping the pathspec or --no-color silently
defeats it:
+
+ >>> with (
+ ... patch.object(git, "run", return_value="+ unrelated change\\n") as
run,
+ ... patch("builtins.input", side_effect=never),
+ ... redirect_stdout(StringIO()),
+ ... ):
+ ... maybe_binding_policy_warning("branch-4.1", "deadbeef")
+ >>> run.call_args[0][0][:6]
+ ['git', 'diff', '--no-color', '--no-ext-diff', 'deadbeef', 'HEAD']
+ >>> run.call_args[0][0][6:]
+ ['--', ':(top)*.scala', ':(top)*.java']
+
+ Warns and prompts when the change adds a token on a pre-4.2 branch;
accepting continues
+ (no abort), so input is called once by the continue_maybe prompt:
+
+ >>> with (
+ ... patch.object(git, "run", return_value="+.withBindingPolicy(X)\\n"),
+ ... patch("builtins.input", return_value="y") as inp,
+ ... redirect_stdout(StringIO()),
+ ... ):
+ ... maybe_binding_policy_warning("branch-4.1", "deadbeef")
+ >>> inp.call_count
+ 1
+
+ Declining skips just that branch, so an already-pushed branch-M.x pick
+ and the JIRA resolution survive (the second git.run is the
CHERRY_PICK_HEAD probe):
+
+ >>> with (
+ ... patch.object(
+ ... git,
+ ... "run",
+ ... side_effect=[
+ ... "+.withBindingPolicy(X)\\n",
+ ... subprocess.CalledProcessError(1, "git"),
+ ... ],
+ ... ),
+ ... patch("builtins.input", return_value=""),
+ ... redirect_stdout(StringIO()),
+ ... ):
+ ... try:
+ ... maybe_binding_policy_warning("branch-4.1", "deadbeef")
+ ... skipped = False
+ ... except SkipCherryPick:
+ ... skipped = True
+ >>> skipped
+ True
+
+ A git failure warns and scans nothing rather than aborting a half-pushed
merge:
+
+ >>> with (
+ ... patch.object(git, "run", side_effect=OSError("git is sad")),
+ ... patch("builtins.input", side_effect=never),
+ ... redirect_stdout(StringIO()) as out,
+ ... ):
+ ... maybe_binding_policy_warning("branch-4.1", "deadbeef")
+ >>> "git is sad" in out.getvalue()
+ True
+ """
+ if not _is_pre_binding_policy_branch(ref):
+ return
+ try:
+ diff = git.run(
+ ["git", "diff", "--no-color", "--no-ext-diff", base_head, "HEAD",
"--"]
+ + list(BINDING_POLICY_PATHSPECS)
+ )
+ except Exception as e:
+ print_error(
+ "Could not diff %s..HEAD; skipping the ConfigBindingPolicy check:
%s" % (base_head, e)
+ )
+ return
+ tokens = _added_binding_policy_tokens(diff)
+ if not tokens:
+ return
+ print_error(
+ "Warning: what would be pushed to %s adds %s, which does not exist
before branch-4.2 "
+ "(SPARK-55928). Drop the .withBindingPolicy(...) call and the
ConfigBindingPolicy "
+ "import. Leave .version(...) alone -- it names the release the config
shipped in -- "
+ "unless the config itself is new on this branch, in which case
retarget it to this "
+ "branch's next release." % (ref, " / ".join(tokens))
+ )
+ 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()
+ if merge_footer_pr(message) != int(m.group(1)):
+ return None
+ authors = re.findall(r"^(?:Lead-authored-by|Authored-by): (.+)$", message,
re.MULTILINE)
Review Comment:
**Nit (P3):** Every `_backport_of`, `_land_via_fork` and `merge_pr` fixture
uses a single `Authored-by:` line. `merge_pr` writes `Lead-authored-by:`
whenever the original PR had co-authors, so the shape every co-authored
original carries is never parsed here. If the `Lead-authored-by` alternative
were dropped, `authors` would be empty for those originals and `merge_pr` would
raise `IndexError`. If `authors[-1]` became `authors[0]`, a body that quotes an
earlier footer would set the wrong `--author`. Both would pass today's
doctests. Cases for a `Lead-authored-by` original and for a body that quotes an
earlier footer would pin this.
See **Shared repair plan 1** in the review body.
##########
dev/merge_spark_pr.py:
##########
@@ -3518,53 +4781,47 @@ def main():
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.
+ # 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:
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)
break
- picked = cherry_pick(
- pr_num,
- merge_hash,
- default,
- branch_names,
- target_ref,
- already_picked=tuple(merged_refs),
+ picks.record(
+ cherry_pick(
+ pr_num,
+ merge_hash,
+ default,
+ branch_names,
+ target_ref,
+ already_picked=tuple(picks.landed),
Review Comment:
**Nit (P3):** Nothing checks what this or the neighboring ledger arguments
carry, in either pick loop. `__test__['main_titles']` mocks `cherry_pick` to
return a landed marker, `pending_fork_backports` to return `{}` and
`branches_with_merge_footer` to return `[]`. It asserts only the titles and the
branch names `default_pick_branch` receives. Each of these regressions would
break a stated decision and keep every doctest green:
- passing `picks.seen()` here, which skips the maintenance-only confirmation
- passing `picks.seen()` to `update_jira_for_pr`, which records fix versions
for unmerged backport PRs
- passing `picks.landed` to `default_pick_branch`
- using `pr_num` instead of `original`
- dropping the earlier-run lookup
Two runs that assert these arguments, one with a pending marker and one on a
merged backport PR's message, would pin the wiring.
**Verification:**
- **Regression:** With a branch that has only a pending backport PR, both
pick loops pass only landed branches as already picked and to the JIRA update,
pass the pending branches to the pick, and keep the pending branch out of the
default, so swapping the landed set with the landed-plus-pending set anywhere
fails a case.
- **Regression:** A run on a merged backport PR looks up footer branches and
fork backport PRs by the original PR's number and drops earlier pending
branches that already landed, so using the run's own PR number or skipping the
lookup fails a case.
- **Behavior:** After merging a recognized backport PR, the merge loop's
ledger is asserted to hold the original PR's landed and pending branches.
##########
dev/merge_spark_pr.py:
##########
@@ -1146,41 +1779,71 @@ def merge_pr(pr_num, target_ref, title, body,
pr_repo_desc, pr_author, co_author
continue_maybe(msg)
had_conflicts = True
- # Use PR author as the primary author for proper GitHub attribution
- primary_author = bold_input(
- 'Enter primary author in the format of "name <email>" [%s]: ' %
pr_author
- )
- if primary_author == "":
- primary_author = pr_author
-
- merge_message_flags = []
-
- merge_message_flags += ["-m", title]
- if body is not None:
- # We remove @ symbols from the body to avoid triggering e-mails
- # to people every time someone creates a public fork of Spark.
- merge_message_flags += ["-m", body.replace("@", "")]
+ backport = _backport_of(body, pr_repo_desc.split("/", 1)[-1], target_ref)
+ if backport:
+ # The footer already names the author; a different --author would
contradict it.
+ print("Backport of #%s: keeping its commit message and author." %
backport[0])
+ # Soft check: the marker and footer are plain PR text, so confirm they
are some
+ # commit's message on the branch, as _land_via_fork leaves them.
+ commits = git.run(["git", "log", "--format=%b%x00", "HEAD..%s" %
pr_branch_name])
+ if backport[1] not in [_pick_message(c) for c in commits.split("\0")]:
+ continue_maybe(
+ "The Backport-of message in the PR body matches none of its
commits, so the "
+ "author and footer below are only as good as that text. Merge
it anyway?"
+ )
+ primary_author = backport[2]
+ else:
+ # Use PR author as the primary author for proper GitHub attribution
+ primary_author = bold_input(
+ 'Enter primary author in the format of "name <email>" [%s]: ' %
pr_author
+ )
+ if primary_author == "":
+ primary_author = pr_author
committer_name = git.run("git config --get user.name").strip()
committer_email = git.run("git config --get user.email").strip()
+ signoff = "Signed-off-by: %s <%s>" % (committer_name, committer_email)
+ conflicts = "This patch had conflicts when merged, resolved by\nCommitter:
%s <%s>" % (
+ committer_name,
+ committer_email,
+ )
- if had_conflicts:
- message = "This patch had conflicts when merged, resolved
by\nCommitter: %s <%s>" % (
- committer_name,
- committer_email,
- )
- merge_message_flags += ["-m", message]
+ merge_message_flags = ["-m", title]
+ if backport:
+ # The original message already ends with #N's footer and authors (its
@s were stripped
+ # at the original merge). No "Closes #<this PR>": that would become
the last footer and
+ # hide the branch from #N's merge status. main() closes this PR
through the API.
+ # git reads trailers from the last paragraph only, so the conflicts
note goes first
+ # and ours join the original's.
+ if had_conflicts:
+ merge_message_flags += ["-m", conflicts]
+ # Credit anyone who pushed fixups to the backport PR itself. Match on
the "<email>":
Review Comment:
**Nit (P3):** This doesn't credit everyone who pushed fixups. `main()`
builds `co_authors` only from commits whose GitHub login differs from the PR
author's. That rule was written for the regular path, where the PR author
becomes the primary author. On a backport PR, the PR author is usually the
committer who ran `[p]` and then pushed fixups after CI, so those commits never
reach this list. The `<email>` filter below would drop them as well, because
the pick's `Signed-off-by` from `cherry-pick -s` puts that committer's address
in the original message. Either keep the PR author's commits when the PR is a
recognized backport and filter only on the original's author lines, or narrow
this comment and the PR description to what the code credits.
**Verification:**
- **Regression:** Merging a backport PR whose own author pushed a fixup
commit adds a Co-authored-by line for that author before the committer's
sign-off.
- **Behavior:** A backport PR that carries only the pick adds no
Co-authored-by line, and nobody named in the original's Authored-by,
Lead-authored-by or Co-authored-by lines is credited again, while a sign-off
alone does not suppress a fixup author's credit.
- **Compatibility:** A regular PR's merge message keeps its Authored-by or
Lead-authored-by and Co-authored-by lines exactly as before.
##########
dev/merge_spark_pr.py:
##########
@@ -1270,14 +2358,43 @@ def _do_cherry_pick(pr_num, merge_hash, pick_ref):
if updated_message != raw_message:
amend_commit_message(updated_message)
- continue_maybe(
- "Pick complete (local ref %s). Push to %s?" % (pick_branch_name,
PUSH_REMOTE_NAME)
- )
+ maybe_binding_policy_warning(pick_ref, pick_head)
+ maybe_compile_check(pick_branch_name)
- try:
- git.push(PUSH_REMOTE_NAME, pick_branch_name, pick_ref)
- except Exception as e:
- fail("Exception while pushing: %s" % e)
+ while True:
+ choice = _landing_choice(pick_branch_name, pick_ref)
+ if choice == "s":
+ # Restore the original checkout and drop the temp PICK_PR_*
branches, as the
+ # continue_maybe decline path does; otherwise a later pick of the
same ref fails
+ # when `git fetch` tries to update the checked-out branch.
+ print("Skipping this branch; the merge continues.")
+ clean_up()
+ raise SkipCherryPick()
Review Comment:
**Nit (P3):** This raise is one of two new reasons for `SkipCherryPick`. The
other is declining the binding-policy or compile-check prompt through
`continue_maybe(..., True)`. The class docstring still says it 'Signals that
the committer declined to resolve a conflicting cherry-pick'. Describe it as
skipping just this branch, whether the committer declined a conflict, declined
a pre-push check, or chose `[s]`. That keeps it accurate for the `except`
handlers in `cherry_pick`.
**Verification:**
- **Inspection:** The SkipCherryPick docstring names a declined conflict
resolution, a declined pre-push check and the [s] answer at the landing prompt
as its triggers.
##########
dev/spark_merge_footer.py:
##########
@@ -130,8 +171,14 @@ def has_merge_footer(message, pr_num):
False
>>> has_merge_footer(later, 2)
True
+
+ A merged backport PR counts for itself and for the original:
+
+ >>> backport = "[SPARK-1][4.2][SQL] Title\\n\\n" + footer +
"\\nBackport-PR: #9"
+ >>> [has_merge_footer(backport, pr) for pr in (1, 9, 2)]
+ [True, True, False]
"""
- return merge_footer_pr(message) == int(pr_num)
+ return int(pr_num) in (merge_footer_pr(message), backport_pr(message))
Review Comment:
**Nit (P3):** With this change, `has_merge_footer(message, M)` is also true
when the final paragraph names backport PR M. As a result, `committed_title` in
`dev/merge_spark_pr.py` now returns the subject of a backport merge whose
footer closes the original PR. That is the right title for a run on the merged
backport PR, but `committed_title`'s docstring still says the subject is used
only when the merge footer of `message` closes `pr_num`. Adding the
merged-backport case there keeps the two in step.
**Verification:**
- **Inspection:** committed_title's docstring states that the subject is
used when the merge footer closes the PR or the final Backport-PR trailer names
it.
##########
dev/merge_spark_pr.py:
##########
@@ -1209,12 +1872,437 @@ 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):
- """Cherry-pick `merge_hash` onto `pick_ref` and push.
+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.
- Returns the (pushed ref, pushed commit hash) pair. Raises `SkipCherryPick`
if the
- cherry-pick conflicts and the committer declines to resolve it, after
attempting to
- abort the cherry-pick and restore the working tree.
+ >>> _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).
+
+ >>> from contextlib import redirect_stdout
+ >>> from io import StringIO
+ >>> from unittest.mock import patch
+ >>> with patch("builtins.input", return_value=""),
redirect_stdout(StringIO()):
+ ... choice = _landing_choice("PR_TOOL_PICK_PR_1_BRANCH-4.2",
"branch-4.2")
+ >>> choice
+ 's'
+ """
+ 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", ""]},
+ )
+
+
+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)
+ except Exception as e:
+ print_error("Could not push the pick to your fork: %s" % e)
+ push = "git push <your fork> %s:%s" % (pick_branch_name,
backport_branch)
+ return _manual_backport_pr(pick_ref, pr_title, pr_body, push=push)
+ head = "%s:%s" % (owner, backport_branch)
+ created = github.create_pr(pick_ref, head, pr_title, pr_body)
+ if created and created.get("html_url"):
+ print("Backport PR for #%s against %s: %s" % (pr_num, pick_ref,
created["html_url"]))
+ return created["html_url"]
+ print_error("Backport PR was not opened (see above); the pick is on %s." %
head)
+ return _manual_backport_pr(pick_ref, pr_title, pr_body, head=head) or
"fork:%s" % head
+
+
+def _manual_backport_pr(pick_ref, title, body, push=None, head=None):
+ """Walk the committer through opening the backport PR by hand; the URL
pasted, or None.
+
+ `push` is the command still needed to get the pick onto the fork; `head`
is the fork
+ branch when it is already there.
+
+ >>> from contextlib import redirect_stdout
+ >>> from io import StringIO
+ >>> from unittest.mock import patch
+ >>> with (
+ ... patch("builtins.input",
return_value="https://github.com/apache/spark/pull/9"),
+ ... redirect_stdout(StringIO()) as out,
+ ... ):
+ ... url = _manual_backport_pr("branch-4.2", "T", "Backport-of: #7",
head="me:b")
+ >>> url
+ 'https://github.com/apache/spark/pull/9'
+ >>> "compare/branch-4.2...me:b?expand=1" in out.getvalue()
+ True
+ >>> with patch("builtins.input", return_value=""),
redirect_stdout(StringIO()) as out:
+ ... url = _manual_backport_pr("branch-4.2", "T", "B", push="git push
<your fork> P:b")
+ >>> url is None, "git push <your fork> P:b" in out.getvalue()
+ (True, True)
+ """
+ print("To open the backport PR by hand, as a draft against %s:" % pick_ref)
+ if push:
+ print(" %s (before you skip: the local ref goes away with it)" %
push)
+ print(" then open a PR from that branch")
+ if head:
+ print(" https://github.com/apache/spark/compare/%s...%s?expand=1" %
(pick_ref, head))
+ print(
+ "Title:\n%s\nBody (keep the Backport-of line; merging with this script
uses it to "
+ "keep the original author):\n%s" % (title, body)
+ )
+ url = get_input(
+ "Paste the backport PR URL once it is open (Enter to skip): ",
+ r"^(https://github\.com/apache/spark/pull/\d+)?$",
+ ignore_case=False,
+ )
+ return url or None
+
+
+def _landed(marker):
+ """Whether a pick's marker means it landed on the Apache branch.
+
+ A direct push returns a bare commit hash (landed); the backport-PR paths
return a PR URL
+ (`https://`) or a `fork:` marker (PR not opened), both pending.
+
+ >>> [_landed(m) for m in ("deadbeef", "https://x/pull/9",
"fork:o:backport-pr1-branch-4.2")]
+ [True, False, False]
+ """
+ return not marker.startswith(("https://", "fork:"))
+
+
+class _PickLedger:
+ """Where the change is during a run, for main()'s two pick loops.
+
+ `landed` (the merge sink, footer branches, direct pushes) drives
Upstream-First and JIRA
+ fix versions, so neither treats an open backport PR as having the change.
`pending` maps
+ branches with only a backport PR, from this run or an earlier one, to
their markers.
+ `seen()` is both, kept out of the prompt default. `commits` is this run's
picks.
+
+ >>> picks = _PickLedger(["master"], pending={"branch-4.1":
"https://x/pull/8"})
+ >>> picks.record([("branch-4.x", "abc"), ("branch-4.3",
"https://x/pull/9")])
+ >>> picks.record([("branch-4.2", "fork:me:backport-pr7-branch-4.2")])
+ >>> picks.landed, sorted(picks.pending)
+ (['master', 'branch-4.x'], ['branch-4.1', 'branch-4.2', 'branch-4.3'])
+ >>> sorted(picks.seen())
+ ['branch-4.1', 'branch-4.2', 'branch-4.3', 'branch-4.x', 'master']
+ >>> [ref for ref, _ in picks.commits]
+ ['branch-4.x', 'branch-4.3', 'branch-4.2']
+ >>> picks.record([("branch-4.1", "def")])
+ >>> picks.landed[-1], "branch-4.1" in picks.pending
+ ('branch-4.1', False)
+ """
+
+ def __init__(self, landed, pending=None):
+ self.landed = list(landed)
+ self.pending = dict(pending or {})
+ self.commits = []
+
+ def seen(self):
+ return tuple(self.landed) + tuple(self.pending)
+
+ def record(self, picked):
+ for ref, marker in picked:
+ if _landed(marker):
+ self.landed.append(ref)
+ self.pending.pop(ref, None)
+ else:
+ self.pending[ref] = marker
+ self.commits += picked
+
+
+def _do_cherry_pick(pr_num, merge_hash, pick_ref, title="",
pending_sibling=None):
+ """Cherry-pick `merge_hash` onto `pick_ref` and land it.
+
+ Returns (pick_ref, marker), where the marker says how it landed (see
_landed):
+ a commit hash for a direct push (landed), a PR URL for a draft backport
PR, or
+ `fork:<owner>:<branch>` when the fork push worked but the PR did not open
(both pending).
+ `pending_sibling` is the (branch-M.x, marker) whose backport is only
pending; a direct push
+ then needs an explicit maintenance-only confirmation. Raises
`SkipCherryPick`, after
+ restoring the working tree, when the committer declines to resolve a
conflict, declines
+ the binding-policy or compile-check prompt, or answers [s]kip at the
landing prompt.
+ A failed fork landing or direct push returns to the landing prompt with
the pick kept.
+
+ >>> from contextlib import redirect_stdout
+ >>> from io import StringIO
+ >>> from unittest.mock import Mock, call, patch
+ >>> policy, compile_check = Mock(), Mock()
+ >>> def land(answers, via_fork=(), push_error=None):
+ ... with (
+ ... patch("builtins.input", side_effect=answers),
+ ... patch.object(git, "run", return_value="head\\n"),
Review Comment:
**Nit (P3):** This mock answers every git command with `head`, so the
pre-pick `rev-parse` and any later one return the same value. The assertion
below, that the binding-policy check ran 'against the pre-pick head', therefore
can't fail. If `_do_cherry_pick` passed the post-pick HEAD instead, the check
would diff HEAD against itself and never warn, and the doctest would stay
green. Returning different tips before and after the pick would make the
assertion mean what it says.
**Verification:**
- **Regression:** With distinct branch tips before and after the pick, the
ConfigBindingPolicy check receives the tip from before the pick.
##########
dev/merge_spark_pr.py:
##########
@@ -916,9 +956,46 @@ 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."""
+ 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):
+ # 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:
**Nit (P3):** No test runs this method or `open_pr`. Every doctest that
reaches them patches them on `github` or uses `DryRunGitHub`, and nothing calls
`_api`. So several behaviors are unpinned: `"draft": True` here, the PATCH of
an already-open PR above it, the missing-token skip, and the failure returns.
With `draft` False, the script, which refuses only draft PRs, could merge a
backport PR before its CI ran. An `open_pr` that always returned None would
quietly disable earlier-run detection in `pending_fork_backports`. Stubbing
`_api` and checking the method, URL and payload for each branch would cover it.
**Verification:**
- **Regression:** Without GITHUB_OAUTH_KEY the backport PR is skipped before
any request is made.
- **Regression:** When an open PR already exists from the same head against
the same base, its title and body are updated instead of a second PR being
opened; otherwise a PR is created as a draft with the given head, base, title
and body.
- **Behavior:** A failed request yields no PR, and the open-PR lookup
returns the first open PR or none, also when the request fails.
##########
dev/merge_spark_pr.py:
##########
@@ -1146,41 +1779,71 @@ def merge_pr(pr_num, target_ref, title, body,
pr_repo_desc, pr_author, co_author
continue_maybe(msg)
had_conflicts = True
- # Use PR author as the primary author for proper GitHub attribution
- primary_author = bold_input(
- 'Enter primary author in the format of "name <email>" [%s]: ' %
pr_author
- )
- if primary_author == "":
- primary_author = pr_author
-
- merge_message_flags = []
-
- merge_message_flags += ["-m", title]
- if body is not None:
- # We remove @ symbols from the body to avoid triggering e-mails
- # to people every time someone creates a public fork of Spark.
- merge_message_flags += ["-m", body.replace("@", "")]
+ backport = _backport_of(body, pr_repo_desc.split("/", 1)[-1], target_ref)
+ if backport:
+ # The footer already names the author; a different --author would
contradict it.
+ print("Backport of #%s: keeping its commit message and author." %
backport[0])
+ # Soft check: the marker and footer are plain PR text, so confirm they
are some
+ # commit's message on the branch, as _land_via_fork leaves them.
+ commits = git.run(["git", "log", "--format=%b%x00", "HEAD..%s" %
pr_branch_name])
+ if backport[1] not in [_pick_message(c) for c in commits.split("\0")]:
+ continue_maybe(
+ "The Backport-of message in the PR body matches none of its
commits, so the "
+ "author and footer below are only as good as that text. Merge
it anyway?"
+ )
+ primary_author = backport[2]
+ else:
+ # Use PR author as the primary author for proper GitHub attribution
+ primary_author = bold_input(
+ 'Enter primary author in the format of "name <email>" [%s]: ' %
pr_author
+ )
+ if primary_author == "":
+ primary_author = pr_author
committer_name = git.run("git config --get user.name").strip()
committer_email = git.run("git config --get user.email").strip()
+ signoff = "Signed-off-by: %s <%s>" % (committer_name, committer_email)
+ conflicts = "This patch had conflicts when merged, resolved by\nCommitter:
%s <%s>" % (
+ committer_name,
+ committer_email,
+ )
- if had_conflicts:
- message = "This patch had conflicts when merged, resolved
by\nCommitter: %s <%s>" % (
- committer_name,
- committer_email,
- )
- merge_message_flags += ["-m", message]
+ merge_message_flags = ["-m", title]
+ if backport:
+ # The original message already ends with #N's footer and authors (its
@s were stripped
+ # at the original merge). No "Closes #<this PR>": that would become
the last footer and
+ # hide the branch from #N's merge status. main() closes this PR
through the API.
+ # git reads trailers from the last paragraph only, so the conflicts
note goes first
+ # and ours join the original's.
+ if had_conflicts:
+ merge_message_flags += ["-m", conflicts]
Review Comment:
**Nit (P3):** The ordering here is load-bearing. The conflicts note has to
come before the original message so that `Backport-PR`, `Co-authored-by` and
the sign-off join the original's final paragraph, which `backport_pr` reads.
But `merge_pr`'s doctest mock never raises from `git merge`, so `had_conflicts`
is always false there. If the note were emitted after the trailer block,
`backport_pr(message)` would return None. `find_merge_commit` and
`dev/pr_merge_status.py` would then stop recognizing a backport PR merged after
conflicts, and no doctest would fail. A conflicting-merge case that asserts
`backport_pr(message)` returns the backport PR's number would catch it.
See **Shared repair plan 1** in the review body.
##########
dev/merge_spark_pr.py:
##########
@@ -983,15 +1140,17 @@ def run(self, cmd):
else:
return subprocess.check_output(cmd.split(" ")).decode("utf-8")
- def push(self, remote, local_ref, remote_ref):
- return self.run("git push %s %s:%s" % (remote, local_ref, remote_ref))
+ def push(self, remote, local_ref, remote_ref, force=False):
+ plus = "+" if force else ""
Review Comment:
**Nit (P3):** Only `_land_via_fork` should send a `+` refspec, but nothing
runs the real `Git.push`. The `[d]` doctest reads only the target branch of the
push call, and `merge_pr`'s doctest patches `git.push` without reading it. Each
of these would stay green: defaulting `force` to True, forcing the `[d]` or
merge push, or sending `[d]` to `FORK_REMOTE_NAME`. A forced push could
overwrite a release branch that moved during the run. Sending `[d]` to the fork
would record a fork-only push as landed in the merge comment and in JIRA.
Assert the real command with and without `force`, plus the remote and force
flag of the `[d]` and merge pushes.
**Verification:**
- **Regression:** A forced push sends a refspec prefixed with '+' and an
unforced push does not.
- **Regression:** A direct [d] push and the merge's push go unforced to the
Apache push remote and the target branch, and only the backport-PR push goes,
forced, to the fork remote.
##########
dev/merge_spark_pr.py:
##########
@@ -1146,41 +1779,71 @@ def merge_pr(pr_num, target_ref, title, body,
pr_repo_desc, pr_author, co_author
continue_maybe(msg)
had_conflicts = True
- # Use PR author as the primary author for proper GitHub attribution
- primary_author = bold_input(
- 'Enter primary author in the format of "name <email>" [%s]: ' %
pr_author
- )
- if primary_author == "":
- primary_author = pr_author
-
- merge_message_flags = []
-
- merge_message_flags += ["-m", title]
- if body is not None:
- # We remove @ symbols from the body to avoid triggering e-mails
- # to people every time someone creates a public fork of Spark.
- merge_message_flags += ["-m", body.replace("@", "")]
+ backport = _backport_of(body, pr_repo_desc.split("/", 1)[-1], target_ref)
+ if backport:
+ # The footer already names the author; a different --author would
contradict it.
+ print("Backport of #%s: keeping its commit message and author." %
backport[0])
+ # Soft check: the marker and footer are plain PR text, so confirm they
are some
+ # commit's message on the branch, as _land_via_fork leaves them.
+ commits = git.run(["git", "log", "--format=%b%x00", "HEAD..%s" %
pr_branch_name])
+ if backport[1] not in [_pick_message(c) for c in commits.split("\0")]:
Review Comment:
**Nit (P3):** The only case feeds a branch commit identical to the body and
asserts that no Backport-of prompt appears. A check that never fires gives the
same result, so replacing this condition with `False` would keep every doctest
green. An edited or mismatched body could then set the author and the `Closes
#N` footer of a merged backport PR without asking. A case whose branch commit
differs from the body, asserting the prompt, would cover it.
See **Shared repair plan 1** in the review body.
--
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]