second-source 0.5.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.
- second_source/__init__.py +3 -0
- second_source/action/__init__.py +4 -0
- second_source/action/commands.py +88 -0
- second_source/action/event.py +89 -0
- second_source/action/inputs.py +118 -0
- second_source/action/main.py +203 -0
- second_source/action/publish.py +184 -0
- second_source/action/setup.py +143 -0
- second_source/action/sweep.py +85 -0
- second_source/action/wait.py +49 -0
- second_source/benchmark/__init__.py +1 -0
- second_source/benchmark/aidev.py +248 -0
- second_source/benchmark/aidev_local.py +85 -0
- second_source/benchmark/golden.py +314 -0
- second_source/benchmark/redact.py +45 -0
- second_source/benchmark/rescore.py +388 -0
- second_source/benchmark/runner.py +159 -0
- second_source/benchmark/sample.py +243 -0
- second_source/benchmark/stats.py +363 -0
- second_source/cli/__init__.py +1 -0
- second_source/cli/bench.py +427 -0
- second_source/cli/main.py +182 -0
- second_source/core/__init__.py +4 -0
- second_source/core/aggregate.py +102 -0
- second_source/core/checks.py +470 -0
- second_source/core/engine.py +98 -0
- second_source/core/evidence.py +29 -0
- second_source/core/expr.py +206 -0
- second_source/core/hashing.py +41 -0
- second_source/core/model.py +112 -0
- second_source/core/pack.py +156 -0
- second_source/packs/__init__.py +1 -0
- second_source/packs/coding/__init__.py +16 -0
- second_source/packs/coding/checks/ci_config_caution.yaml +23 -0
- second_source/packs/coding/checks/ci_result.yaml +133 -0
- second_source/packs/coding/checks/ci_weakening_caution.yaml +27 -0
- second_source/packs/coding/checks/deployed.yaml +36 -0
- second_source/packs/coding/checks/docs_updated.yaml +22 -0
- second_source/packs/coding/checks/fixes_issue.yaml +58 -0
- second_source/packs/coding/checks/fixes_issue_durable.yaml +60 -0
- second_source/packs/coding/checks/integrity_guard.yaml +34 -0
- second_source/packs/coding/checks/integrity_inspection.yaml +21 -0
- second_source/packs/coding/checks/lint_caution.yaml +22 -0
- second_source/packs/coding/checks/matching_jobs_caution.yaml +22 -0
- second_source/packs/coding/checks/not_reverted.yaml +38 -0
- second_source/packs/coding/checks/tests_added.yaml +25 -0
- second_source/packs/coding/checks/tests_added_guard.yaml +26 -0
- second_source/packs/coding/checks/tests_removed_caution.yaml +23 -0
- second_source/packs/coding/detection.py +94 -0
- second_source/packs/coding/diff_facts.py +665 -0
- second_source/packs/coding/extract.py +911 -0
- second_source/packs/coding/functions.py +241 -0
- second_source/packs/coding/pack.yaml +33 -0
- second_source/packs/coding/trusted_rules.yaml +50 -0
- second_source/pipeline.py +112 -0
- second_source/report/__init__.py +1 -0
- second_source/report/render.py +503 -0
- second_source/sources/__init__.py +1 -0
- second_source/sources/github/__init__.py +4 -0
- second_source/sources/github/auth.py +48 -0
- second_source/sources/github/cache.py +67 -0
- second_source/sources/github/client.py +261 -0
- second_source/sources/github/mappers.py +454 -0
- second_source/sources/github/source.py +385 -0
- second_source/sources/github/urls.py +51 -0
- second_source-0.5.0.dist-info/METADATA +311 -0
- second_source-0.5.0.dist-info/RECORD +71 -0
- second_source-0.5.0.dist-info/WHEEL +4 -0
- second_source-0.5.0.dist-info/entry_points.txt +2 -0
- second_source-0.5.0.dist-info/licenses/LICENSE +202 -0
- second_source-0.5.0.dist-info/licenses/NOTICE +9 -0
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
"""GitHub source: load a pull request and fetch exactly the evidence its claims need.
|
|
2
|
+
|
|
3
|
+
Two steps, so callers can extract claims in between and fetch only what is necessary:
|
|
4
|
+
|
|
5
|
+
loaded = source.load(ref) # 3 API calls: PR, commits, comments
|
|
6
|
+
result = source.fetch_evidence(loaded, claims, needed_types)
|
|
7
|
+
|
|
8
|
+
Failure policy (see docs/sources/github.md): a rate limit stops all further fetching and
|
|
9
|
+
marks every remaining record type stale; any other error marks only its own record type
|
|
10
|
+
stale. Stale types make checks return UNVERIFIABLE, never CONTRADICTED.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from collections.abc import Callable, Iterable, Sequence
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from datetime import UTC, datetime, timedelta
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from second_source.core.model import Claim, Evidence
|
|
21
|
+
from second_source.packs.coding.detection import PullRequestSignals
|
|
22
|
+
from second_source.packs.coding.extract import (
|
|
23
|
+
BUILD_OK,
|
|
24
|
+
DEPLOYED,
|
|
25
|
+
FIXES_ISSUE,
|
|
26
|
+
LINT_OK,
|
|
27
|
+
TESTS_PASS,
|
|
28
|
+
TextSource,
|
|
29
|
+
)
|
|
30
|
+
from second_source.sources.github import mappers
|
|
31
|
+
from second_source.sources.github.client import (
|
|
32
|
+
GitHubClient,
|
|
33
|
+
GitHubError,
|
|
34
|
+
NotFound,
|
|
35
|
+
RateLimited,
|
|
36
|
+
)
|
|
37
|
+
from second_source.sources.github.urls import PullRequestRef
|
|
38
|
+
|
|
39
|
+
Json = dict[str, Any]
|
|
40
|
+
|
|
41
|
+
# Fetch order. Cheap and most decisive types first, so a rate limit hurts as little as possible.
|
|
42
|
+
# Reverts are looked for only inside the durability window that follows the merge (the
|
|
43
|
+
# coding.not_reverted check's default window_days). Without an end date, a PR merged months ago
|
|
44
|
+
# would make us page through every later commit and hit the page limit on any busy repository.
|
|
45
|
+
REVERT_WINDOW = timedelta(days=30)
|
|
46
|
+
REVERT_MAX_PAGES = 10 # up to 1,000 commits in the window
|
|
47
|
+
|
|
48
|
+
FETCH_ORDER = (
|
|
49
|
+
"pr_state",
|
|
50
|
+
# Workflow runs before check runs: a workflow seen unfinished keeps the claim waiting, and
|
|
51
|
+
# its check runs read afterwards are at least as new. It also finds Second Source's own
|
|
52
|
+
# runs, whose check runs are then left out.
|
|
53
|
+
"ci_workflow_run",
|
|
54
|
+
"check_result",
|
|
55
|
+
"changed_file",
|
|
56
|
+
"changed_files_summary",
|
|
57
|
+
"issue_state",
|
|
58
|
+
"revert",
|
|
59
|
+
"deployment_status",
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
MAX_DEPLOYMENTS_PER_REF = 5
|
|
63
|
+
# PR text is attacker-controlled, and each distinct reference costs requests from the
|
|
64
|
+
# repository's shared hourly quota (security review 1, H3: one body of "Fixes #N" lines made
|
|
65
|
+
# 5,000 requests). Up to these caps, references are fetched in priority order: the PR body
|
|
66
|
+
# and title first, then commit messages, then comments, each in the order written. The rest
|
|
67
|
+
# are not fetched, so their claims find no evidence and are UNVERIFIABLE; the report says how
|
|
68
|
+
# many were left out. References in commits or comments therefore never push out a claim the
|
|
69
|
+
# body or title makes (security review 2, N2: a whole-type cap let 21 decoy references hide
|
|
70
|
+
# every issue claim). The body itself is written by the agent too, so a body full of decoys
|
|
71
|
+
# can still push out its own later claims; they then fail closed, as UNVERIFIABLE.
|
|
72
|
+
MAX_ISSUES_PER_PR = 20 # two requests each
|
|
73
|
+
MAX_CI_REFS_PER_PR = 8 # three requests each (check runs, statuses, workflow runs)
|
|
74
|
+
MAX_DEPLOY_REFS_PER_PR = 4 # up to six requests each
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
_ORIGIN_RANK = {"body": 0, "title": 0, "commit": 1, "comment": 2}
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _priority(claim: Claim) -> tuple[int, Any]:
|
|
81
|
+
if claim.attributes.get("stated_in_body"):
|
|
82
|
+
return 0, claim.made_at # said first in a commit, but also in the body
|
|
83
|
+
return _ORIGIN_RANK.get(claim.origin, 3), claim.made_at
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class PullRequestNotFound(Exception):
|
|
87
|
+
"""The PR does not exist, or the token cannot see it."""
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@dataclass(frozen=True)
|
|
91
|
+
class LoadedPullRequest:
|
|
92
|
+
ref: PullRequestRef
|
|
93
|
+
pull: Json
|
|
94
|
+
commits: Sequence[Json]
|
|
95
|
+
comments: Sequence[Json]
|
|
96
|
+
signals: PullRequestSignals
|
|
97
|
+
texts: Sequence[TextSource]
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def merged(self) -> bool:
|
|
101
|
+
return bool(self.pull.get("merged_at"))
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def repo(self) -> str:
|
|
105
|
+
"""The repository's current name. A renamed or transferred repository still answers at
|
|
106
|
+
its old URL, but the episode (mappers.episode_from_pull) uses the current name, so
|
|
107
|
+
evidence about it must too, or checks would not find their own repository's records."""
|
|
108
|
+
return ((self.pull.get("base") or {}).get("repo") or {}).get(
|
|
109
|
+
"full_name"
|
|
110
|
+
) or self.ref.full_name
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@dataclass
|
|
114
|
+
class EvidenceResult:
|
|
115
|
+
records: list[Evidence] = field(default_factory=list)
|
|
116
|
+
stale: set[str] = field(default_factory=set)
|
|
117
|
+
errors: list[str] = field(default_factory=list) # human-readable, for the report
|
|
118
|
+
# True when the rate limit cut fetching short. Batch callers stop and retry the PR later
|
|
119
|
+
# instead of recording verdicts that are unverifiable only for lack of quota.
|
|
120
|
+
rate_limited: bool = False
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class GitHubSource:
|
|
124
|
+
def __init__(
|
|
125
|
+
self,
|
|
126
|
+
client: GitHubClient,
|
|
127
|
+
clock: Callable[[], datetime] = lambda: datetime.now(UTC),
|
|
128
|
+
*,
|
|
129
|
+
own_workflow_path: str | None = None,
|
|
130
|
+
) -> None:
|
|
131
|
+
"""``own_workflow_path`` (the Action passes its workflow file, for example
|
|
132
|
+
``.github/workflows/second-source.yml``): runs of that workflow, and their check runs,
|
|
133
|
+
are Second Source itself, never CI evidence, whatever the workflow or job is named."""
|
|
134
|
+
self.client = client
|
|
135
|
+
self._clock = clock
|
|
136
|
+
self._left_out: dict[str, int] = {} # per fetch_evidence call: references not fetched
|
|
137
|
+
self._own_workflow_path = own_workflow_path
|
|
138
|
+
self._own_suites: set[int] = set()
|
|
139
|
+
# PR files, shared by the changed_file and revert fetchers within one fetch_evidence
|
|
140
|
+
# call. Reset on every call: the Action re-checks a PR after new commits.
|
|
141
|
+
self._files: dict[str, list[Json]] = {}
|
|
142
|
+
self._mapped: dict[str, list[Evidence]] = {}
|
|
143
|
+
|
|
144
|
+
# ---- step 1 ------------------------------------------------------------------------------
|
|
145
|
+
|
|
146
|
+
def load(self, ref: PullRequestRef) -> LoadedPullRequest:
|
|
147
|
+
base = f"/repos/{ref.owner}/{ref.repo}"
|
|
148
|
+
try:
|
|
149
|
+
pull = self.client.get(f"{base}/pulls/{ref.number}")
|
|
150
|
+
except NotFound as error:
|
|
151
|
+
raise PullRequestNotFound(f"{ref} was not found or is not accessible") from error
|
|
152
|
+
commits = self.client.get_paginated(f"{base}/pulls/{ref.number}/commits")
|
|
153
|
+
comments = self.client.get_paginated(f"{base}/issues/{ref.number}/comments")
|
|
154
|
+
return LoadedPullRequest(
|
|
155
|
+
ref=ref,
|
|
156
|
+
pull=pull,
|
|
157
|
+
commits=commits,
|
|
158
|
+
comments=comments,
|
|
159
|
+
signals=mappers.signals_from_pull(pull, commits),
|
|
160
|
+
texts=mappers.texts_from_pull(pull, commits, comments),
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
# ---- step 2 ------------------------------------------------------------------------------
|
|
164
|
+
|
|
165
|
+
def fetch_evidence(
|
|
166
|
+
self, loaded: LoadedPullRequest, claims: Sequence[Claim], needed: Iterable[str]
|
|
167
|
+
) -> EvidenceResult:
|
|
168
|
+
"""Fetch the requested evidence types; failures become stale types, not exceptions."""
|
|
169
|
+
wanted = set(needed)
|
|
170
|
+
result = EvidenceResult()
|
|
171
|
+
self._files = {}
|
|
172
|
+
self._mapped = {}
|
|
173
|
+
self._left_out: dict[str, int] = {}
|
|
174
|
+
fetchers = {
|
|
175
|
+
"pr_state": self._pr_state,
|
|
176
|
+
"check_result": self._check_results,
|
|
177
|
+
"ci_workflow_run": self._workflow_runs,
|
|
178
|
+
"changed_file": self._changed_files,
|
|
179
|
+
"changed_files_summary": self._files_summary,
|
|
180
|
+
"issue_state": self._issue_states,
|
|
181
|
+
"revert": self._reverts,
|
|
182
|
+
"deployment_status": self._deployments,
|
|
183
|
+
}
|
|
184
|
+
pending = [kind for kind in FETCH_ORDER if kind in wanted]
|
|
185
|
+
unknown = wanted - set(fetchers)
|
|
186
|
+
result.stale |= unknown # a type we cannot fetch must not be judged
|
|
187
|
+
|
|
188
|
+
for index, kind in enumerate(pending):
|
|
189
|
+
try:
|
|
190
|
+
result.records.extend(fetchers[kind](loaded, claims))
|
|
191
|
+
except RateLimited:
|
|
192
|
+
remaining = pending[index:]
|
|
193
|
+
result.stale |= set(remaining)
|
|
194
|
+
result.errors.append(f"GitHub rate limit reached; not fetched: {remaining}")
|
|
195
|
+
result.rate_limited = True
|
|
196
|
+
break
|
|
197
|
+
except GitHubError as error: # includes PageLimitReached
|
|
198
|
+
result.stale.add(kind)
|
|
199
|
+
result.errors.append(f"{kind}: {error}")
|
|
200
|
+
result.errors += [
|
|
201
|
+
f"{count} {what} not checked (more than the per-PR limit)"
|
|
202
|
+
for what, count in self._left_out.items()
|
|
203
|
+
]
|
|
204
|
+
return result
|
|
205
|
+
|
|
206
|
+
def _first(self, keyed: Iterable[tuple[Any, Claim]], limit: int, what: str) -> list[Any]:
|
|
207
|
+
"""Distinct keys in claim priority order, at most ``limit``; counts the rest."""
|
|
208
|
+
ordered: list[Any] = []
|
|
209
|
+
for key, _claim in sorted(keyed, key=lambda pair: _priority(pair[1])):
|
|
210
|
+
if key not in ordered:
|
|
211
|
+
ordered.append(key)
|
|
212
|
+
if len(ordered) > limit:
|
|
213
|
+
self._left_out[what] = len(ordered) - limit
|
|
214
|
+
return ordered[:limit]
|
|
215
|
+
|
|
216
|
+
def _ci_refs(self, claims: Sequence[Claim], loaded: LoadedPullRequest) -> list[str]:
|
|
217
|
+
"""Commits with CI claims, by claim priority, then the PR's head commit (for the
|
|
218
|
+
evidence summary every report shows). A claim's opening and final commit are taken
|
|
219
|
+
together or not at all: judging it on only one of them could verify it on a commit
|
|
220
|
+
that is not the one that matters."""
|
|
221
|
+
ordered: list[str] = []
|
|
222
|
+
left_out = 0
|
|
223
|
+
ci_claims = [c for c in claims if c.type in {TESTS_PASS, BUILD_OK, LINT_OK}]
|
|
224
|
+
for claim in sorted(ci_claims, key=_priority):
|
|
225
|
+
refs = [
|
|
226
|
+
r
|
|
227
|
+
for r in (claim.attributes.get("ref"), claim.attributes.get("final_ref"))
|
|
228
|
+
if r and r not in ordered
|
|
229
|
+
]
|
|
230
|
+
if len(ordered) + len(refs) <= MAX_CI_REFS_PER_PR:
|
|
231
|
+
ordered += refs
|
|
232
|
+
else:
|
|
233
|
+
left_out += len(refs)
|
|
234
|
+
if left_out:
|
|
235
|
+
self._left_out["commits with CI claims"] = left_out
|
|
236
|
+
head = (loaded.pull.get("head") or {}).get("sha")
|
|
237
|
+
if head and head not in ordered and len(ordered) < MAX_CI_REFS_PER_PR:
|
|
238
|
+
ordered.append(head)
|
|
239
|
+
return ordered
|
|
240
|
+
|
|
241
|
+
# ---- one fetcher per evidence type -------------------------------------------------------
|
|
242
|
+
|
|
243
|
+
def _base(self, loaded: LoadedPullRequest) -> str:
|
|
244
|
+
return f"/repos/{loaded.ref.owner}/{loaded.ref.repo}"
|
|
245
|
+
|
|
246
|
+
def _pr_state(self, loaded: LoadedPullRequest, _claims: Sequence[Claim]) -> list[Evidence]:
|
|
247
|
+
return [mappers.pr_state_evidence(loaded.pull, self._clock())]
|
|
248
|
+
|
|
249
|
+
def _check_results(self, loaded: LoadedPullRequest, claims: Sequence[Claim]) -> list[Evidence]:
|
|
250
|
+
records: list[Evidence] = []
|
|
251
|
+
for ref in self._ci_refs(claims, loaded):
|
|
252
|
+
now = self._clock()
|
|
253
|
+
runs = self.client.get_paginated(
|
|
254
|
+
f"{self._base(loaded)}/commits/{ref}/check-runs", {"filter": "latest"}
|
|
255
|
+
)
|
|
256
|
+
records.extend(
|
|
257
|
+
mappers.check_run_evidence(run, ref, now)
|
|
258
|
+
for run in runs
|
|
259
|
+
if (run.get("check_suite") or {}).get("id") not in self._own_suites
|
|
260
|
+
)
|
|
261
|
+
combined = self.client.get(f"{self._base(loaded)}/commits/{ref}/status")
|
|
262
|
+
records.extend(
|
|
263
|
+
mappers.status_evidence(status, ref, now) for status in combined.get("statuses", [])
|
|
264
|
+
)
|
|
265
|
+
return records
|
|
266
|
+
|
|
267
|
+
def _workflow_runs(self, loaded: LoadedPullRequest, claims: Sequence[Claim]) -> list[Evidence]:
|
|
268
|
+
records: list[Evidence] = []
|
|
269
|
+
for ref in self._ci_refs(claims, loaded):
|
|
270
|
+
now = self._clock()
|
|
271
|
+
runs = self.client.get_paginated(
|
|
272
|
+
f"{self._base(loaded)}/actions/runs", {"head_sha": ref}, max_pages=3
|
|
273
|
+
)
|
|
274
|
+
for run in runs:
|
|
275
|
+
if self._own_workflow_path and run.get("path") == self._own_workflow_path:
|
|
276
|
+
self._own_suites.add(run.get("check_suite_id"))
|
|
277
|
+
continue
|
|
278
|
+
records.append(mappers.workflow_run_evidence(run, ref, now))
|
|
279
|
+
return records
|
|
280
|
+
|
|
281
|
+
def _pull_files(self, loaded: LoadedPullRequest) -> list[Json]:
|
|
282
|
+
key = str(loaded.ref)
|
|
283
|
+
if key not in self._files:
|
|
284
|
+
self._files[key] = self.client.get_paginated(
|
|
285
|
+
f"{self._base(loaded)}/pulls/{loaded.ref.number}/files", max_pages=30
|
|
286
|
+
)
|
|
287
|
+
return self._files[key]
|
|
288
|
+
|
|
289
|
+
def _changed_files(self, loaded: LoadedPullRequest, _claims: Sequence[Claim]) -> list[Evidence]:
|
|
290
|
+
# Mapped once per fetch: reading every patch is the costly part, and the summary
|
|
291
|
+
# fetcher needs the same records.
|
|
292
|
+
key = f"{loaded.ref}:records"
|
|
293
|
+
if key not in self._mapped:
|
|
294
|
+
now = self._clock()
|
|
295
|
+
self._mapped[key] = [
|
|
296
|
+
mappers.changed_file_evidence(file, now) for file in self._pull_files(loaded)
|
|
297
|
+
]
|
|
298
|
+
return self._mapped[key]
|
|
299
|
+
|
|
300
|
+
def _files_summary(self, loaded: LoadedPullRequest, claims: Sequence[Claim]) -> list[Evidence]:
|
|
301
|
+
"""PR-level integrity totals, from the same (shared, cached) file list."""
|
|
302
|
+
files = self._changed_files(loaded, claims)
|
|
303
|
+
expected = loaded.pull.get("changed_files")
|
|
304
|
+
return [
|
|
305
|
+
mappers.files_summary_evidence(
|
|
306
|
+
files,
|
|
307
|
+
loaded.ref.number,
|
|
308
|
+
self._clock(),
|
|
309
|
+
expected_files=int(expected) if isinstance(expected, int) else None,
|
|
310
|
+
)
|
|
311
|
+
]
|
|
312
|
+
|
|
313
|
+
def _issue_states(self, loaded: LoadedPullRequest, claims: Sequence[Claim]) -> list[Evidence]:
|
|
314
|
+
records: list[Evidence] = []
|
|
315
|
+
own_repo = loaded.repo
|
|
316
|
+
keyed = [
|
|
317
|
+
((claim.attributes.get("repo") or own_repo, int(claim.attributes["issue"])), claim)
|
|
318
|
+
for claim in claims
|
|
319
|
+
if claim.type == FIXES_ISSUE
|
|
320
|
+
]
|
|
321
|
+
for repo, number in self._first(keyed, MAX_ISSUES_PER_PR, "issue references"):
|
|
322
|
+
try:
|
|
323
|
+
issue = self.client.get(f"/repos/{repo}/issues/{number}")
|
|
324
|
+
except NotFound:
|
|
325
|
+
continue # inaccessible issue: the check reports ISSUE_NOT_ACCESSIBLE
|
|
326
|
+
events = self.client.get_paginated(f"/repos/{repo}/issues/{number}/events")
|
|
327
|
+
evidence = mappers.issue_evidence(issue, events, repo, self._clock())
|
|
328
|
+
if evidence is not None:
|
|
329
|
+
records.append(evidence)
|
|
330
|
+
return records
|
|
331
|
+
|
|
332
|
+
def _reverts(self, loaded: LoadedPullRequest, _claims: Sequence[Claim]) -> list[Evidence]:
|
|
333
|
+
pull = loaded.pull
|
|
334
|
+
if not loaded.merged or not pull.get("merge_commit_sha"):
|
|
335
|
+
return []
|
|
336
|
+
base = pull["base"]
|
|
337
|
+
default_branch = (base.get("repo") or {}).get("default_branch")
|
|
338
|
+
if default_branch and base["ref"] != default_branch:
|
|
339
|
+
# Merged into a feature or release branch (often deleted since): there is no
|
|
340
|
+
# meaningful branch to scan. coding.not_reverted reports NOT_DEFAULT_BRANCH.
|
|
341
|
+
return []
|
|
342
|
+
merged_at = mappers.parse_time(pull["merged_at"])
|
|
343
|
+
until = merged_at + REVERT_WINDOW if merged_at else None
|
|
344
|
+
params = {"sha": base["ref"], "since": pull["merged_at"]}
|
|
345
|
+
if until is not None:
|
|
346
|
+
params["until"] = until.isoformat().replace("+00:00", "Z")
|
|
347
|
+
# Only commits touching one of the PR's files: a full revert must touch it too.
|
|
348
|
+
path = mappers.revert_probe_path(self._pull_files(loaded))
|
|
349
|
+
if path:
|
|
350
|
+
params["path"] = path
|
|
351
|
+
commits = self.client.get_paginated(
|
|
352
|
+
f"{self._base(loaded)}/commits", params, max_pages=REVERT_MAX_PAGES
|
|
353
|
+
)
|
|
354
|
+
return mappers.revert_evidence(
|
|
355
|
+
commits,
|
|
356
|
+
pull["merge_commit_sha"],
|
|
357
|
+
loaded.ref.full_name,
|
|
358
|
+
loaded.ref.number,
|
|
359
|
+
self._clock(),
|
|
360
|
+
title=pull.get("title") or "",
|
|
361
|
+
other_names=(loaded.repo,),
|
|
362
|
+
)
|
|
363
|
+
|
|
364
|
+
def _deployments(self, loaded: LoadedPullRequest, claims: Sequence[Claim]) -> list[Evidence]:
|
|
365
|
+
records: list[Evidence] = []
|
|
366
|
+
keyed = [
|
|
367
|
+
(claim.attributes["ref"], claim)
|
|
368
|
+
for claim in claims
|
|
369
|
+
if claim.type == DEPLOYED and claim.attributes.get("ref")
|
|
370
|
+
]
|
|
371
|
+
for ref in self._first(keyed, MAX_DEPLOY_REFS_PER_PR, "commits with deploy claims"):
|
|
372
|
+
deployments = self.client.get(f"{self._base(loaded)}/deployments", {"sha": ref})
|
|
373
|
+
# GitHub lists deployments newest first; past the cap, a success may be unseen.
|
|
374
|
+
complete = len(deployments) <= MAX_DEPLOYMENTS_PER_REF
|
|
375
|
+
for deployment in deployments[:MAX_DEPLOYMENTS_PER_REF]:
|
|
376
|
+
statuses = self.client.get(
|
|
377
|
+
f"{self._base(loaded)}/deployments/{deployment['id']}/statuses",
|
|
378
|
+
{"per_page": 5},
|
|
379
|
+
)
|
|
380
|
+
evidence = mappers.deployment_evidence(
|
|
381
|
+
deployment, statuses, self._clock(), complete=complete
|
|
382
|
+
)
|
|
383
|
+
if evidence is not None:
|
|
384
|
+
records.append(evidence)
|
|
385
|
+
return records
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Parse pull-request references that users paste: URLs and ``owner/repo#123`` shorthands."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
# GitHub owner and repository names: letters, digits, '-', '_' and '.'.
|
|
9
|
+
_NAME = r"[A-Za-z0-9_.-]+"
|
|
10
|
+
_URL = re.compile(
|
|
11
|
+
rf"^(?:https?://)?(?:www\.)?github\.com/(?P<owner>{_NAME})/(?P<repo>{_NAME})"
|
|
12
|
+
r"/pulls?/(?P<number>\d+)(?:[/?#].*)?$"
|
|
13
|
+
)
|
|
14
|
+
_SHORT = re.compile(rf"^(?P<owner>{_NAME})/(?P<repo>{_NAME})(?:#|/pull/)(?P<number>\d+)$")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class PullRequestRef:
|
|
19
|
+
owner: str
|
|
20
|
+
repo: str
|
|
21
|
+
number: int
|
|
22
|
+
|
|
23
|
+
@property
|
|
24
|
+
def full_name(self) -> str:
|
|
25
|
+
return f"{self.owner}/{self.repo}"
|
|
26
|
+
|
|
27
|
+
@property
|
|
28
|
+
def url(self) -> str:
|
|
29
|
+
return f"https://github.com/{self.owner}/{self.repo}/pull/{self.number}"
|
|
30
|
+
|
|
31
|
+
def __str__(self) -> str:
|
|
32
|
+
return f"{self.full_name}#{self.number}"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def parse_pull_request(text: str) -> PullRequestRef:
|
|
36
|
+
"""Parse a PR reference, or raise ValueError with an example of what is accepted.
|
|
37
|
+
|
|
38
|
+
Accepts ``https://github.com/o/r/pull/7`` (with or without extra path such as
|
|
39
|
+
``/files``), ``github.com/o/r/pull/7``, ``o/r#7`` and ``o/r/pull/7``.
|
|
40
|
+
"""
|
|
41
|
+
candidate = text.strip()
|
|
42
|
+
found = _URL.match(candidate) or _SHORT.match(candidate)
|
|
43
|
+
if not found or found.group("repo") in {".", ".."}:
|
|
44
|
+
raise ValueError(
|
|
45
|
+
f"not a pull request reference: {text!r} "
|
|
46
|
+
"(expected e.g. https://github.com/owner/repo/pull/123 or owner/repo#123)"
|
|
47
|
+
)
|
|
48
|
+
number = int(found.group("number"))
|
|
49
|
+
if number <= 0:
|
|
50
|
+
raise ValueError(f"pull request numbers start at 1: {text!r}")
|
|
51
|
+
return PullRequestRef(found.group("owner"), found.group("repo"), number)
|