holdenk commented on code in PR #60472:
URL: https://github.com/apache/spark/pull/60472#discussion_r4620974237


##########
dev/merge_spark_pr.py:
##########
@@ -948,9 +991,88 @@ def comment(self, pr_num, body):
             print_error("Failed to comment on PR #%s: HTTP %s %s" % (pr_num, 
e.code, e.reason))
             return None
 
+    def _api(self, url, method="GET", payload=None):
+        data = None if payload is None else json.dumps(payload).encode("utf-8")
+        request = Request(url, data=data, method=method)
+        request.add_header("Content-Type", "application/json")
+        request.add_header("Accept", "application/vnd.github+json")
+        if GITHUB_OAUTH_KEY:
+            request.add_header("Authorization", "token %s" % GITHUB_OAUTH_KEY)
+        return json.load(urlopen(request))
+
+    def open_pr(self, base, head):
+        """The open PR from `head` against `base`, or None -- also when the 
lookup fails.
+
+        >>> from contextlib import redirect_stdout
+        >>> from io import StringIO
+        >>> from unittest.mock import patch
+        >>> gh = GitHub()
+        >>> with patch.object(gh, "_api", return_value=[{"n": 1}, {"n": 2}]) 
as api:
+        ...     gh.open_pr("branch-4.2", "me:b")
+        {'n': 1}
+        >>> api.call_args.args[0].split("?")[1]
+        'state=open&base=branch-4.2&head=me%3Ab'
+        >>> with patch.object(gh, "_api", side_effect=OSError("down")), 
redirect_stdout(StringIO()):
+        ...     found = gh.open_pr("branch-4.2", "me:b")
+        >>> found is None
+        True
+        """
+        query = urlencode({"state": "open", "base": base, "head": head})
+        try:
+            found = self._api("%s/pulls?%s" % (GITHUB_API_BASE, query))
+        except Exception as e:
+            print_error("Could not look up open PRs from %s: %s" % (head, e))
+            return None
+        return found[0] if found else None
+
+    def create_pr(self, base, head, title, body):
+        """Open a draft PR from `head`, or refresh the open one; None on 
failure or no token.
+
+        >>> from contextlib import redirect_stdout
+        >>> from io import StringIO
+        >>> from unittest.mock import patch
+        >>> def create(found, fails=False, token="t"):
+        ...     calls = []
+        ...     def api(url, method="GET", payload=None):
+        ...         calls.append((url.split("/")[-1], method, payload))
+        ...         if fails and method != "GET":
+        ...             raise OSError("HTTP 422")
+        ...         return found if method == "GET" else {"html_url": "pr"}
+        ...     gh = GitHub()
+        ...     with (
+        ...         patch.object(gh, "_api", side_effect=api),
+        ...         patch.dict(GitHub.create_pr.__globals__, 
GITHUB_OAUTH_KEY=token),
+        ...         redirect_stdout(StringIO()),
+        ...     ):
+        ...         return gh.create_pr("branch-4.2", "me:b", "T", "B"), calls
+        >>> url, method, payload = create([])[1][1]
+        >>> url, method, payload["draft"], payload["head"], payload["base"]
+        ('pulls', 'POST', True, 'me:b', 'branch-4.2')
+        >>> create([{"url": "u/pulls/5", "html_url": "h"}])[1][1]
+        ('5', 'PATCH', {'title': 'T', 'body': 'B'})
+        >>> create([], fails=True)[0], create([], token="")
+        (None, (None, []))
+        """
+        # Opening a PR is a write and needs auth; without a token, skip rather 
than 401.
+        if not GITHUB_OAUTH_KEY:
+            print_error("GITHUB_OAUTH_KEY is not set; skipping the backport 
PR.")
+            return None
+        existing = self.open_pr(base, head)
+        try:
+            if existing:
+                # A retry force-pushed the branch. Refresh the PR too: 
merge_pr turns its body
+                # into the commit message.
+                print("Updating the open backport PR %s." % 
existing["html_url"])
+                return self._api(existing["url"], "PATCH", {"title": title, 
"body": body})
+            payload = {"title": title, "head": head, "base": base, "body": 
body, "draft": True}

Review Comment:
   Sure we can raise at as non-draft PR; draft was a probable a mistake on my 
point.



-- 
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]

Reply via email to