eddieland-canopy-github 0.14.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- canopy_github/__init__.py +504 -0
- canopy_github/connect.py +267 -0
- canopy_github/issues.py +682 -0
- canopy_github/post.py +866 -0
- canopy_github/read.py +656 -0
- canopy_github/repository.py +91 -0
- eddieland_canopy_github-0.14.0.dist-info/METADATA +115 -0
- eddieland_canopy_github-0.14.0.dist-info/RECORD +10 -0
- eddieland_canopy_github-0.14.0.dist-info/WHEEL +4 -0
- eddieland_canopy_github-0.14.0.dist-info/entry_points.txt +3 -0
canopy_github/post.py
ADDED
|
@@ -0,0 +1,866 @@
|
|
|
1
|
+
"""`canopy-post-github`: posts what the operator approved in canopy, word for word (DESIGN §29, §34).
|
|
2
|
+
|
|
3
|
+
On stdin, one JSON object: one PR's drafts, `{"pr": URL, "delete_pending": ID | null, "body": TEXT | null,
|
|
4
|
+
"replies": [{"comment": ID, "text": TEXT | null, "reaction": REACTION | null}, ...]}`, posted as one review: a pending
|
|
5
|
+
review, each reply's text added to the thread of the review comment it names, the body as the review's, submitted as
|
|
6
|
+
`COMMENT`; or one ticket's, `{"issue": URL, "ticket": KEY, "body": TEXT}`, posted as one comment on that issue, which
|
|
7
|
+
must be numbered as the key is. A review of a PR canopy reviewed (§34) names the commit it read, `"commit": SHA`, and
|
|
8
|
+
its comments, `"comments": [{"path": PATH, "line": N, "text": TEXT}, ...]`: the pending review is opened on that
|
|
9
|
+
commit, and each comment starts a thread of its own on line N of PATH, on the commit's side, before the submit. A
|
|
10
|
+
PR's drafts with `"submit": false` are staged instead: the pending review is opened with the body as its own and each
|
|
11
|
+
reply and comment added, and left for the operator to submit on GitHub. `delete_pending` names a pending review an
|
|
12
|
+
earlier post left, which is deleted first, and only if it is still pending, on that PR, and the poster's own.
|
|
13
|
+
|
|
14
|
+
GitHub keeps one pending review a person on a PR, so a stage on a PR where the poster already has one adds to that one
|
|
15
|
+
instead, joining it: its own comments and body stay as they are, and it is neither submitted nor deleted. A reply or a
|
|
16
|
+
comment it already holds, word for word on the same thread or line, as an earlier stage that stopped part way left, is
|
|
17
|
+
not added again. The body goes in as the review's own when it has none, and below it, after a blank line, when it has
|
|
18
|
+
one that does not already hold it, so neither text is lost. A review whose comments sit on another commit than the
|
|
19
|
+
request's, or whose body and the request's together are longer than GitHub takes, is refused, and nothing is added. A
|
|
20
|
+
post that submits is refused on such a PR, since submitting would submit what the review already holds. A pending
|
|
21
|
+
review that turns up between the look and the opening is joined as well.
|
|
22
|
+
|
|
23
|
+
A reply's `reaction`, one of `+1`, `-1`, `laugh`, `confused`, `heart`, `hooray`, `rocket`, and `eyes`, is added to the
|
|
24
|
+
comment it names before the review is opened, staged or not, since GitHub has no pending reaction; a reply with a
|
|
25
|
+
reaction and no text adds the reaction alone, and a PR's drafts that are all such open no review.
|
|
26
|
+
|
|
27
|
+
On stdout, one JSON line each: `as`, the login it posts as; for a PR, `reaction` for each reaction added (the comment,
|
|
28
|
+
the reaction, and the comment's URL), then `pending`, the pending review's node id and its id, once it has one, with
|
|
29
|
+
`"joined": true` for one it joined; once it is submitted, `comment` for each reply (the comment it answered, the new
|
|
30
|
+
comment's id and URL), and for each of `comments` (its `index` there, from 1, and the new comment's id and URL), and
|
|
31
|
+
`review` (its id and URL); once a staged review holds every reply and comment, their `comment` lines; for an issue,
|
|
32
|
+
`comment`; last, `end`, saying whether it submitted: `"submitted": true` once the review or the issue comment is
|
|
33
|
+
submitted, or once every reaction is added when there is nothing else to post; `"submitted": false, "staged": true`
|
|
34
|
+
once a staged review holds every reply, with `"joined": true` for one it joined. A joined review GitHub refused part of
|
|
35
|
+
is left as it is, never deleted: the `comment` lines name each reply and comment it now holds, and `end` says
|
|
36
|
+
`"submitted": false, "joined": true`, so a later stage adds only the rest. Otherwise `"submitted": false` is printed
|
|
37
|
+
only when nothing but the reactions its `reaction` lines name was posted, with `pending` naming a pending review it
|
|
38
|
+
could not delete; a pending review GitHub may have opened without saying so is looked for and deleted. No `end` line
|
|
39
|
+
means the outcome is unknown: the submit may have reached GitHub. A reaction GitHub already holds is not added twice, so
|
|
40
|
+
a reaction whose outcome is unknown is one to send again, never one that can post twice.
|
|
41
|
+
|
|
42
|
+
It never approves, requests changes, resolves a thread, or deletes a review but the pending one it is handed, or one it
|
|
43
|
+
opened and could not fill; never one it joined.
|
|
44
|
+
|
|
45
|
+
Exit codes: 0 posted; 1 GitHub refused, or the outcome is unknown, as the `end` line says; 2 stdin or the command line
|
|
46
|
+
is not usable, `gh` holds no token for the host, or a reply names a comment the PR has no thread for, and nothing was
|
|
47
|
+
posted. A comment GitHub refuses, as on a line its diff of the PR does not show, posts nothing of a review the poster
|
|
48
|
+
opened, and the error names it.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
from __future__ import annotations
|
|
52
|
+
|
|
53
|
+
import re
|
|
54
|
+
import sys
|
|
55
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
56
|
+
from dataclasses import dataclass
|
|
57
|
+
from typing import Final, TextIO
|
|
58
|
+
|
|
59
|
+
import click
|
|
60
|
+
|
|
61
|
+
from canopy_github import (
|
|
62
|
+
Client,
|
|
63
|
+
GitHubError,
|
|
64
|
+
Hosts,
|
|
65
|
+
InputError,
|
|
66
|
+
Ref,
|
|
67
|
+
client_for,
|
|
68
|
+
emit,
|
|
69
|
+
items,
|
|
70
|
+
number,
|
|
71
|
+
obj,
|
|
72
|
+
parse_issue,
|
|
73
|
+
parse_pr,
|
|
74
|
+
read_input,
|
|
75
|
+
text,
|
|
76
|
+
)
|
|
77
|
+
from canopy_github.read import threads
|
|
78
|
+
|
|
79
|
+
#: GitHub's own limit on a comment's body.
|
|
80
|
+
MAX_TEXT: Final = 65536
|
|
81
|
+
#: Each reaction a reply may add, by the name canopy and GitHub's REST API give it, to the name GraphQL takes.
|
|
82
|
+
REACTIONS: Final = {
|
|
83
|
+
"+1": "THUMBS_UP",
|
|
84
|
+
"-1": "THUMBS_DOWN",
|
|
85
|
+
"laugh": "LAUGH",
|
|
86
|
+
"confused": "CONFUSED",
|
|
87
|
+
"heart": "HEART",
|
|
88
|
+
"hooray": "HOORAY",
|
|
89
|
+
"rocket": "ROCKET",
|
|
90
|
+
"eyes": "EYES",
|
|
91
|
+
}
|
|
92
|
+
MAX_REPLIES: Final = 100
|
|
93
|
+
#: As many comments as replies: canopy sends at most 30 (DESIGN §34).
|
|
94
|
+
MAX_COMMENTS: Final = 100
|
|
95
|
+
#: A commit's full object id, SHA-1 or SHA-256, as GitHub's `GitObjectID` takes it.
|
|
96
|
+
_COMMIT: Final = re.compile(r"[0-9a-f]{40}|[0-9a-f]{64}")
|
|
97
|
+
#: A key a GitHub Issues tracker gives a ticket: letters, a hyphen, the issue's number (DESIGN §17).
|
|
98
|
+
_KEY: Final = re.compile(r"[A-Za-z][A-Za-z0-9_]*-([1-9][0-9]{0,9})")
|
|
99
|
+
#: How many pages of a joined review's comments are read to find those already in it: 100 to a page.
|
|
100
|
+
_MAX_HELD_PAGES: Final = 20
|
|
101
|
+
#: What GitHub's refusal to open a second pending review a person says.
|
|
102
|
+
_ONE_PENDING: Final = "one pending review"
|
|
103
|
+
|
|
104
|
+
_VIEWER: Final = "query Viewer { viewer { login } }"
|
|
105
|
+
_PR_ID: Final = """
|
|
106
|
+
query PullRequestId($owner: String!, $name: String!, $number: Int!) {
|
|
107
|
+
repository(owner: $owner, name: $name) { pullRequest(number: $number) { id } }
|
|
108
|
+
}
|
|
109
|
+
"""
|
|
110
|
+
_ISSUE_ID: Final = """
|
|
111
|
+
query IssueId($owner: String!, $name: String!, $number: Int!) {
|
|
112
|
+
repository(owner: $owner, name: $name) { issue(number: $number) { id } }
|
|
113
|
+
}
|
|
114
|
+
"""
|
|
115
|
+
_PENDING: Final = """
|
|
116
|
+
query PendingReviews($owner: String!, $name: String!, $number: Int!) {
|
|
117
|
+
repository(owner: $owner, name: $name) {
|
|
118
|
+
pullRequest(number: $number) {
|
|
119
|
+
reviews(states: [PENDING], first: 10) {
|
|
120
|
+
nodes { id fullDatabaseId author { login } body comments { totalCount } }
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
"""
|
|
126
|
+
_HELD: Final = """
|
|
127
|
+
query PendingReview($id: ID!, $after: String) {
|
|
128
|
+
node(id: $id) {
|
|
129
|
+
... on PullRequestReview {
|
|
130
|
+
state body commit { oid }
|
|
131
|
+
comments(first: 100, after: $after) {
|
|
132
|
+
nodes { fullDatabaseId url body path line originalLine replyTo { fullDatabaseId } }
|
|
133
|
+
pageInfo { hasNextPage endCursor }
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
"""
|
|
139
|
+
_REVIEW: Final = """
|
|
140
|
+
query Review($id: ID!) {
|
|
141
|
+
node(id: $id) { ... on PullRequestReview { state author { login } pullRequest { id } } }
|
|
142
|
+
}
|
|
143
|
+
"""
|
|
144
|
+
_ADD_REVIEW: Final = """
|
|
145
|
+
mutation AddReview($pr: ID!, $body: String, $commit: GitObjectID) {
|
|
146
|
+
addPullRequestReview(input: {pullRequestId: $pr, body: $body, commitOID: $commit}) {
|
|
147
|
+
pullRequestReview { id fullDatabaseId }
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
"""
|
|
151
|
+
_REPLY: Final = """
|
|
152
|
+
mutation Reply($review: ID!, $thread: ID!, $body: String!) {
|
|
153
|
+
addPullRequestReviewThreadReply(
|
|
154
|
+
input: {pullRequestReviewId: $review, pullRequestReviewThreadId: $thread, body: $body}
|
|
155
|
+
) {
|
|
156
|
+
comment { fullDatabaseId url }
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
"""
|
|
160
|
+
_THREAD: Final = """
|
|
161
|
+
mutation Thread($review: ID!, $path: String!, $line: Int!, $body: String!) {
|
|
162
|
+
addPullRequestReviewThread(
|
|
163
|
+
input: {pullRequestReviewId: $review, path: $path, line: $line, side: RIGHT, body: $body}
|
|
164
|
+
) {
|
|
165
|
+
thread { comments(first: 1) { nodes { fullDatabaseId url } } }
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
"""
|
|
169
|
+
_SUBMIT: Final = """
|
|
170
|
+
mutation Submit($review: ID!, $body: String) {
|
|
171
|
+
submitPullRequestReview(input: {pullRequestReviewId: $review, event: COMMENT, body: $body}) {
|
|
172
|
+
pullRequestReview { fullDatabaseId url state }
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
"""
|
|
176
|
+
_UPDATE: Final = """
|
|
177
|
+
mutation UpdateReview($review: ID!, $body: String!) {
|
|
178
|
+
updatePullRequestReview(input: {pullRequestReviewId: $review, body: $body}) { pullRequestReview { id } }
|
|
179
|
+
}
|
|
180
|
+
"""
|
|
181
|
+
_DELETE: Final = """
|
|
182
|
+
mutation Delete($review: ID!) { deletePullRequestReview(input: {pullRequestReviewId: $review}) { clientMutationId } }
|
|
183
|
+
"""
|
|
184
|
+
_REACT: Final = """
|
|
185
|
+
mutation React($subject: ID!, $content: ReactionContent!) {
|
|
186
|
+
addReaction(input: {subjectId: $subject, content: $content}) { reaction { content } }
|
|
187
|
+
}
|
|
188
|
+
"""
|
|
189
|
+
_COMMENT: Final = """
|
|
190
|
+
mutation Comment($subject: ID!, $body: String!) {
|
|
191
|
+
addComment(input: {subjectId: $subject, body: $body}) { commentEdge { node { fullDatabaseId url } } }
|
|
192
|
+
}
|
|
193
|
+
"""
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
@dataclass(frozen=True)
|
|
197
|
+
class Reply:
|
|
198
|
+
"""A reply to post: the review comment whose thread it answers, its text, and its reaction on that comment.
|
|
199
|
+
|
|
200
|
+
At least one of the text and the reaction is set.
|
|
201
|
+
"""
|
|
202
|
+
|
|
203
|
+
comment: int
|
|
204
|
+
text: str | None
|
|
205
|
+
reaction: str | None
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
@dataclass(frozen=True)
|
|
209
|
+
class NewComment:
|
|
210
|
+
"""A comment that starts a thread of its own: the file, the line on the commit's side, and its text."""
|
|
211
|
+
|
|
212
|
+
path: str
|
|
213
|
+
line: int
|
|
214
|
+
text: str
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
@dataclass(frozen=True)
|
|
218
|
+
class Review:
|
|
219
|
+
"""One PR's drafts, to post as one comment review, or with `submit` false to stage as a pending one.
|
|
220
|
+
|
|
221
|
+
A review of a commit canopy reviewed names it, `commit`, and carries its `comments`, each a thread of its own.
|
|
222
|
+
"""
|
|
223
|
+
|
|
224
|
+
pr: Ref
|
|
225
|
+
delete_pending: str | None
|
|
226
|
+
body: str | None
|
|
227
|
+
replies: tuple[Reply, ...]
|
|
228
|
+
submit: bool = True
|
|
229
|
+
commit: str | None = None
|
|
230
|
+
comments: tuple[NewComment, ...] = ()
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
@dataclass(frozen=True)
|
|
234
|
+
class IssueComment:
|
|
235
|
+
"""One ticket's draft, to post as one comment on its issue."""
|
|
236
|
+
|
|
237
|
+
issue: Ref
|
|
238
|
+
body: str
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
@dataclass(frozen=True)
|
|
242
|
+
class Pending:
|
|
243
|
+
"""The poster's own pending review on a PR, as read before a stage adds to it."""
|
|
244
|
+
|
|
245
|
+
node: str
|
|
246
|
+
id: int | None
|
|
247
|
+
body: str
|
|
248
|
+
#: The commit it is opened on, if GitHub names one.
|
|
249
|
+
commit: str | None
|
|
250
|
+
#: Each comment it holds, as GitHub's `comments` of the review lists them.
|
|
251
|
+
comments: tuple[Mapping[str, object], ...]
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
class UnknownOutcomeError(GitHubError):
|
|
255
|
+
"""A submit or a comment that may have reached GitHub: no `end` line is printed for it."""
|
|
256
|
+
|
|
257
|
+
def __init__(self, cause: GitHubError) -> None:
|
|
258
|
+
"""Wrap `cause`, which left the outcome unknown."""
|
|
259
|
+
super().__init__(f"the outcome is unknown: {cause}", certain=False)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
class Out:
|
|
263
|
+
"""What the program prints, and whether its `end` line is printed yet."""
|
|
264
|
+
|
|
265
|
+
def __init__(self, stdout: TextIO) -> None:
|
|
266
|
+
"""Print to `stdout`."""
|
|
267
|
+
self._stdout = stdout
|
|
268
|
+
self.ended = False
|
|
269
|
+
|
|
270
|
+
def line(self, line: Mapping[str, object]) -> None:
|
|
271
|
+
"""Print one line."""
|
|
272
|
+
emit(self._stdout, line)
|
|
273
|
+
if line.get("kind") == "end":
|
|
274
|
+
self.ended = True
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
@click.command("canopy-post-github", context_settings={"help_option_names": ["-h", "--help"]})
|
|
278
|
+
@click.pass_context
|
|
279
|
+
def main(ctx: click.Context) -> None:
|
|
280
|
+
"""Post what the operator approved in canopy, word for word (DESIGN §29, §34).
|
|
281
|
+
|
|
282
|
+
What to post is one JSON object on stdin; what was posted is JSON lines on stdout, the `end` line last.
|
|
283
|
+
"""
|
|
284
|
+
hosts = ctx.find_object(Hosts) or Hosts()
|
|
285
|
+
out = Out(sys.stdout)
|
|
286
|
+
try:
|
|
287
|
+
request = parse_request(read_input(sys.stdin))
|
|
288
|
+
ref = request.pr if isinstance(request, Review) else request.issue
|
|
289
|
+
client = client_for(ref.host, hosts.endpoint_of, hosts.token_of)
|
|
290
|
+
except InputError as e:
|
|
291
|
+
print(f"canopy-post-github: {e}", file=sys.stderr) # noqa: T201
|
|
292
|
+
ctx.exit(2)
|
|
293
|
+
try:
|
|
294
|
+
login = _id(obj(client.query(_VIEWER, {}).get("viewer"), "viewer").get("login"), "viewer's login")
|
|
295
|
+
out.line({"kind": "as", "login": login})
|
|
296
|
+
if isinstance(request, Review):
|
|
297
|
+
post_review(client, request, login, out)
|
|
298
|
+
else:
|
|
299
|
+
post_comment(client, request, out)
|
|
300
|
+
except InputError as e:
|
|
301
|
+
# Refused before anything was opened, so nothing was posted.
|
|
302
|
+
out.line({"kind": "end", "submitted": False})
|
|
303
|
+
print(f"canopy-post-github: {e}", file=sys.stderr) # noqa: T201
|
|
304
|
+
ctx.exit(2)
|
|
305
|
+
except GitHubError as e:
|
|
306
|
+
# Anything but an unknown submit failed before what it posted could be seen.
|
|
307
|
+
if not out.ended and not isinstance(e, UnknownOutcomeError):
|
|
308
|
+
out.line({"kind": "end", "submitted": False})
|
|
309
|
+
print(f"canopy-post-github: {e}", file=sys.stderr) # noqa: T201
|
|
310
|
+
ctx.exit(1)
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def parse_request(request: Mapping[str, object]) -> Review | IssueComment:
|
|
314
|
+
"""Read one PR's or one ticket's drafts from what stdin held.
|
|
315
|
+
|
|
316
|
+
Returns:
|
|
317
|
+
What to post.
|
|
318
|
+
|
|
319
|
+
Raises:
|
|
320
|
+
InputError: It is neither shape, a text is empty or too long, or a reaction is not one GitHub offers.
|
|
321
|
+
"""
|
|
322
|
+
if "issue" in request:
|
|
323
|
+
issue = parse_issue(request.get("issue"))
|
|
324
|
+
key = request.get("ticket")
|
|
325
|
+
match = _KEY.fullmatch(key) if isinstance(key, str) else None
|
|
326
|
+
if match is None or int(match.group(1)) != issue.number:
|
|
327
|
+
raise InputError(f"ticket {key!r} is not issue #{issue.number}'s key")
|
|
328
|
+
return IssueComment(issue=issue, body=_text(request.get("body"), "body"))
|
|
329
|
+
pr = parse_pr(request.get("pr"))
|
|
330
|
+
pending = request.get("delete_pending")
|
|
331
|
+
if pending is not None and not (isinstance(pending, str) and pending):
|
|
332
|
+
raise InputError("delete_pending must be a review's id or null")
|
|
333
|
+
raw = request.get("replies", [])
|
|
334
|
+
if not isinstance(raw, list) or len(raw) > MAX_REPLIES:
|
|
335
|
+
raise InputError(f"replies must be a list of at most {MAX_REPLIES}")
|
|
336
|
+
replies = tuple(_reply(r) for r in raw)
|
|
337
|
+
commit, comments = _comments(request)
|
|
338
|
+
body = request.get("body")
|
|
339
|
+
if body is None and not replies and not comments:
|
|
340
|
+
raise InputError("there is nothing to post: no body, no replies, and no comments")
|
|
341
|
+
submit = request.get("submit", True)
|
|
342
|
+
if not isinstance(submit, bool):
|
|
343
|
+
raise InputError("submit must be true or false")
|
|
344
|
+
return Review(
|
|
345
|
+
pr=pr,
|
|
346
|
+
delete_pending=pending,
|
|
347
|
+
body=None if body is None else _text(body, "body"),
|
|
348
|
+
replies=replies,
|
|
349
|
+
submit=submit,
|
|
350
|
+
commit=commit,
|
|
351
|
+
comments=comments,
|
|
352
|
+
)
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def _comments(request: Mapping[str, object]) -> tuple[str | None, tuple[NewComment, ...]]:
|
|
356
|
+
"""The commit a review is opened on and the comments that start threads on it, if the request names them.
|
|
357
|
+
|
|
358
|
+
Returns:
|
|
359
|
+
The commit, or None, and the comments.
|
|
360
|
+
|
|
361
|
+
Raises:
|
|
362
|
+
InputError: The commit is not a full commit id, or a comment is not a file, a line, and a text; or comments
|
|
363
|
+
come without a commit.
|
|
364
|
+
"""
|
|
365
|
+
commit = request.get("commit")
|
|
366
|
+
if commit is not None and not (isinstance(commit, str) and _COMMIT.fullmatch(commit)):
|
|
367
|
+
raise InputError("commit must be a commit's full id")
|
|
368
|
+
raw = request.get("comments", [])
|
|
369
|
+
if not isinstance(raw, list) or len(raw) > MAX_COMMENTS:
|
|
370
|
+
raise InputError(f"comments must be a list of at most {MAX_COMMENTS}")
|
|
371
|
+
if raw and commit is None:
|
|
372
|
+
raise InputError("comments need the commit they are on")
|
|
373
|
+
comments: list[NewComment] = []
|
|
374
|
+
for found in raw:
|
|
375
|
+
entry = items([found])
|
|
376
|
+
path = text(entry[0].get("path")) if entry else None
|
|
377
|
+
line = number(entry[0].get("line")) if entry else None
|
|
378
|
+
if not path or line is None or isinstance(entry[0].get("line"), str):
|
|
379
|
+
raise InputError("each comment needs its file's path, a line, and its text")
|
|
380
|
+
comments.append(NewComment(path=path, line=line, text=_text(entry[0].get("text"), "comment")))
|
|
381
|
+
return commit, tuple(comments)
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def _reply(raw: object) -> Reply:
|
|
385
|
+
found = items([raw])
|
|
386
|
+
comment = number(found[0].get("comment")) if found else None
|
|
387
|
+
if comment is None:
|
|
388
|
+
raise InputError("each reply needs the id of the review comment it answers, and its text or reaction")
|
|
389
|
+
reaction, text = found[0].get("reaction"), found[0].get("text")
|
|
390
|
+
if reaction is not None and reaction not in REACTIONS:
|
|
391
|
+
raise InputError(f"a reply's reaction must be one of {', '.join(REACTIONS)}")
|
|
392
|
+
if reaction is not None and text is None:
|
|
393
|
+
return Reply(comment=comment, text=None, reaction=str(reaction))
|
|
394
|
+
return Reply(comment=comment, text=_text(text, "reply"), reaction=None if reaction is None else str(reaction))
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def _text(value: object, what: str) -> str:
|
|
398
|
+
if not isinstance(value, str) or not value.strip():
|
|
399
|
+
raise InputError(f"the {what} is empty")
|
|
400
|
+
if len(value) > MAX_TEXT:
|
|
401
|
+
raise InputError(f"the {what} is longer than GitHub's {MAX_TEXT} characters")
|
|
402
|
+
return value
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def post_review(client: Client, review: Review, login: str, out: Out) -> None:
|
|
406
|
+
"""Post `review`'s drafts as one comment review, or stage them as a pending one, printing as the module says.
|
|
407
|
+
|
|
408
|
+
A stage on a PR where the poster has a pending review already adds to that one (`_join`).
|
|
409
|
+
|
|
410
|
+
Raises:
|
|
411
|
+
InputError: A reply names a comment the PR has no thread for, or the pending review to delete is not one.
|
|
412
|
+
GitHubError: GitHub refused a reaction, which opened no review; the poster's own pending review cannot take
|
|
413
|
+
this one, and nothing was posted; or as `_submit` and `_join` raise it.
|
|
414
|
+
"""
|
|
415
|
+
pr = review.pr
|
|
416
|
+
found = {line.get("id"): (thread.id, line) for thread in threads(client, pr) for line in thread.comments}
|
|
417
|
+
missing = [r.comment for r in review.replies if r.comment not in found]
|
|
418
|
+
if missing:
|
|
419
|
+
raise InputError(f"{pr.url} has no review thread with comment {', '.join(map(str, missing))}")
|
|
420
|
+
variables = {"owner": pr.owner, "name": pr.name, "number": pr.number}
|
|
421
|
+
pr_id = _id(obj(_repository(client, _PR_ID, variables).get("pullRequest"), "pullRequest").get("id"), "PR's id")
|
|
422
|
+
if review.delete_pending is not None:
|
|
423
|
+
_delete_left(client, review.delete_pending, pr_id, login)
|
|
424
|
+
replies = [(r.comment, found[r.comment][0], r.text) for r in review.replies if r.text is not None]
|
|
425
|
+
opens = review.body is not None or bool(replies) or bool(review.comments)
|
|
426
|
+
# Looked for before anything is added, so a review that cannot take this one is refused with nothing posted.
|
|
427
|
+
own = _own_pending(client, pr, login) if opens else None
|
|
428
|
+
if own is not None:
|
|
429
|
+
_check_joinable(own, review)
|
|
430
|
+
# First, since GitHub adds a reaction once however often it is asked: one added before a review that then fails
|
|
431
|
+
# stays added, and sending again adds nothing more.
|
|
432
|
+
for reply in review.replies:
|
|
433
|
+
if reply.reaction is not None:
|
|
434
|
+
_react(client, reply.comment, found[reply.comment][1], reply.reaction, out)
|
|
435
|
+
if not opens:
|
|
436
|
+
out.line({"kind": "end", "submitted": True})
|
|
437
|
+
return
|
|
438
|
+
joining = _Joining(replies=replies, thread_of={c: t for c, (t, _) in found.items() if isinstance(c, int)})
|
|
439
|
+
if own is not None:
|
|
440
|
+
_join(client, own, review, joining, out)
|
|
441
|
+
return
|
|
442
|
+
_submit(client, pr, pr_id, review, joining, login, out)
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
@dataclass(frozen=True)
|
|
446
|
+
class _Joining:
|
|
447
|
+
"""What a review adds as replies, and the thread each comment of the PR's is on, to know one already added."""
|
|
448
|
+
|
|
449
|
+
#: Each reply: the comment answered, its thread's node id, and the text.
|
|
450
|
+
replies: Sequence[tuple[int, str, str]]
|
|
451
|
+
#: Each review comment of the PR's threads, by its id, to its thread's node id.
|
|
452
|
+
thread_of: Mapping[int, str]
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def _own_pending(client: Client, pr: Ref, login: str) -> Pending | None:
|
|
456
|
+
"""The poster's own pending review on `pr`, if it has one, read whole: GitHub keeps one a person.
|
|
457
|
+
|
|
458
|
+
Returns:
|
|
459
|
+
It, or None.
|
|
460
|
+
|
|
461
|
+
Raises:
|
|
462
|
+
GitHubError: GitHub refused to look, or the review was submitted or deleted while it was read.
|
|
463
|
+
"""
|
|
464
|
+
variables = {"owner": pr.owner, "name": pr.name, "number": pr.number}
|
|
465
|
+
found = obj(_repository(client, _PENDING, variables).get("pullRequest"), "pullRequest")
|
|
466
|
+
for node in items(obj(found.get("reviews"), "reviews").get("nodes")):
|
|
467
|
+
review = text(node.get("id"))
|
|
468
|
+
if _author(node) == login and review:
|
|
469
|
+
return _held(client, review, number(node.get("fullDatabaseId")))
|
|
470
|
+
return None
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def _held(client: Client, review: str, review_id: int | None) -> Pending:
|
|
474
|
+
"""Pending review `review`, whose id is `review_id`, with every comment it holds.
|
|
475
|
+
|
|
476
|
+
Returns:
|
|
477
|
+
It.
|
|
478
|
+
|
|
479
|
+
Raises:
|
|
480
|
+
GitHubError: It is no longer pending, it holds more comments than are read, or GitHub refused a page.
|
|
481
|
+
"""
|
|
482
|
+
comments: list[Mapping[str, object]] = []
|
|
483
|
+
after: str | None = None
|
|
484
|
+
for _ in range(_MAX_HELD_PAGES):
|
|
485
|
+
node = obj(client.query(_HELD, {"id": review, "after": after}).get("node"), "pending review")
|
|
486
|
+
if node.get("state") != "PENDING":
|
|
487
|
+
raise GitHubError(f"your pending review {review} was submitted or deleted meanwhile", certain=True)
|
|
488
|
+
connection = obj(node.get("comments"), "comments")
|
|
489
|
+
comments.extend(items(connection.get("nodes")))
|
|
490
|
+
info = obj(connection.get("pageInfo"), "pageInfo")
|
|
491
|
+
after = text(info.get("endCursor"))
|
|
492
|
+
if info.get("hasNextPage") is not True or after is None:
|
|
493
|
+
commit = node.get("commit")
|
|
494
|
+
return Pending(
|
|
495
|
+
node=review,
|
|
496
|
+
id=review_id,
|
|
497
|
+
body=text(node.get("body")) or "",
|
|
498
|
+
commit=text(commit.get("oid")) if isinstance(commit, dict) else None,
|
|
499
|
+
comments=tuple(comments),
|
|
500
|
+
)
|
|
501
|
+
raise GitHubError(f"your pending review {review} holds too many comments to check which are added", certain=True)
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def _check_joinable(own: Pending, review: Review) -> None:
|
|
505
|
+
"""Refuse to add `review` to the poster's own pending review `own` when it cannot take it as it is.
|
|
506
|
+
|
|
507
|
+
Raises:
|
|
508
|
+
GitHubError: `review` submits, which would submit what `own` holds too; its comments sit on another commit
|
|
509
|
+
than `own`; or the two bodies together are longer than GitHub takes. Nothing is added.
|
|
510
|
+
"""
|
|
511
|
+
where = f"you have a pending review on {review.pr.url}"
|
|
512
|
+
if review.submit:
|
|
513
|
+
raise GitHubError(
|
|
514
|
+
f"{where}, and GitHub keeps one pending review a person: submitting would submit what it holds too, so "
|
|
515
|
+
"canopy added nothing. Submit or delete it on GitHub, or stage this instead, which adds to it",
|
|
516
|
+
certain=True,
|
|
517
|
+
)
|
|
518
|
+
if review.comments and own.commit != review.commit:
|
|
519
|
+
raise GitHubError(
|
|
520
|
+
f"{where} on commit {own.commit or 'unknown'}, and these comments are on lines of {review.commit}, so "
|
|
521
|
+
"canopy added nothing to it. Submit or delete it on GitHub, then stage this again",
|
|
522
|
+
certain=True,
|
|
523
|
+
)
|
|
524
|
+
body = _joined_body(own.body, review.body)
|
|
525
|
+
if body is not None and len(body) > MAX_TEXT:
|
|
526
|
+
raise GitHubError(
|
|
527
|
+
f"{where}, and its body with this one below it would be longer than GitHub's {MAX_TEXT} characters, so "
|
|
528
|
+
"canopy added nothing to it",
|
|
529
|
+
certain=True,
|
|
530
|
+
)
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
def _joined_body(held: str, body: str | None) -> str | None:
|
|
534
|
+
"""The body of a joined review that holds `held`, with `body` added; None when it needs no change.
|
|
535
|
+
|
|
536
|
+
`body` goes in as the review's own when it has none, and below `held`, after a blank line, when `held` does not
|
|
537
|
+
already end with it, as an earlier stage that stopped part way may have left it: neither text is lost. Only the
|
|
538
|
+
whole of `held`, or its last block after a blank line, counts as holding it, so a short body such as "LGTM" that
|
|
539
|
+
the operator's own words happen to contain is still added.
|
|
540
|
+
|
|
541
|
+
Returns:
|
|
542
|
+
The body to set, or None.
|
|
543
|
+
"""
|
|
544
|
+
if body is None:
|
|
545
|
+
return None
|
|
546
|
+
mine, theirs = _plain(body), _plain(held)
|
|
547
|
+
if theirs == mine or theirs.endswith(f"\n\n{mine}"):
|
|
548
|
+
return None
|
|
549
|
+
if not held.strip():
|
|
550
|
+
return body
|
|
551
|
+
return f"{held.rstrip()}\n\n{body}"
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
def _plain(words: str) -> str:
|
|
555
|
+
return words.replace("\r\n", "\n").strip()
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
def _join(client: Client, own: Pending, review: Review, joining: _Joining, out: Out) -> None:
|
|
559
|
+
"""Add `review`'s replies, comments, and body to the poster's own pending review `own`, which stays pending.
|
|
560
|
+
|
|
561
|
+
A reply or a comment `own` holds already, word for word on the same thread or line, is not added again: it is
|
|
562
|
+
named as though it were. Nothing of `own` is removed, and `own` is never deleted.
|
|
563
|
+
|
|
564
|
+
Raises:
|
|
565
|
+
GitHubError: GitHub refused one, or may have; what `own` holds of the request is printed first, and `end`.
|
|
566
|
+
"""
|
|
567
|
+
out.line({"kind": "pending", "review": own.node, "id": own.id, "joined": True})
|
|
568
|
+
held = list(own.comments)
|
|
569
|
+
posted: list[Mapping[str, object]] = []
|
|
570
|
+
try:
|
|
571
|
+
for answered, thread, words in joining.replies:
|
|
572
|
+
same = _take(held, lambda c, t=thread, w=words: _reply_to(c, joining.thread_of) == t and _same(c, w))
|
|
573
|
+
added = _named(same) if same is not None else _add_reply(client, own.node, thread, words)
|
|
574
|
+
posted.append({"comment": answered, **added})
|
|
575
|
+
for index, new in enumerate(review.comments, 1):
|
|
576
|
+
same = _take(held, lambda c, n=new: _starts(c, n))
|
|
577
|
+
added = _named(same) if same is not None else _thread(client, own.node, index, new)
|
|
578
|
+
posted.append({"index": index, **added})
|
|
579
|
+
body = _joined_body(own.body, review.body)
|
|
580
|
+
if body is not None:
|
|
581
|
+
client.query(_UPDATE, {"review": own.node, "body": body})
|
|
582
|
+
except GitHubError:
|
|
583
|
+
# The review is the operator's: what was added stays, and a later stage adds only what is missing. So even an
|
|
584
|
+
# outcome GitHub left unknown ends `joined` and returns the draft to waiting: staging again is safe because a
|
|
585
|
+
# comment `own` already holds is matched by its words, and the body only by its last block, never added twice.
|
|
586
|
+
# A change to either match must keep that.
|
|
587
|
+
for line in posted:
|
|
588
|
+
out.line({"kind": "comment", **line})
|
|
589
|
+
out.line({"kind": "end", "submitted": False, "joined": True})
|
|
590
|
+
raise
|
|
591
|
+
for line in posted:
|
|
592
|
+
out.line({"kind": "comment", **line})
|
|
593
|
+
out.line({"kind": "end", "submitted": False, "staged": True, "joined": True})
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def _take(
|
|
597
|
+
held: list[Mapping[str, object]],
|
|
598
|
+
matches: Callable[[Mapping[str, object]], bool],
|
|
599
|
+
) -> Mapping[str, object] | None:
|
|
600
|
+
"""Take the first of `held` that `matches` out of it, so two requests alike need two comments.
|
|
601
|
+
|
|
602
|
+
Returns:
|
|
603
|
+
It, or None.
|
|
604
|
+
"""
|
|
605
|
+
for i, comment in enumerate(held):
|
|
606
|
+
if matches(comment):
|
|
607
|
+
return held.pop(i)
|
|
608
|
+
return None
|
|
609
|
+
|
|
610
|
+
|
|
611
|
+
def _reply_to(comment: Mapping[str, object], thread_of: Mapping[int, str]) -> str | None:
|
|
612
|
+
"""The thread a pending review's `comment` answers, by its node id; None for one that starts a thread.
|
|
613
|
+
|
|
614
|
+
Returns:
|
|
615
|
+
The thread's node id, or None.
|
|
616
|
+
"""
|
|
617
|
+
answered = comment.get("replyTo")
|
|
618
|
+
found = number(answered.get("fullDatabaseId")) if isinstance(answered, dict) else None
|
|
619
|
+
return None if found is None else thread_of.get(found)
|
|
620
|
+
|
|
621
|
+
|
|
622
|
+
def _same(comment: Mapping[str, object], words: str) -> bool:
|
|
623
|
+
return _plain(text(comment.get("body")) or "") == _plain(words)
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
def _starts(comment: Mapping[str, object], new: NewComment) -> bool:
|
|
627
|
+
"""Whether a pending review's `comment` is `new`: a thread's start on its file and line, in its words.
|
|
628
|
+
|
|
629
|
+
Returns:
|
|
630
|
+
True when it is.
|
|
631
|
+
"""
|
|
632
|
+
on = new.line in {number(comment.get("line")), number(comment.get("originalLine"))}
|
|
633
|
+
return comment.get("replyTo") is None and comment.get("path") == new.path and on and _same(comment, new.text)
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
def _named(comment: Mapping[str, object]) -> dict[str, object]:
|
|
637
|
+
return {"id": number(comment.get("fullDatabaseId")), "url": comment.get("url")}
|
|
638
|
+
|
|
639
|
+
|
|
640
|
+
def _author(node: Mapping[str, object]) -> str | None:
|
|
641
|
+
author = node.get("author")
|
|
642
|
+
return text(author.get("login")) if isinstance(author, dict) else None
|
|
643
|
+
|
|
644
|
+
|
|
645
|
+
def _submit( # noqa: PLR0917 (what one review is posted from)
|
|
646
|
+
client: Client,
|
|
647
|
+
pr: Ref,
|
|
648
|
+
pr_id: str,
|
|
649
|
+
review: Review,
|
|
650
|
+
joining: _Joining,
|
|
651
|
+
login: str,
|
|
652
|
+
out: Out,
|
|
653
|
+
) -> None:
|
|
654
|
+
"""Post `review`'s body and `joining`'s replies as one review.
|
|
655
|
+
|
|
656
|
+
The review is opened on `review.commit`, if it names one, and its comments added after the replies. It is
|
|
657
|
+
submitted as a comment, or, for `review.submit` false, left pending with the body as its own. A stage that GitHub
|
|
658
|
+
refuses to open one for, since a pending review of the poster's turned up after it looked, joins that one.
|
|
659
|
+
|
|
660
|
+
Raises:
|
|
661
|
+
UnknownOutcomeError: The submit may have reached GitHub.
|
|
662
|
+
GitHubError: GitHub refused before anything of it could be seen; the pending review is deleted, or named.
|
|
663
|
+
"""
|
|
664
|
+
# A staged review keeps its body from the start, since the operator submits it on GitHub, not canopy.
|
|
665
|
+
body = None if review.submit else review.body
|
|
666
|
+
opening = {"pr": pr_id, "body": body, "commit": review.commit}
|
|
667
|
+
try:
|
|
668
|
+
added = obj(client.query(_ADD_REVIEW, opening).get("addPullRequestReview"), "addPullRequestReview")
|
|
669
|
+
opened = obj(added.get("pullRequestReview"), "pullRequestReview")
|
|
670
|
+
pending = _id(opened.get("id"), "pending review's id")
|
|
671
|
+
except GitHubError as e:
|
|
672
|
+
own = _own_pending(client, pr, login) if e.certain and _ONE_PENDING in str(e).lower() else None
|
|
673
|
+
if own is not None:
|
|
674
|
+
_check_joinable(own, review)
|
|
675
|
+
_join(client, own, review, joining, out)
|
|
676
|
+
return
|
|
677
|
+
if not e.certain:
|
|
678
|
+
# GitHub may have opened it, and the next post could open no other while it stands.
|
|
679
|
+
_abandon_unseen(client, pr, login, body, out)
|
|
680
|
+
raise
|
|
681
|
+
out.line({"kind": "pending", "review": pending, "id": number(opened.get("fullDatabaseId"))})
|
|
682
|
+
try:
|
|
683
|
+
posted = _fill(client, pending, joining.replies, review.comments)
|
|
684
|
+
except GitHubError:
|
|
685
|
+
# Nobody else sees a pending review or its replies, so a reply that failed posted nothing.
|
|
686
|
+
_abandon(client, pending, out)
|
|
687
|
+
raise
|
|
688
|
+
if not review.submit:
|
|
689
|
+
for line in posted:
|
|
690
|
+
out.line({"kind": "comment", **line})
|
|
691
|
+
out.line({"kind": "end", "submitted": False, "staged": True})
|
|
692
|
+
return
|
|
693
|
+
try:
|
|
694
|
+
submit = client.query(_SUBMIT, {"review": pending, "body": review.body})
|
|
695
|
+
except GitHubError as e:
|
|
696
|
+
if not e.certain:
|
|
697
|
+
raise UnknownOutcomeError(e) from e
|
|
698
|
+
_abandon(client, pending, out)
|
|
699
|
+
raise
|
|
700
|
+
submitted = obj(obj(submit.get("submitPullRequestReview"), "submit").get("pullRequestReview"), "review")
|
|
701
|
+
for line in posted:
|
|
702
|
+
out.line({"kind": "comment", **line})
|
|
703
|
+
out.line({"kind": "review", "id": number(submitted.get("fullDatabaseId")), "url": submitted.get("url")})
|
|
704
|
+
out.line({"kind": "end", "submitted": True})
|
|
705
|
+
|
|
706
|
+
|
|
707
|
+
def _fill(
|
|
708
|
+
client: Client,
|
|
709
|
+
pending: str,
|
|
710
|
+
replies: Sequence[tuple[int, str, str]],
|
|
711
|
+
comments: Sequence[NewComment],
|
|
712
|
+
) -> list[Mapping[str, object]]:
|
|
713
|
+
"""Add each reply and each comment to pending review `pending`, in order.
|
|
714
|
+
|
|
715
|
+
Returns:
|
|
716
|
+
A line for each, as `comment` prints it.
|
|
717
|
+
|
|
718
|
+
Raises:
|
|
719
|
+
GitHubError: GitHub refused one, or may have.
|
|
720
|
+
"""
|
|
721
|
+
posted: list[Mapping[str, object]] = [
|
|
722
|
+
{"comment": answered, **_add_reply(client, pending, thread, words)} for answered, thread, words in replies
|
|
723
|
+
]
|
|
724
|
+
posted.extend({"index": index, **_thread(client, pending, index, new)} for index, new in enumerate(comments, 1))
|
|
725
|
+
return posted
|
|
726
|
+
|
|
727
|
+
|
|
728
|
+
def _add_reply(client: Client, pending: str, thread: str, words: str) -> dict[str, object]:
|
|
729
|
+
"""Add `words` to pending review `pending` as a reply on thread `thread`.
|
|
730
|
+
|
|
731
|
+
Returns:
|
|
732
|
+
The new comment's id and URL.
|
|
733
|
+
|
|
734
|
+
Raises:
|
|
735
|
+
GitHubError: GitHub refused it, or may have.
|
|
736
|
+
"""
|
|
737
|
+
variables = {"review": pending, "thread": thread, "body": words}
|
|
738
|
+
data = obj(client.query(_REPLY, variables).get("addPullRequestReviewThreadReply"), "reply")
|
|
739
|
+
comment = obj(data.get("comment"), "comment")
|
|
740
|
+
return {"id": number(comment.get("fullDatabaseId")), "url": comment.get("url")}
|
|
741
|
+
|
|
742
|
+
|
|
743
|
+
def _thread(client: Client, pending: str, index: int, comment: NewComment) -> dict[str, object]:
|
|
744
|
+
"""Add `comment` to pending review `pending` as a thread of its own on its line.
|
|
745
|
+
|
|
746
|
+
Returns:
|
|
747
|
+
The new comment's id and URL.
|
|
748
|
+
|
|
749
|
+
Raises:
|
|
750
|
+
GitHubError: GitHub refused it, as for a line its diff of the PR does not show, naming the comment.
|
|
751
|
+
"""
|
|
752
|
+
variables = {"review": pending, "path": comment.path, "line": comment.line, "body": comment.text}
|
|
753
|
+
try:
|
|
754
|
+
data = obj(client.query(_THREAD, variables).get("addPullRequestReviewThread"), "thread")
|
|
755
|
+
except GitHubError as e:
|
|
756
|
+
where = f"comment {index}, on {comment.path}:{comment.line}"
|
|
757
|
+
raise GitHubError(f"GitHub refused {where}: {e}", certain=e.certain, types=e.types) from e
|
|
758
|
+
nodes = items(obj(obj(data.get("thread"), "thread").get("comments"), "comments").get("nodes"))
|
|
759
|
+
first: Mapping[str, object] = nodes[0] if nodes else {}
|
|
760
|
+
return {"id": number(first.get("fullDatabaseId")), "url": first.get("url")}
|
|
761
|
+
|
|
762
|
+
|
|
763
|
+
def _react(client: Client, comment: int, line: Mapping[str, object], reaction: str, out: Out) -> None:
|
|
764
|
+
"""Add the poster's `reaction` to review comment `comment`, whose line as the reader prints it is `line`.
|
|
765
|
+
|
|
766
|
+
Raises:
|
|
767
|
+
GitHubError: GitHub refused it, or its outcome is unknown; either way it is safe to send again.
|
|
768
|
+
"""
|
|
769
|
+
subject = _id(line.get("node"), "review comment's node id")
|
|
770
|
+
client.query(_REACT, {"subject": subject, "content": REACTIONS[reaction]})
|
|
771
|
+
out.line({"kind": "reaction", "comment": comment, "reaction": reaction, "url": line.get("url")})
|
|
772
|
+
|
|
773
|
+
|
|
774
|
+
def _id(value: object, what: str) -> str:
|
|
775
|
+
"""`value` as an id GitHub sent, so a reply missing one is never passed on as null.
|
|
776
|
+
|
|
777
|
+
Returns:
|
|
778
|
+
The id.
|
|
779
|
+
|
|
780
|
+
Raises:
|
|
781
|
+
GitHubError: There is none, so GitHub's reply is not the shape asked for.
|
|
782
|
+
"""
|
|
783
|
+
found = text(value)
|
|
784
|
+
if not found:
|
|
785
|
+
raise GitHubError(f"GitHub's reply has no {what}", certain=False)
|
|
786
|
+
return found
|
|
787
|
+
|
|
788
|
+
|
|
789
|
+
def _repository(client: Client, document: str, variables: Mapping[str, object]) -> Mapping[str, object]:
|
|
790
|
+
return obj(client.query(document, variables).get("repository"), "repository")
|
|
791
|
+
|
|
792
|
+
|
|
793
|
+
def _delete_left(client: Client, review_id: str, pr_id: str, login: str) -> None:
|
|
794
|
+
"""Delete the pending review an earlier post left, if it is still that: pending, on this PR, the poster's own.
|
|
795
|
+
|
|
796
|
+
Raises:
|
|
797
|
+
InputError: It was submitted, so it posted, or it is someone else's or another PR's.
|
|
798
|
+
GitHubError: GitHub refused to look it up or to delete it.
|
|
799
|
+
"""
|
|
800
|
+
try:
|
|
801
|
+
node = client.query(_REVIEW, {"id": review_id}).get("node")
|
|
802
|
+
except GitHubError as e:
|
|
803
|
+
if "NOT_FOUND" in e.types:
|
|
804
|
+
return
|
|
805
|
+
raise
|
|
806
|
+
if not isinstance(node, dict) or not node:
|
|
807
|
+
return
|
|
808
|
+
found = obj(node, "review")
|
|
809
|
+
on = text(obj(found.get("pullRequest"), "pullRequest").get("id"))
|
|
810
|
+
if on != pr_id or _author(found) != login:
|
|
811
|
+
raise InputError(f"review {review_id} is not a review of this PR by {login}")
|
|
812
|
+
if found.get("state") != "PENDING":
|
|
813
|
+
raise InputError(f"review {review_id} was submitted, so what it held is posted")
|
|
814
|
+
client.query(_DELETE, {"review": review_id})
|
|
815
|
+
|
|
816
|
+
|
|
817
|
+
def _abandon_unseen(client: Client, pr: Ref, login: str, body: str | None, out: Out) -> None:
|
|
818
|
+
"""Delete the poster's own pending review on `pr`, which GitHub may have opened, with `body`, without saying so.
|
|
819
|
+
|
|
820
|
+
There was none when the post looked, so one found now is the post's, unless the operator opened one meanwhile: only
|
|
821
|
+
one that holds no comment, and no body but `body`, is deleted.
|
|
822
|
+
"""
|
|
823
|
+
variables = {"owner": pr.owner, "name": pr.name, "number": pr.number}
|
|
824
|
+
try:
|
|
825
|
+
found = obj(_repository(client, _PENDING, variables).get("pullRequest"), "pullRequest")
|
|
826
|
+
except GitHubError:
|
|
827
|
+
return
|
|
828
|
+
for node in items(obj(found.get("reviews"), "reviews").get("nodes")):
|
|
829
|
+
pending = text(node.get("id"))
|
|
830
|
+
if _author(node) != login or not pending:
|
|
831
|
+
continue
|
|
832
|
+
comments = node.get("comments")
|
|
833
|
+
empty = isinstance(comments, dict) and comments.get("totalCount") == 0
|
|
834
|
+
if empty and (text(node.get("body")) or "") in {"", body or ""}:
|
|
835
|
+
_abandon(client, pending, out)
|
|
836
|
+
return
|
|
837
|
+
|
|
838
|
+
|
|
839
|
+
def _abandon(client: Client, pending: str, out: Out) -> None:
|
|
840
|
+
try:
|
|
841
|
+
client.query(_DELETE, {"review": pending})
|
|
842
|
+
except GitHubError:
|
|
843
|
+
out.line({"kind": "end", "submitted": False, "pending": pending})
|
|
844
|
+
return
|
|
845
|
+
out.line({"kind": "end", "submitted": False})
|
|
846
|
+
|
|
847
|
+
|
|
848
|
+
def post_comment(client: Client, comment: IssueComment, out: Out) -> None:
|
|
849
|
+
"""Post `comment` on its issue, printing as the module says.
|
|
850
|
+
|
|
851
|
+
Raises:
|
|
852
|
+
UnknownOutcomeError: The comment may have reached GitHub.
|
|
853
|
+
GitHubError: GitHub refused it, so nothing was posted.
|
|
854
|
+
"""
|
|
855
|
+
issue = comment.issue
|
|
856
|
+
variables = {"owner": issue.owner, "name": issue.name, "number": issue.number}
|
|
857
|
+
subject = text(obj(_repository(client, _ISSUE_ID, variables).get("issue"), f"issue {issue.url}").get("id"))
|
|
858
|
+
try:
|
|
859
|
+
data = obj(client.query(_COMMENT, {"subject": subject, "body": comment.body}).get("addComment"), "addComment")
|
|
860
|
+
except GitHubError as e:
|
|
861
|
+
if e.certain:
|
|
862
|
+
raise
|
|
863
|
+
raise UnknownOutcomeError(e) from e
|
|
864
|
+
node = obj(obj(data.get("commentEdge"), "commentEdge").get("node"), "comment")
|
|
865
|
+
out.line({"kind": "comment", "id": number(node.get("fullDatabaseId")), "url": node.get("url")})
|
|
866
|
+
out.line({"kind": "end", "submitted": True})
|