spark-test commented on code in PR #60472:
URL: https://github.com/apache/spark/pull/60472#discussion_r4577039971
##########
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:
Thanks, confirmed: `[p]` now pushes the pick without the skip-checks
trailer, and `[d]` adds it right before the push to apache. One part of the
reply doesn't hold yet: a retried `[d]` on a sampled branch amends the pick
again rather than pushing the same commit, and this review raises that
separately.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4576372737","thread_id":"inline:4576372737","verdict_sha256":"2af83da94f1c84aa83e18622cff99198e5afa2718f58417ac85e6b7666f7c6f5"}
-->
##########
dev/merge_spark_pr.py:
##########
@@ -1209,12 +2072,507 @@ 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 _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)
+ if wanted != current:
Review Comment:
**Non-blocking (P2):** `--format=%B` is tformat, so git ends this output
with an extra newline, while `remove_inherited_post_merge_ci_skip` and
`append_post_merge_ci_skip` return a message ending in exactly one. Once HEAD
carries `skip-checks: true`, `wanted != current` is always true, so each `[d]`
attempt on a sampled pick amends again and moves HEAD to a new commit with the
same tree and message. That breaks the case the retry exists for: if a failed
push did land, the retried `[d]` pushes a sibling of the commit already on
apache, the push is rejected as non-fast-forward, and the error text steers the
committer to `[p]`, which opens a redundant backport PR, or `[s]`, which leaves
a branch that has the change out of the merge comment and the JIRA fix
versions. The `sampled()` doctest passes only because its `%B` mock omits git's
extra newline. Comparing without trailing newlines leaves HEAD alone when the
trailer is already right:
```suggestion
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)
if wanted.rstrip("\n") != current.rstrip("\n"):
```
This extends an [existing
discussion](https://github.com/apache/spark/pull/60472#discussion_r4576372737).
**Verification:**
- **Regression:** With HEAD's message read the way git reports it, ending in
one extra newline, a sampled pick answered [d], failed, and answered [d] again
is amended only once, and both pushes send the same commit.
- **Behavior:** A sampled pick answered [d] pushes a message ending in
exactly one skip-checks trailer after two empty lines, and answered [p], also
after a failed [d], pushes a message without it.
- **Compatibility:** An unsampled pick, or a pick onto a branch with no
sampling interval, is amended only to drop an inherited trailer, as before.
##########
dev/merge_spark_pr.py:
##########
@@ -3518,56 +5071,83 @@ 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. A merged backport
PR also inherits
+ # the original's branches, so [p] does not force-push over its other open
backport PRs.
+ if backport:
+ picks = _seed_picks(backport[0], target_ref, branch_names)
Review Comment:
**Non-blocking (P2):** This call runs after `merge_pr` has pushed the merge
but before the `try` whose `finally` closes this PR through the API, posts the
merge comment and runs `update_jira_for_pr`. `_seed_picks` makes a `git
ls-remote` against the fork and one GitHub read per matching fork branch, with
no timeout, and its helpers catch only `Exception`. So if the fork lookup
stalls or asks for an SSH passphrase and the committer presses Ctrl-C,
`KeyboardInterrupt` leaves `main()` before the `try`: the merged backport PR
stays open on GitHub with no merge comment and no JIRA update, although the
comments here say cancelling after the push must not drop them. Creating `picks
= _PickLedger([target_ref])` before the `try` and seeding as the first
statement inside it keeps that guarantee.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60472#discussion_r4576372741).
**Verification:**
- **Regression:** An interrupt raised from the seeding lookups after a
recognized backport PR has been merged still closes the PR, posts the merge
comment with the merge line, and reaches the JIRA update with the merged branch.
- **Compatibility:** Without an interrupt, a plain merge, a backport-PR
merge and a run on a merged backport PR give the pick loop the same default
exclusions, already-picked branches and pending branches as before.
##########
dev/merge_spark_pr.py:
##########
@@ -1146,41 +1974,76 @@ 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", 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]
+ # Deduplicate original authors by email; sign-offs do not credit fixup
authors.
+ credited = re.findall(
+ r"^(?:Lead-authored-by|Authored-by|Co-authored-by): (.+)$",
+ backport[1].rsplit("\n\n", 1)[-1],
Review Comment:
**Nit (P3):** This reads the original's credited authors from its final
paragraph only. When the original merge carried the sampled `skip-checks: true`
trailer, as about nine in ten merges into master or branch-4.x without
`do-not-skip-ci` do, `git cherry-pick -sx` appends `(cherry picked from commit
...)` and the sign-off to that trailer paragraph, and
`_set_skip_trailer(False)` then leaves them as a paragraph of their own. The
final paragraph then holds no author lines, and since `main()` passes every
commit author of a recognized backport PR, including the pick's own author, the
merged commit gets `--author="A <[email protected]>"` plus `Co-authored-by: A
<[email protected]>`. Nobody loses credit, but the duplicate lands in release-branch
history for most backport PRs that `[p]` opens. Reading the author lines of
every paragraph from the original's last merge footer on avoids it, while still
ignoring author lines quoted before that footer.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60472#discussion_r4576372744).
**Verification:**
- **Regression:** Merging a backport PR built from a pick of a sampled
original, with the pick's own author among the commit authors, adds no
Co-authored-by line for that author.
- **Behavior:** Fixup authors still get exactly one Co-authored-by line
each, a sign-off or a prose mention does not suppress it, and an author line
quoted before the original's footer does not count as credit.
##########
dev/merge_spark_pr.py:
##########
@@ -1010,19 +1247,137 @@ class SkipCherryPick(Exception):
"""
-def continue_maybe(prompt, cherry=False):
+def continue_maybe(prompt: str, cherry: bool = False) -> None:
+ """Prompt to continue; on "no" either skip this cherry-pick (`cherry`) or
exit the script.
+
+ `cherry` is the decline semantics, not a statement that a cherry-pick is
mid-flight: the
+ pre-push checks run after the pick is committed, and declining there must
still skip only
+ that branch. So the abort is attempted only when git says one is actually
in progress.
+
+ >>> from contextlib import redirect_stdout
+ >>> from io import StringIO
+ >>> from unittest.mock import call, patch
+
+ Declining with `cherry` while a pick is mid-flight aborts the pick before
skipping --
+ the first git call is the probe, the second the abort:
+
+ >>> with (
+ ... patch("builtins.input", return_value=""),
+ ... patch.object(git, "run", side_effect=["", ""]) as run,
+ ... redirect_stdout(StringIO()),
+ ... ):
+ ... try:
+ ... continue_maybe("Resolved?", cherry=True)
+ ... skipped = False
+ ... except SkipCherryPick:
+ ... skipped = True
+ >>> skipped
+ True
+ >>> run.call_args_list[0]
+ call(['git', 'rev-parse', '--verify', '--quiet', 'CHERRY_PICK_HEAD'])
+ >>> run.call_args_list[1]
+ call('git cherry-pick --abort')
+ >>> run.call_count
+ 2
+
+ After the pick is committed there is nothing to abort. A checkout git
refuses over
+ uncommitted edits waits for the committer to stash them, then the branch
is skipped:
+
+ >>> refused = subprocess.CalledProcessError(1, "git checkout")
+ >>> with (
+ ... patch("builtins.input", side_effect=["", ""]) as inp,
+ ... patch.object(git, "run", side_effect=[refused, refused, ""]) as
run,
+ ... patch.dict(continue_maybe.__globals__, original_head="master"),
+ ... patch.object(sys.modules[__name__], "clean_up") as clean,
+ ... redirect_stdout(StringIO()),
+ ... ):
+ ... try:
+ ... continue_maybe("Push anyway?", cherry=True)
+ ... skipped = False
+ ... except SkipCherryPick:
+ ... skipped = True
+ >>> skipped
+ True
+ >>> [c.args[0] for c in run.call_args_list[1:]]
+ [['git', 'checkout', 'master'], ['git', 'checkout', 'master']]
+ >>> inp.call_count, clean.call_count
+ (2, 1)
+
+ A checkout git keeps refusing, e.g. over a stale index.lock, can be given
up on:
+
+ >>> with (
+ ... patch("builtins.input", side_effect=["", "a"]),
+ ... patch.object(git, "run", side_effect=[refused, refused]),
+ ... patch.dict(continue_maybe.__globals__, original_head="master"),
+ ... redirect_stdout(StringIO()),
+ ... ):
+ ... try:
+ ... continue_maybe("Push anyway?", cherry=True)
+ ... exited = False
+ ... except SystemExit:
+ ... exited = True
+ >>> exited
+ True
+ """
if get_input(f"{prompt} (y/N): ", ["y", "n", ""]) != "y":
if cherry:
- try:
- git.run("git cherry-pick --abort")
- except Exception:
- print_error("Unable to abort and get back to the state before
cherry-pick")
+ if _cherry_pick_in_progress():
+ try:
+ git.run("git cherry-pick --abort")
+ except Exception:
+ print_error("Unable to abort and get back to the state
before cherry-pick")
+ else:
+ _restore_original_head()
print("Skipping this cherry-pick; the merge continues.")
clean_up()
raise SkipCherryPick()
fail("Okay, exiting")
+def _cherry_pick_in_progress() -> bool:
+ """True if the repo is mid-cherry-pick. With --quiet, exit 1 is git's "no
such ref" answer,
+ i.e. no pick in progress. Any other trouble answers "yes", so the caller
still attempts
+ the abort, as if a pick were in progress.
+
+ >>> from unittest.mock import patch
+ >>> answers = []
+ >>> for failure in (None, subprocess.CalledProcessError(1, "g"),
+ ... subprocess.CalledProcessError(128, "g"), OSError("no
git")):
+ ... with patch.object(git, "run", side_effect=failure):
+ ... answers.append(_cherry_pick_in_progress())
+ >>> answers
+ [True, False, True, True]
+ """
+ try:
+ git.run(["git", "rev-parse", "--verify", "--quiet",
"CHERRY_PICK_HEAD"])
+ return True
+ except subprocess.CalledProcessError as e:
+ return e.returncode != 1
+ except Exception:
+ return True
+
+
+def _restore_original_head():
+ """Check out original_head, waiting for the committer while git refuses
over local edits.
+
+ The committed pick is discarded by clean_up() afterwards; the edits are
theirs to keep, and
+ any git carries over to original_head are listed."""
+ if "original_head" not in globals():
+ return
+ while True:
+ try:
+ carried = git.run(["git", "checkout", original_head]).strip()
Review Comment:
**Nit (P3):** `git checkout` writes the branch's tracking status to stdout
along with any carried-over edits, so on a branch with an upstream this prints
`Uncommitted changes carried over to master:` followed by `Your branch is up to
date with 'origin/master'.` even when nothing was carried, on every `[s]` (the
landing prompt's default) and every declined pre-push check. Real edits come
mixed with that line, or with 'behind ... can be fast-forwarded' text when the
branch is behind. Checking out with `--quiet` and listing the edits from `git
status --porcelain --untracked-files=no` would print only the tracked changes
git carried over; a plain `git status --porcelain` would add any untracked
files the committer already had.
**Verification:**
- **Regression:** Skipping a pick when the original checkout is a branch
with an upstream and no tracked file has changed reports no uncommitted changes
carried over, also when an untracked file is present.
- **Behavior:** With a modified tracked file that git carries over, the skip
lists that file and no branch-tracking text, and a refused checkout still loops
until the committer retries or aborts.
##########
dev/merge_spark_pr.py:
##########
@@ -3438,43 +4992,42 @@ def main():
if merge_hash is not None:
# The change is already on target_ref and on any branch a previous run
backported it
# to, so exclude all of them: defaulting to one would cherry-pick an
empty commit.
- picked_refs = [target_ref] + [
- b for b in branches_with_merge_footer(pr_num, branch_names) if b
!= target_ref
- ]
- if len(picked_refs) > 1:
- print("Already backported to: %s" % ", ".join(picked_refs[1:]))
+ # For a merged backport PR, "it" is the original PR, whose footer the
commit carries
+ # and whose number _land_via_fork names its branches after.
+ picks = _seed_picks(merge_footer_pr(message) or pr_num, target_ref,
branch_names)
# Loop so one invocation can reach several maintenance branches, as
the merge path does.
- picked_commits = []
try:
while True:
- default = default_pick_branch(branch_names, tuple(picked_refs))
+ default = default_pick_branch(branch_names, picks.seen())
Review Comment:
**Nit (P3):** `picks.seen()` is the landed plus the pending branches, so
this keeps branches with only an open backport PR out of the default, as
intended. But `default_pick_branch`'s docstring still says `already_picked`
'holds the branches the change is known to be on' and that `None` means 'every
known branch already has it', and on `None` both loops print 'Every known
release branch already contains #N; nothing to pick.' Since `branch_names`
holds every `branch-*` on apache/spark, back to branch-0.5, that message
practically never prints; what remains is a stale contract that tells a
maintainer `already_picked` means landed. Describing `already_picked` as the
branches kept out of the default, landed or with an open backport PR, and
wording the message to match, for example 'already has #N or an open backport
PR for it', fixes both.
**Verification:**
- **Inspection:** default_pick_branch's docstring and the message both loops
print when it returns None describe the excluded branches as landed or with an
open backport PR, no longer say that every known branch contains the change,
and no code around them changes.
##########
dev/spark_merge_footer.py:
##########
@@ -108,8 +122,35 @@ def merge_footer_pr(message):
return int(matches[-1]) if matches else None
+def backport_pr(message):
+ """The backport PR merged by `message`, or None: a `Backport-PR` trailer
in the final
+ paragraph, after the generated footer, so one quoted in a body does not
count.
+
+ >>> footer = "Closes #7 from a/b.\\n\\nAuthored-by: A
<[email protected]>\\nSigned-off-by: C <[email protected]>"
+ >>> backport_pr("Fix\\n\\n%s\\nBackport-PR: #9\\nSigned-off-by: M
<[email protected]>" % footer)
+ 9
+ >>> backport_pr("Fix\\n\\nBackport-PR: #9\\n\\n" + footer) is None
+ True
+ >>> backport_pr("Fix\\n\\nBackport-PR: #9") is None
+ True
+
+ A trailing `skip-checks` paragraph, added for the post-merge CI sampling,
does not hide it:
+
+ >>> backport_pr("Fix\\n\\n%s\\nBackport-PR: #9\\n\\n\\nskip-checks:
true\\n" % footer)
+ 9
+ """
+ matches = list(_MERGE_FOOTER_RE.finditer(message))
+ if not matches:
+ return None
+ paragraphs = [p.strip() for p in message[matches[-1].start()
:].split("\n\n")]
+ while paragraphs and (not paragraphs[-1] or
paragraphs[-1].lower().startswith("skip-checks:")):
+ paragraphs.pop()
+ found = _BACKPORT_PR_RE.findall(paragraphs[-1]) if paragraphs else []
+ return int(found[-1]) if found else None
Review Comment:
**Nit (P3):** The merge path's own chained flow puts two trailers here:
picking merged backport PR #9 of #7 into another branch with `[p]` opens #10,
whose body carries #9's trailer block, and merging #10 appends `Backport-PR:
#10` to that same paragraph. Taking the last one is what makes #10 count as
merged and #9 not, but every doctest message in both files has a single
`Backport-PR` trailer, so `found[0]` would pass them all; `find_merge_commit`
would then treat #10 as unmerged and `dev/pr_merge_status.py 10` would report
it closed without merging. A `backport_pr` or `has_merge_footer` doctest with
both trailers in the final paragraph would pin it.
**Verification:**
- **Regression:** For a message whose final paragraph holds 'Backport-PR:
#9' and then 'Backport-PR: #10', the reader names #10, the commit counts as
merging #10 and the original PR, and it does not count as merging #9.
##########
dev/merge_spark_pr.py:
##########
@@ -1263,21 +2621,49 @@ def _do_cherry_pick(pr_num, merge_hash, pick_ref):
else:
print("Cherry-pick already completed manually; continuing with the
backport.")
- raw_message = git.run(["git", "log", "-1", "--format=%B"])
- updated_message = remove_inherited_post_merge_ci_skip(raw_message)
- if skip_post_merge_ci:
- updated_message = append_post_merge_ci_skip(updated_message)
- if updated_message != raw_message:
- amend_commit_message(updated_message)
+ _set_skip_trailer(False)
- 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.")
+ _restore_original_head()
+ clean_up()
+ raise SkipCherryPick()
+ if choice == "p":
+ _set_skip_trailer(False)
+ 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":
Review Comment:
**Nit (P3):** The only doctest of this confirmation answers `[d]`, declines
it and answers `[s]`, calling `_do_cherry_pick` directly and catching
`SkipCherryPick` itself, and `cherry_pick`'s `pick()` helper feeds
`_do_cherry_pick` only successful results. So nothing checks that an accepted
confirmation pushes, that `[p]` goes through without asking, that the `except
SkipCherryPick: return []` in `cherry_pick`'s pending branch turns a gated
`[s]` into an empty result instead of aborting the run, or that `[b]oth` still
returns the pending branch-M.x pick when the branch-M.N pick is skipped. Cases
for those four paths would pin them.
**Verification:**
- **Regression:** With branch-M.x pending, answering [d] and accepting the
confirmation pushes the pick, answering [p] behaves as the Upstream-First
decision leaves it, and answering [s] makes cherry_pick return no picks without
raising.
- **Regression:** In the [b]oth path, skipping the branch-M.N pick after
branch-M.x went to a backport PR still returns the branch-M.x pick with its
marker.
##########
dev/merge_spark_pr.py:
##########
@@ -1263,21 +2621,49 @@ def _do_cherry_pick(pr_num, merge_hash, pick_ref):
else:
print("Cherry-pick already completed manually; continuing with the
backport.")
- raw_message = git.run(["git", "log", "-1", "--format=%B"])
- updated_message = remove_inherited_post_merge_ci_skip(raw_message)
- if skip_post_merge_ci:
- updated_message = append_post_merge_ci_skip(updated_message)
- if updated_message != raw_message:
- amend_commit_message(updated_message)
+ _set_skip_trailer(False)
- 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.")
+ _restore_original_head()
Review Comment:
**Nit (P3):** The `land()` and `sampled()` helpers patch `clean_up` with a
`Mock` that no assertion reads and leave `original_head` unset, so this call
returns at once, and deleting it, or the `clean_up()` here or on `[p]`'s
success, passes every doctest. Without the cleanup a skip leaves HEAD on the
temporary pick branch, which the comment above says makes a later pick of the
same ref fail in `git fetch`; without the restore, a checkout git refuses over
local edits makes `clean_up()` raise out of the run instead of waiting as
`continue_maybe`'s decline does. One case with `original_head` set that asserts
the restore checkout and the `clean_up` calls would pin both.
**Verification:**
- **Regression:** Answering [s] restores the original checkout and cleans up
the temporary branches before the branch is skipped, and a successful [p]
cleans up before returning its marker, each checked by an assertion that fails
when that call is removed.
##########
dev/merge_spark_pr.py:
##########
@@ -3518,56 +5071,83 @@ 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. A merged backport
PR also inherits
+ # the original's branches, so [p] does not force-push over its other open
backport PRs.
Review Comment:
**Nit (P3):** The seeded ledger doesn't prevent that. It keeps the
original's landed and pending branches out of the next-pick default, but
`cherry_pick` still accepts any typed release branch, and `[p]` then
force-pushes to `backport-pr<N>-<branch>` and updates that open PR, the
retry-like behavior the previous round settled on. For example, after merging
backport PR #9 of #7 while #7 has an open backport PR for branch-4.1, typing
branch-4.1 and answering `[p]` pushes
`+PR_TOOL_PICK_PR_9_BRANCH-4.1:backport-pr7-branch-4.1`. Saying what the
seeding does keeps a maintainer from relying on a guard that isn't there:
```suggestion
# the original's branches: the default skips them; [p] on a typed
pending one updates its PR.
```
This extends an [existing
discussion](https://github.com/apache/spark/pull/60472#discussion_r4576372741).
**Verification:**
- **Inspection:** The comment no longer says the seeding stops [p] from
force-pushing over the original's open backport PRs, and it describes the
default exclusion and the retry-like update of an explicitly named branch.
##########
dev/merge_spark_pr.py:
##########
@@ -1119,6 +1866,7 @@ def amend_commit_message(message):
"git",
"commit",
"--amend",
+ "--only",
Review Comment:
**Nit (P3):** This flag keeps files staged during the pre-push checks out of
the landing-time amend that `_set_skip_trailer` makes: without it, `git commit
--amend` commits the index along with the new message, so a sampled `[d]` after
the committer ran `git add`, as the dirty-tree warning suggests, would push
those edits to the Apache branch. No doctest reads the amend argv, since the
`sampled()` helper matches only `cmd[:3] == ['git', 'commit', '--amend']`, so
dropping `--only` passes every doctest. Asserting it in that helper, or in an
`amend_commit_message` doctest, would pin it.
**Verification:**
- **Regression:** A doctest fails when the script's message-only amend is
issued without --only.
--
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]