Repository navigation
Expand file tree
/
Copy pathgh_graphql.py
More file actions
247 lines (193 loc) · 9.96 KB
/
Copy pathgh_graphql.py
File metadata and controls
247 lines (193 loc) · 9.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
"""One GraphQL transport, one cursor walker, and one absent test, shared by the scripts reading through `gh`.
This is a library module and has no command line. `pr_review.py`, `pr_cleanup.py`,
`backlog_metrics.py`, and `handoff.py` import it as a sibling.
That works from any working directory because Python puts the running script's own directory on `sys.path`.
Every child `run_subprocess` starts runs with `GH_HOST` pinned to github.com, per `pinned_env`.
A failure raises `GraphQLError` and never exits. Each caller maps it to its own exit contract, since the contracts differ.
`pr_review.py` and `backlog_metrics.py` report a failed read as exit 1.
`pr_cleanup.py` and `handoff.py` reserve 1 for a refusal and report a read that did not run as 2.
A transport that exited on its own would pick one of those for both.
"""
from __future__ import annotations
import json
import os
import re
import subprocess
from collections.abc import Callable, Iterator, Sequence
from typing import NamedTuple
DETAIL_CAP = 800
HOST = "github.com"
class GraphQLError(Exception):
"""A read that did not produce an answer.
`detail` is the stderr or error text worth showing beside the one-line message, and it is
empty where the message already says everything.
"""
def __init__(self, message: str, detail: str = "") -> None:
super().__init__(message)
self.detail = detail
class NullNodeError(GraphQLError):
"""A response holding a null list item, which GitHub could not resolve at read time.
GraphQL can return one with no entry in `errors`, so nothing read off the response is
trustworthy. `where` is the dotted path of the first connection holding one.
"""
def __init__(self, where: str) -> None:
super().__init__(f"gh graphql returned a null node GitHub could not resolve under {where}")
self.where = where
class Response(NamedTuple):
"""The `data` of one response, and the errors it carried that the caller chose to tolerate."""
data: dict
tolerated: list
Runner = Callable[[list[str]], "tuple[int, str, str]"]
HTTP_STATUS = re.compile(r"\(HTTP (\d{3})\)")
ABSENT = frozenset({"404", "422"})
def said_absent(stderr: str) -> bool:
"""Whether `gh`'s `stderr` says GitHub answered that the object is not there.
`HTTP_STATUS` is what `gh` prints only where GitHub answered. Outside `ABSENT`, the two returns
for an object that is not there, an answer means "not read" rather than "not there".
"""
m = HTTP_STATUS.search(stderr)
return m is not None and m.group(1) in ABSENT
ORIGIN = re.compile(r"[:/]([A-Za-z0-9_.\-]+)/([A-Za-z0-9_.\-]+?)(?:\.git)?/?$")
def origin_slug(url: str) -> str | None:
"""The lowercase `owner/repo` a git remote URL names, or None where it names none.
The https, ssh, and scp-like forms read alike, with or without `.git` and a trailing slash.
"""
m = ORIGIN.search(url)
return f"{m.group(1)}/{m.group(2)}".lower() if m else None
def pinned_env() -> dict[str, str]:
"""This process's environment with `GH_HOST` naming `HOST`, for the child a `gh` call runs in.
The registry names every repository on github.com. `gh` reads `GH_HOST` for the host wherever a
command names none, `gh api` and a `--repo OWNER/REPO` alike. An exported one would move a read,
or a write, to a host the registry never named. Setting it in the child pins every subcommand
one way, where `--hostname` exists on `gh api` alone.
"""
return {**os.environ, "GH_HOST": HOST}
def run_subprocess(argv: list[str]) -> tuple[int, str, str]:
"""Run `argv` on the pinned host and return its exit code, stdout and stderr.
Every read decodes as UTF-8 rather than as whatever the platform's locale is. `gh` emits UTF-8
on every platform, where a Windows console locale is cp1252. One typographic quote in a
review body crashed the decode and left the caller reading a null stdout.
"""
try:
r = subprocess.run(
argv,
capture_output=True,
text=True,
encoding="utf-8",
check=False,
env=pinned_env(),
)
except OSError as exc:
raise GraphQLError(f"could not run {argv[0]}: {exc}") from exc
return r.returncode, r.stdout, r.stderr
def build_argv(query: str, variables: dict[str, object]) -> list[str]:
"""The `gh api graphql` argv for `query` carrying `variables`.
A string goes through `-f` and an int through `-F`, because `-F` infers a type from the text.
Under `-F`, a reply body of `123` or `true` arrives as an Int or a Boolean.
The mutation then fails on a type nobody passed it.
Under `-F`, a body opening with `@` is read as a filename.
A list is sent as one `name[]` field per element, which is how `gh` spells a list variable.
"""
argv = ["gh", "api", "graphql", "-f", f"query={query}"]
for name, value in variables.items():
if isinstance(value, list | tuple):
for item in value:
argv += ["-F" if isinstance(item, int) else "-f", f"{name}[]={item}"]
else:
argv += ["-F" if isinstance(value, int) else "-f", f"{name}={value}"]
return argv
def request(
query: str,
variables: dict[str, object],
*,
run: Runner = run_subprocess,
tolerate: Callable[[object], bool] | None = None,
) -> Response:
"""Run one GraphQL document and return its `data`, raising rather than reporting a blank.
`errors` is checked rather than trusted to the exit code, since a GraphQL document can fail
per-field while the request itself succeeds. The caller would otherwise read the null that leaves.
`gh api graphql` exits non-zero with the JSON still on stdout when the response carries
errors, so that stdout is read first. An error is tolerated only where `tolerate` accepts it,
and the tolerated ones come back beside the data for the caller to report.
A null item in any `nodes` list raises `NullNodeError`, since every caller would otherwise
index into it. A caller reading a query may read again before giving up.
"""
code, stdout, stderr = run(build_argv(query, variables))
try:
payload = json.loads(stdout)
except ValueError:
payload = None
if not isinstance(payload, dict) or (code != 0 and not payload.get("errors")):
raise GraphQLError(f"gh graphql failed rc={code}", stderr[:DETAIL_CAP])
errors = payload.get("errors")
if errors and not (tolerate and all(tolerate(e) for e in errors)):
raise GraphQLError("gh graphql reported errors", json.dumps(errors)[:DETAIL_CAP])
if payload.get("data") is None:
raise GraphQLError("gh graphql returned no data", json.dumps(errors)[:DETAIL_CAP])
if not isinstance(payload["data"], dict):
raise GraphQLError("gh graphql returned data that is not an object")
if (where := null_node(payload["data"])) is not None:
raise NullNodeError(where)
return Response(payload["data"], list(errors or []))
def mutated(data: dict, *path: str) -> dict:
"""The object a mutation returned at `path` under `data`, empty wherever a step is absent."""
for key in path:
data = data.get(key) or {}
return data
def null_node(data: object, path: str = "") -> str | None:
"""The path of the first connection under `data` whose `nodes` holds a null, else None."""
if isinstance(data, list):
items = [(path, value) for value in data]
elif isinstance(data, dict):
if isinstance(nodes := data.get("nodes"), list) and None in nodes:
return path or "nodes"
items = [(f"{path}.{key}".lstrip("."), value) for key, value in data.items()]
else:
return None
return next((found for key, value in items if (found := null_node(value, key))), None)
def _descend(node: object, path: Sequence[str]) -> object:
for key in path:
if not isinstance(node, dict) or key not in node:
raise GraphQLError(f"the response holds no {'.'.join(path)}")
node = node[key]
return node
def walk(
fetch: Callable[[str | None], dict],
path: Sequence[str],
after: str | None = None,
*,
strict_page: bool = False,
) -> Iterator[dict]:
"""Each page of the connection at `path`, from the one past `after` to the last.
`fetch` reads one page given the cursor to start after, or `None` for the first, and returns
that response's `data`. `path` is the keys from `data` down to the connection. What is
yielded is the object holding the connection, the last key's parent, so a caller reads its
siblings too. The connection is read for its `pageInfo`, so the walk is one place a fix to how
a page is followed lands. A caller wanting fewer pages simply stops iterating.
A page whose `pageInfo` or `hasNextPage` is absent reads as the last page, unless `strict_page`
is set. Setting it raises instead, for a caller that would otherwise answer from a cut short list.
A page claiming another without a cursor that moves past the one just sent raises, since the
same page would otherwise be read forever.
"""
if not path:
raise ValueError("a connection path names at least one key")
while True:
parent = _descend(fetch(after), path[:-1])
if not isinstance(parent, dict):
raise GraphQLError(f"the response holds no {'.'.join(path[:-1])}")
connection = parent.get(path[-1])
if not isinstance(connection, dict):
raise GraphQLError(f"the response holds no {'.'.join(path)}")
page = connection.get("pageInfo")
if strict_page and (not isinstance(page, dict) or "hasNextPage" not in page):
raise GraphQLError(f"the {'.'.join(path)} carries no pageInfo.hasNextPage")
yield parent
page = page or {}
if not page.get("hasNextPage"):
return
cursor = page.get("endCursor")
if not cursor or cursor == after:
raise GraphQLError(
f"the {'.'.join(path)} reported another page without a cursor that advances"
)
after = cursor