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.
@@ -0,0 +1,267 @@
1
+ """`canopy-connect-github`: canopy's GitHub reader, the `vcs` source (DESIGN §29, §30). Prints what it reads.
2
+
3
+ Given a repository, `--repo OWNER/NAME`, it is instead the `tracker` source for that repository's GitHub Issues, which
4
+ `canopy_github.issues` reads. Without one, it reads PRs and branches, as follows.
5
+
6
+ On stdin, one JSON object naming what to observe, each key optional: `prs`, PRs' URLs; `repositories`, each
7
+ `{"name": NAME, "url": CLONE_URL}`, with `branch_prefix`; and `review_query`, in GitHub's search syntax. On stdout, one
8
+ JSON line per observation, in DESIGN §30's shapes:
9
+
10
+ - for each PR read whole, its `pr` line (with its labels and mergeable state), a `check` line for each context at its
11
+ head, check run or commit status, then a `review` line for each review (`"item": "review"`) and for each review
12
+ comment (`"item": "comment"`, with its thread's id, path, line, side, and whether it is outdated or resolved), and
13
+ for each comment on its conversation, on no line of its diff (`"item": "pr_comment"`);
14
+ - for each repository read whole, a `branch` line for each branch under the prefix.
15
+
16
+ Last, an `end` line naming the PRs and the repositories read whole and, when the review query was read to its end,
17
+ the PRs it returned, in its order. The PRs are read many to a query; the review query is run on each host the
18
+ repositories are on, or on github.com when none is named. What could not be read whole prints nothing but its error
19
+ on stderr, so a cut-off read never looks like a PR with no checks or a repository with no branches. Nothing is
20
+ written to GitHub.
21
+
22
+ Exit codes: 0 everything was read; 1 something was not, and the `end` line names what was; 2 stdin or the command line
23
+ is not usable, and nothing was read.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import re
29
+ import sys
30
+ from collections.abc import Mapping, Sequence
31
+ from dataclasses import dataclass, field
32
+ from typing import Final, TextIO
33
+
34
+ import click
35
+
36
+ from canopy_github import (
37
+ Client,
38
+ Endpoint,
39
+ GitHubError,
40
+ Hosts,
41
+ InputError,
42
+ Ref,
43
+ Repository,
44
+ Token,
45
+ client_for,
46
+ emit,
47
+ issues,
48
+ parse_pr,
49
+ parse_repository,
50
+ read_input,
51
+ )
52
+ from canopy_github.read import Pulled, pull_requests
53
+ from canopy_github.repository import branches, search
54
+
55
+ #: More than any one request needs: canopy names every PR of a ticket not marked done, and those drafts wait on.
56
+ MAX_PRS: Final = 1000
57
+ #: More than any workspace's map holds.
58
+ MAX_REPOSITORIES: Final = 100
59
+ #: The host a review query runs on when no repository names one.
60
+ DEFAULT_HOST: Final = "github.com"
61
+ #: A repository's name as canopy sends it, and a branch prefix: plain, printable, one line.
62
+ _NAME: Final = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,99}")
63
+ _PREFIX: Final = re.compile(r"[A-Za-z0-9][A-Za-z0-9_./-]{0,254}")
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class Asked:
68
+ """A repository the request names, and its clone URL, if it has one."""
69
+
70
+ name: str
71
+ url: object = None
72
+
73
+
74
+ @dataclass(frozen=True)
75
+ class Request:
76
+ """What one run is asked to observe. `repositories` is None when not asked, which the `end` line keeps apart."""
77
+
78
+ prs: Sequence[Ref] = ()
79
+ repositories: Sequence[Asked] | None = None
80
+ branch_prefix: str = ""
81
+ review_query: str | None = None
82
+
83
+
84
+ @click.command("canopy-connect-github", context_settings={"help_option_names": ["-h", "--help"]})
85
+ @click.option(
86
+ "--repo",
87
+ metavar="[HOST/]OWNER/NAME",
88
+ default=None,
89
+ help="Read this repository's issues instead, as canopy's tracker source: issue 12 is ticket GH-12.",
90
+ )
91
+ @click.pass_context
92
+ def main(ctx: click.Context, repo: str | None) -> None:
93
+ """Read GitHub's PRs and branches into canopy's journal: canopy's vcs source (DESIGN §29, §30).
94
+
95
+ With --repo, read that repository's issues instead: canopy's tracker source for GitHub Issues. The request is one
96
+ JSON object on stdin; what was read is JSON lines on stdout, the `end` line last.
97
+ """
98
+ hosts = ctx.find_object(Hosts) or Hosts()
99
+ if repo is not None:
100
+ ctx.exit(issues.observe(repo, hosts, sys.stdin, sys.stdout))
101
+ try:
102
+ request = _request(read_input(sys.stdin))
103
+ except InputError as e:
104
+ _say(str(e))
105
+ ctx.exit(2)
106
+ reader = _Reader(sys.stdout, hosts.endpoint_of, hosts.token_of)
107
+ reader.prs(request.prs)
108
+ end: dict[str, object] = {"kind": "end", "prs": reader.whole_prs}
109
+ repositories = [] if request.repositories is None else reader.repositories(request)
110
+ if request.repositories is not None:
111
+ end["repositories"] = reader.whole_repositories
112
+ if request.review_query is not None:
113
+ found = reader.review_query(request.review_query, repositories)
114
+ if found is not None:
115
+ end["review_query"] = found
116
+ emit(sys.stdout, end)
117
+ ctx.exit(1 if reader.failed else 0)
118
+
119
+
120
+ def _request(raw: Mapping[str, object]) -> Request:
121
+ """Read the request: a key canopy sends another kind of source is not this one's, and is passed over.
122
+
123
+ Returns:
124
+ The request, each PR and repository once, in the order given.
125
+
126
+ Raises:
127
+ InputError: A PR, a repository, the branch prefix, or the review query is not usable.
128
+ """
129
+ prs = raw.get("prs", [])
130
+ if not isinstance(prs, list):
131
+ raise InputError('stdin\'s prs must be a list: {"prs": ["https://..."]}')
132
+ if len(prs) > MAX_PRS:
133
+ raise InputError(f"stdin names {len(prs)} PRs; at most {MAX_PRS} a read")
134
+ refs = list({ref.url: ref for ref in map(parse_pr, prs)}.values())
135
+ query = raw.get("review_query")
136
+ if query is not None and not (isinstance(query, str) and query.strip()):
137
+ raise InputError("the review query must be a string that is not blank")
138
+ review_query = query if isinstance(query, str) else None
139
+ if "repositories" not in raw:
140
+ return Request(refs, None, review_query=review_query)
141
+ asked = _repositories(raw["repositories"])
142
+ prefix = raw.get("branch_prefix")
143
+ if asked and not (isinstance(prefix, str) and _PREFIX.fullmatch(prefix)):
144
+ raise InputError(f"the repositories need the branch prefix their branches are under, not {prefix!r}")
145
+ return Request(refs, asked, branch_prefix=prefix if isinstance(prefix, str) else "", review_query=review_query)
146
+
147
+
148
+ def _repositories(raw: object) -> list[Asked]:
149
+ """Read the repositories the request names.
150
+
151
+ Returns:
152
+ Each once, in the order given.
153
+
154
+ Raises:
155
+ InputError: They are not a list of repositories, each with a name.
156
+ """
157
+ if not isinstance(raw, list):
158
+ raise InputError('stdin\'s repositories must be a list: {"repositories": [{"name": "api", "url": "..."}]}')
159
+ if len(raw) > MAX_REPOSITORIES:
160
+ raise InputError(f"stdin names {len(raw)} repositories; at most {MAX_REPOSITORIES} a read")
161
+ asked: dict[str, Asked] = {}
162
+ for repository in raw:
163
+ if not isinstance(repository, dict):
164
+ raise InputError(f"{repository!r} is not a repository: {{'name': NAME, 'url': CLONE_URL}}")
165
+ name: object = repository.get("name")
166
+ if not isinstance(name, str) or not _NAME.fullmatch(name):
167
+ raise InputError(f"{name!r} is not a repository's name")
168
+ asked.setdefault(name, Asked(name, repository.get("url")))
169
+ return list(asked.values())
170
+
171
+
172
+ @dataclass
173
+ class _Reader:
174
+ """One run's reads: a client for each host, what it printed whole, and whether anything was not read."""
175
+
176
+ stdout: TextIO
177
+ endpoint_of: Endpoint
178
+ token_of: Token
179
+ #: The PRs and repositories printed whole, in the order asked.
180
+ whole_prs: list[str] = field(default_factory=list[str])
181
+ whole_repositories: list[str] = field(default_factory=list[str])
182
+ failed: bool = False
183
+ #: Each host's client, or why it has none, as `gh` holds no token for it: asked once a run.
184
+ _clients: dict[str, Client | InputError] = field(default_factory=dict[str, Client | InputError])
185
+
186
+ def prs(self, refs: Sequence[Ref]) -> None:
187
+ """Read each PR whole, many to a query on each host, and print them in the order asked."""
188
+ found: dict[str, Pulled] = {}
189
+ for host in sorted({ref.host for ref in refs}):
190
+ on_host = [ref for ref in refs if ref.host == host]
191
+ client = self._client(host)
192
+ if isinstance(client, InputError):
193
+ found.update((ref.url, Pulled(error=GitHubError(str(client), certain=True))) for ref in on_host)
194
+ continue
195
+ found.update(pull_requests(client, on_host))
196
+ for ref in refs:
197
+ pulled = found[ref.url]
198
+ if pulled.error is not None:
199
+ self._miss(ref.url, pulled.error)
200
+ continue
201
+ for line in pulled.lines:
202
+ emit(self.stdout, line)
203
+ self.whole_prs.append(ref.url)
204
+
205
+ def repositories(self, request: Request) -> list[Repository]:
206
+ """Read and print each repository's branches under the prefix.
207
+
208
+ Returns:
209
+ The repositories whose clone URL names where they are on GitHub, read whole or not.
210
+ """
211
+ found: list[Repository] = []
212
+ for asked in request.repositories or ():
213
+ try:
214
+ repository = parse_repository(asked.name, asked.url)
215
+ except InputError as e:
216
+ self._miss(f"repository {asked.name}", e)
217
+ continue
218
+ found.append(repository)
219
+ client = self._client(repository.host)
220
+ if isinstance(client, InputError):
221
+ self._miss(f"repository {asked.name}", client)
222
+ continue
223
+ try:
224
+ lines = branches(client, repository, request.branch_prefix)
225
+ except GitHubError as e:
226
+ self._miss(f"repository {asked.name}", e)
227
+ continue
228
+ for line in lines:
229
+ emit(self.stdout, line)
230
+ self.whole_repositories.append(asked.name)
231
+ return found
232
+
233
+ def review_query(self, query: str, repositories: Sequence[Repository]) -> list[str] | None:
234
+ """Run the review query on each host the repositories are on, or on github.com, each to its last page.
235
+
236
+ Returns:
237
+ The PRs it returned, each once, host by host in the order the repositories name them; None when it was not
238
+ read to the end on every host.
239
+ """
240
+ urls: dict[str, None] = {}
241
+ for host in list(dict.fromkeys(r.host for r in repositories)) or [DEFAULT_HOST]:
242
+ client = self._client(host)
243
+ if isinstance(client, InputError):
244
+ self._miss(f"the review query on {host}", client)
245
+ return None
246
+ try:
247
+ urls.update(dict.fromkeys(search(client, query)))
248
+ except GitHubError as e:
249
+ self._miss(f"the review query on {host}", e)
250
+ return None
251
+ return list(urls)
252
+
253
+ def _client(self, host: str) -> Client | InputError:
254
+ if host not in self._clients:
255
+ try:
256
+ self._clients[host] = client_for(host, self.endpoint_of, self.token_of)
257
+ except InputError as e:
258
+ self._clients[host] = e
259
+ return self._clients[host]
260
+
261
+ def _miss(self, what: str, why: object) -> None:
262
+ self.failed = True
263
+ _say(f"cannot read {what}: {why}")
264
+
265
+
266
+ def _say(message: str) -> None:
267
+ print(f"canopy-connect-github: {message}", file=sys.stderr) # noqa: T201