Repository navigation
Expand file tree
/
Copy pathgithub.py
More file actions
366 lines (326 loc) · 14.8 KB
/
Copy pathgithub.py
File metadata and controls
366 lines (326 loc) · 14.8 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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
"""GitHub transport and repository-backed state."""
import base64
import json
import re
import subprocess
import time
from urllib.parse import quote
REPO = re.compile(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+")
OID = re.compile(r"[0-9a-f]{40}")
ACTIVE = "factory: active"
INACTIVE = "factory: inactive"
STATE_BRANCH = "factory-state"
STATE_FILE = "factory-state.json"
PUBLIC_STATE_FORBIDDEN = (
(re.compile(r"\b(?:gh[pousr]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,})\b"), "GitHub token"),
(re.compile(r"\bBearer\s+[A-Za-z0-9._~+/-]{16,}=*"), "Bearer credential"),
(re.compile(r"-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----"), "private key"),
(re.compile(r"(?:^|[\s\"'(=:])/(?:Users|home)/[A-Za-z0-9._-]+(?:/|$|[\s\"',;)])"), "local home path"),
)
def assert_public_safe(data):
encoded = json.dumps(data, sort_keys=True)
for pattern, label in PUBLIC_STATE_FORBIDDEN:
if pattern.search(encoded):
raise GitHubError(f"Refusing to write {label} into public factory state")
class GitHubError(RuntimeError):
def __init__(self, message, status=None):
super().__init__(message)
self.status = status
class GitHub:
def __init__(self, target, factory, push):
for repo in (target, factory, push):
if not REPO.fullmatch(repo):
raise ValueError(f"Expected owner/repo, got {repo}")
self.target, self.factory, self.push = target, factory, push
def request(self, path, *, method="GET", body=None, pages=False, accept=None):
args = ["gh", "api", "--hostname", "github.com", "--method", method, path]
if pages:
args += ["--paginate", "--slurp"]
if accept:
args += ["-H", f"Accept: {accept}"]
if body is not None:
args += ["--input", "-"]
result = subprocess.run(
args, input=json.dumps(body) if body is not None else "", text=True,
capture_output=True, timeout=90, check=False,
)
if result.returncode:
if path == "graphql" and result.stdout.strip():
return json.loads(result.stdout)
status = re.search(r"HTTP (\d{3})", result.stderr)
code = 429 if "rate limit" in result.stderr.lower() else int(status[1]) if status else None
# API errors can include arbitrary repo text. Keep the durable log short.
raise GitHubError(
f"GitHub {method} {path.split('?')[0]} failed"
+ (f" (HTTP {status[1]})" if status else ""),
code,
)
if accept:
return result.stdout
return json.loads(result.stdout) if result.stdout.strip() else None
def get_optional(self, path):
try:
return self.request(path)
except GitHubError as error:
if error.status != 404:
raise
return None
def graphql(self, query, variables=None):
result = self.request(
"graphql", method="POST",
body={"query": query, "variables": variables or {}},
)
if result.get("errors") or not result.get("data"):
errors = {item.get("type") for item in result.get("errors", [])}
status = None
for kind, code in (
("RATE_LIMITED", 429), ("FORBIDDEN", 403), ("NOT_FOUND", 404),
("UNPROCESSABLE", 422), ("INSUFFICIENT_SCOPES", 403),
):
if kind in errors:
status = code
break
raise GitHubError("GitHub GraphQL request failed", status)
return result["data"]
def repo(self, repo):
return self.request(f"repos/{repo}")
def branch(self, repo, branch):
ref = self.get_optional(f"repos/{repo}/git/ref/heads/{quote(branch, safe='/')}")
return ref["object"]["sha"] if ref else None
def create_branch(self, repo, branch, at):
self.request(f"repos/{repo}/git/refs", method="POST", body={
"ref": f"refs/heads/{branch}", "sha": at,
})
def issues(self, *, states=None):
owner, repo = self.target.split("/")
if states is None:
query = """
query($owner: String!, $repo: String!, $endCursor: String) {
repository(owner: $owner, name: $repo) {
issues(first: 100, after: $endCursor,
orderBy: {field: CREATED_AT, direction: ASC}) {
pageInfo { hasNextPage endCursor }
nodes { number url title createdAt state labels(first: 100) { nodes { name } } }
}
}
}
"""
base_vars = {"owner": owner, "repo": repo}
else:
state_list = [states] if isinstance(states, str) else list(states)
query = """
query($owner: String!, $repo: String!, $states: [IssueState!], $endCursor: String) {
repository(owner: $owner, name: $repo) {
issues(first: 100, after: $endCursor, states: $states,
orderBy: {field: CREATED_AT, direction: ASC}) {
pageInfo { hasNextPage endCursor }
nodes { number url title createdAt state labels(first: 100) { nodes { name } } }
}
}
}
"""
base_vars = {"owner": owner, "repo": repo, "states": state_list}
issues, cursor = [], None
while True:
data = self.graphql(query, {**base_vars, "endCursor": cursor})
page = data["repository"]["issues"]
issues.extend(page["nodes"])
if not page["pageInfo"]["hasNextPage"]:
return issues
cursor = page["pageInfo"]["endCursor"]
def open_issues(self):
return self.issues(states="OPEN")
def issue(self, number):
row = self.request(f"repos/{self.target}/issues/{number}")
expected = f"https://api.github.com/repos/{self.target}"
if ("pull_request" in row or row.get("number") != number
or row.get("repository_url", "").casefold() != expected.casefold()):
raise GitHubError("Expected a Yggdrasil issue", 404)
return row
def issue_body(self, number):
return self.issue(number).get("body") or ""
def issue_comments(self, number, *, limit=15, max_chars=8000):
rows = self.request(f"repos/{self.target}/issues/{number}/comments?per_page=100") or []
comments = []
used = 0
for row in rows[-limit:]:
body = (row.get("body") or "").strip()[:1500]
if not body:
continue
if used + len(body) > max_chars and comments:
break
comments.append({
"author": (row.get("user") or {}).get("login") or "unknown",
"created_at": row.get("created_at") or "",
"body": body,
})
used += len(body)
return comments
def pull_review_comments(self, number, *, limit=20, max_chars=8000):
items = []
used = 0
reviews = self.request(f"repos/{self.target}/pulls/{number}/reviews?per_page=100") or []
for row in reviews[-limit:]:
body = (row.get("body") or "").strip()[:1500]
if not body:
continue
items.append({
"kind": "review",
"author": (row.get("user") or {}).get("login") or "unknown",
"state": row.get("state") or "",
"body": body,
})
inline = self.request(f"repos/{self.target}/pulls/{number}/comments?per_page=100") or []
for row in inline[-limit:]:
body = (row.get("body") or "").strip()[:1500]
if not body:
continue
items.append({
"kind": "inline",
"author": (row.get("user") or {}).get("login") or "unknown",
"path": row.get("path") or "",
"line": row.get("line") or row.get("original_line"),
"body": body,
})
bounded = []
for item in items[-limit:]:
used += len(item["body"])
if used > max_chars and bounded:
break
bounded.append(item)
return bounded
def ensure_labels(self):
for name, color, description in (
(ACTIVE, "0e8a16", "Enrolled in the YggdrasilFactory cycle"),
(INACTIVE, "d4c5f9", "Outside the YggdrasilFactory cycle"),
):
if self.get_optional(f"repos/{self.target}/labels/{quote(name, safe='')}"):
continue
self.request(f"repos/{self.target}/labels", method="POST", body={
"name": name, "color": color, "description": description,
})
def set_label(self, number, active, labels):
desired, other = (ACTIVE, INACTIVE) if active else (INACTIVE, ACTIVE)
path = f"repos/{self.target}/issues/{number}/labels"
if desired not in labels:
self.request(path, method="POST", body={"labels": [desired]})
time.sleep(0.3)
if other in labels:
try:
self.request(f"{path}/{quote(other, safe='')}", method="DELETE")
except GitHubError as error:
if error.status != 404:
raise
time.sleep(0.3)
def contents(self, repo, path, ref):
return self.get_optional(f"repos/{repo}/contents/{quote(path, safe='/')}?ref={quote(ref, safe='')}")
def commit_files(self, branch, parent, headline, body, additions, deletions):
changes = {
"additions": [
{"path": path, "contents": base64.b64encode(data).decode()}
for path, data in sorted(additions.items())
],
"deletions": [{"path": path} for path in sorted(deletions)],
}
result = self.graphql("""
mutation($input: CreateCommitOnBranchInput!) {
createCommitOnBranch(input: $input) { commit { oid url } }
}
""", {"input": {
"branch": {"repositoryNameWithOwner": self.push, "branchName": branch},
"expectedHeadOid": parent,
"message": {"headline": headline, "body": body},
"fileChanges": changes,
}})
return result["createCommitOnBranch"]["commit"]["oid"]
def commit_info(self, repo, oid):
return self.request(f"repos/{repo}/git/commits/{oid}")
def pull(self, number):
return self.request(f"repos/{self.target}/pulls/{number}")
def owned_pulls(self, branch):
owner = self.push.split("/")[0]
path = f"repos/{self.target}/pulls?state=all&head={quote(owner + ':' + branch, safe='')}&per_page=100"
return [row for page in self.request(path, pages=True) for row in page]
def draft(self, branch, base, title, body):
head = branch if self.push == self.target else f"{self.push.split('/')[0]}:{branch}"
payload = {"head": head, "base": base, "title": title, "body": body, "draft": True}
if self.push != self.target:
payload["head_repo"] = self.push.split("/")[1]
return self.request(f"repos/{self.target}/pulls", method="POST", body=payload)
def update_pull_body(self, number, body):
return self.request(f"repos/{self.target}/pulls/{number}", method="PATCH", body={"body": body})
def mark_ready_for_review(self, node_id):
return self.graphql("""
mutation($id: ID!) {
markPullRequestReadyForReview(input: {pullRequestId: $id}) {
pullRequest { id isDraft }
}
}
""", {"id": node_id})
def squash_merge(self, number, head_sha, commit_title, commit_message):
return self.request(
f"repos/{self.target}/pulls/{number}/merge",
method="PUT",
body={
"merge_method": "squash",
"sha": head_sha,
"commit_title": commit_title,
"commit_message": commit_message,
},
)
def pull_files(self, number):
path = f"repos/{self.target}/pulls/{number}/files?per_page=100"
return [row for page in self.request(path, pages=True) for row in page]
def pull_diff(self, number):
return self.request(f"repos/{self.target}/pulls/{number}", accept="application/vnd.github.diff")
def checks(self, head):
status = {}
root = f"repos/{self.target}/commits/{head}"
for page in self.request(f"{root}/statuses?per_page=100", pages=True):
for row in page:
status.setdefault(row["context"], (row["state"], row.get("target_url") or ""))
for page in self.request(f"{root}/check-runs?per_page=100&filter=latest", pages=True):
for row in page["check_runs"]:
name = f"{(row.get('app') or {}).get('slug', 'check')}/{row['name']}"
status.setdefault(name, (row["conclusion"] or "pending", row.get("html_url") or ""))
return status
class State:
"""Compare-and-swap a single versioned JSON document on the runtime branch."""
def __init__(self, github, *, require_private=False):
self.github = github
self.require_private = require_private
self.sha = None
def load(self):
item = self.github.contents(self.github.factory, STATE_FILE, STATE_BRANCH)
self.sha = item["sha"] if item else None
if item and item.get("encoding") != "base64":
item = self.github.request(f"repos/{self.github.factory}/git/blobs/{self.sha}")
return json.loads(base64.b64decode(item["content"])) if item else None
def init_branch(self):
github = self.github
repo = self.writable_repo()
if not github.branch(github.factory, STATE_BRANCH):
base = repo["default_branch"]
github.create_branch(github.factory, STATE_BRANCH, github.branch(github.factory, base))
def writable_repo(self):
repo = self.github.repo(self.github.factory)
if self.require_private and repo.get("visibility") != "private":
raise GitHubError("Operational state requires a private GitHub repository")
return repo
def save(self, data, message):
repo = self.writable_repo()
if repo.get("visibility") != "private":
assert_public_safe(data)
body = {
"branch": STATE_BRANCH,
"message": f"Factory state: {message}\n\nGenerated by YggdrasilFactory master.",
"content": base64.b64encode(
(json.dumps(data, indent=2, sort_keys=True) + "\n").encode()
).decode(),
}
if self.sha:
body["sha"] = self.sha
result = self.github.request(
f"repos/{self.github.factory}/contents/{STATE_FILE}", method="PUT", body=body,
)
self.sha = result["content"]["sha"]