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,261 @@
|
|
|
1
|
+
"""A small, careful GitHub REST client.
|
|
2
|
+
|
|
3
|
+
Responsibilities:
|
|
4
|
+
|
|
5
|
+
- send authenticated requests (token optional) with a fixed, anonymous user agent;
|
|
6
|
+
- follow pagination (``Link: <...>; rel="next"``) up to a caller-chosen page limit;
|
|
7
|
+
- reuse cached responses with ETags (``If-None-Match`` → ``304 Not Modified``);
|
|
8
|
+
- detect rate limiting and raise ``RateLimited`` instead of retrying forever;
|
|
9
|
+
- send write requests (POST, PATCH) for the GitHub Action's check runs and comments;
|
|
10
|
+
- retry transient failures (5xx, network errors) a couple of times with backoff.
|
|
11
|
+
|
|
12
|
+
Everything that varies (HTTP transport, cache, sleep) is injectable so tests never touch the
|
|
13
|
+
network or wait on real time.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import re
|
|
19
|
+
import time
|
|
20
|
+
from collections.abc import Callable
|
|
21
|
+
from dataclasses import dataclass, field
|
|
22
|
+
from typing import Any, Protocol
|
|
23
|
+
|
|
24
|
+
import httpx
|
|
25
|
+
|
|
26
|
+
from second_source import __version__
|
|
27
|
+
|
|
28
|
+
API_ROOT = "https://api.github.com"
|
|
29
|
+
USER_AGENT = f"second-source/{__version__}"
|
|
30
|
+
_NEXT_LINK = re.compile(r'<([^>]+)>;\s*rel="next"')
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class GitHubError(Exception):
|
|
34
|
+
"""An unexpected response from GitHub (after retries)."""
|
|
35
|
+
|
|
36
|
+
def __init__(self, status: int, url: str, message: str = "") -> None:
|
|
37
|
+
super().__init__(f"GitHub returned {status} for {url} {message}".strip())
|
|
38
|
+
self.status = status
|
|
39
|
+
self.url = url
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class NotFound(GitHubError):
|
|
43
|
+
"""404: the resource does not exist or the token cannot see it."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class RateLimited(GitHubError):
|
|
47
|
+
"""The API rate limit is exhausted. Callers should stop and mark data stale."""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class PageLimitReached(GitHubError):
|
|
51
|
+
"""More pages exist than the caller allowed. Callers should treat the data as partial."""
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class ResponseCache(Protocol):
|
|
55
|
+
"""Stores the last good response per URL, with its ETag."""
|
|
56
|
+
|
|
57
|
+
def get(self, url: str) -> tuple[str, Any] | None: ...
|
|
58
|
+
|
|
59
|
+
def put(self, url: str, etag: str, body: Any) -> None: ...
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass
|
|
63
|
+
class MemoryCache:
|
|
64
|
+
"""In-process cache (used by the GitHub Action and in tests)."""
|
|
65
|
+
|
|
66
|
+
entries: dict[str, tuple[str, Any]] = field(default_factory=dict)
|
|
67
|
+
|
|
68
|
+
def get(self, url: str) -> tuple[str, Any] | None:
|
|
69
|
+
return self.entries.get(url)
|
|
70
|
+
|
|
71
|
+
def put(self, url: str, etag: str, body: Any) -> None:
|
|
72
|
+
self.entries[url] = (etag, body)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass
|
|
76
|
+
class RequestStats:
|
|
77
|
+
"""Counts what a run cost, so the CLI can show it and tests can assert on it."""
|
|
78
|
+
|
|
79
|
+
requests: int = 0
|
|
80
|
+
not_modified: int = 0
|
|
81
|
+
# Requests left in the token's rate-limit window, from the last response that said
|
|
82
|
+
# (``x-ratelimit-remaining``); None until GitHub has told us.
|
|
83
|
+
rate_remaining: int | None = None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class GitHubClient:
|
|
87
|
+
def __init__(
|
|
88
|
+
self,
|
|
89
|
+
token: str | None = None,
|
|
90
|
+
*,
|
|
91
|
+
transport: httpx.BaseTransport | None = None,
|
|
92
|
+
cache: ResponseCache | None = None,
|
|
93
|
+
retries: int = 2,
|
|
94
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
95
|
+
timeout: float = 20.0,
|
|
96
|
+
) -> None:
|
|
97
|
+
headers = {
|
|
98
|
+
"Accept": "application/vnd.github+json",
|
|
99
|
+
"X-GitHub-Api-Version": "2022-11-28",
|
|
100
|
+
"User-Agent": USER_AGENT,
|
|
101
|
+
}
|
|
102
|
+
if token:
|
|
103
|
+
headers["Authorization"] = f"Bearer {token}"
|
|
104
|
+
self._http = httpx.Client(
|
|
105
|
+
base_url=API_ROOT, headers=headers, transport=transport, timeout=timeout
|
|
106
|
+
)
|
|
107
|
+
self._cache = cache or MemoryCache()
|
|
108
|
+
self._retries = retries
|
|
109
|
+
self._sleep = sleep
|
|
110
|
+
self.stats = RequestStats()
|
|
111
|
+
self.authenticated = bool(token)
|
|
112
|
+
|
|
113
|
+
def close(self) -> None:
|
|
114
|
+
self._http.close()
|
|
115
|
+
|
|
116
|
+
def __enter__(self) -> GitHubClient:
|
|
117
|
+
return self
|
|
118
|
+
|
|
119
|
+
def __exit__(self, *_exc: object) -> None:
|
|
120
|
+
self.close()
|
|
121
|
+
|
|
122
|
+
# ---- public API --------------------------------------------------------------------------
|
|
123
|
+
|
|
124
|
+
def get(self, path: str, params: dict[str, Any] | None = None) -> Any:
|
|
125
|
+
"""GET one resource and return its JSON body."""
|
|
126
|
+
body, _next = self._get_page(self._url(path, params))
|
|
127
|
+
return body
|
|
128
|
+
|
|
129
|
+
def get_paginated(
|
|
130
|
+
self, path: str, params: dict[str, Any] | None = None, *, max_pages: int = 3
|
|
131
|
+
) -> list[Any]:
|
|
132
|
+
"""GET a list resource across pages (100 items per page).
|
|
133
|
+
|
|
134
|
+
Raises PageLimitReached if more pages remain after ``max_pages``, so callers never
|
|
135
|
+
mistake a truncated list for a complete one.
|
|
136
|
+
"""
|
|
137
|
+
url: str | None = self._url(path, {"per_page": 100, **(params or {})})
|
|
138
|
+
items: list[Any] = []
|
|
139
|
+
for _ in range(max_pages):
|
|
140
|
+
assert url is not None
|
|
141
|
+
body, url = self._get_page(url)
|
|
142
|
+
# Some list endpoints wrap items (e.g. check-runs: {"check_runs": [...]}).
|
|
143
|
+
items.extend(body if isinstance(body, list) else _unwrap(body))
|
|
144
|
+
if url is None:
|
|
145
|
+
return items
|
|
146
|
+
raise PageLimitReached(200, path, f"(more than {max_pages} pages)")
|
|
147
|
+
|
|
148
|
+
def post(self, path: str, body: dict[str, Any]) -> Any:
|
|
149
|
+
"""Create a resource. Not retried: a repeated POST could create a duplicate."""
|
|
150
|
+
return self._write("POST", path, body, retry=False)
|
|
151
|
+
|
|
152
|
+
def patch(self, path: str, body: dict[str, Any]) -> Any:
|
|
153
|
+
"""Update a resource. Retried on transient failures, because PATCH is idempotent."""
|
|
154
|
+
return self._write("PATCH", path, body, retry=True)
|
|
155
|
+
|
|
156
|
+
# ---- internals ---------------------------------------------------------------------------
|
|
157
|
+
|
|
158
|
+
def _write(self, method: str, path: str, body: dict[str, Any], *, retry: bool) -> Any:
|
|
159
|
+
"""Send a write request (never cached) and return the JSON response, if any."""
|
|
160
|
+
attempts = self._retries + 1 if retry else 1
|
|
161
|
+
for attempt in range(attempts):
|
|
162
|
+
try:
|
|
163
|
+
response = self._http.request(method, path, json=body)
|
|
164
|
+
except httpx.TransportError as error:
|
|
165
|
+
if attempt == attempts - 1:
|
|
166
|
+
raise GitHubError(0, path, f"network error: {error}") from error
|
|
167
|
+
self._sleep(2**attempt)
|
|
168
|
+
continue
|
|
169
|
+
self.stats.requests += 1
|
|
170
|
+
self._note_rate(response)
|
|
171
|
+
if response.status_code in (200, 201):
|
|
172
|
+
return response.json()
|
|
173
|
+
if response.status_code == 204:
|
|
174
|
+
return None
|
|
175
|
+
if response.status_code == 404:
|
|
176
|
+
raise NotFound(404, path)
|
|
177
|
+
if _is_rate_limited(response):
|
|
178
|
+
raise RateLimited(response.status_code, path, "(rate limit exhausted)")
|
|
179
|
+
if response.status_code >= 500 and attempt < attempts - 1:
|
|
180
|
+
self._sleep(2**attempt)
|
|
181
|
+
continue
|
|
182
|
+
raise GitHubError(response.status_code, path)
|
|
183
|
+
raise AssertionError("unreachable") # the loop always returns or raises
|
|
184
|
+
|
|
185
|
+
def _note_rate(self, response: httpx.Response) -> None:
|
|
186
|
+
remaining = response.headers.get("x-ratelimit-remaining", "")
|
|
187
|
+
if remaining.isdigit():
|
|
188
|
+
self.stats.rate_remaining = int(remaining)
|
|
189
|
+
|
|
190
|
+
def _url(self, path: str, params: dict[str, Any] | None) -> str:
|
|
191
|
+
request = self._http.build_request("GET", path, params=params)
|
|
192
|
+
return str(request.url)
|
|
193
|
+
|
|
194
|
+
def _get_page(self, url: str) -> tuple[Any, str | None]:
|
|
195
|
+
"""Fetch one page, using the cache and retrying transient failures."""
|
|
196
|
+
cached = self._cache.get(url)
|
|
197
|
+
headers = {"If-None-Match": cached[0]} if cached else {}
|
|
198
|
+
|
|
199
|
+
for attempt in range(self._retries + 1):
|
|
200
|
+
try:
|
|
201
|
+
# Renamed or transferred repositories answer with a 301 pointing at the new
|
|
202
|
+
# location (/repositories/<id>/...). Follow it for reads; the token is kept
|
|
203
|
+
# because the redirect stays on api.github.com. Writes never follow redirects.
|
|
204
|
+
response = self._http.get(url, headers=headers, follow_redirects=True)
|
|
205
|
+
except httpx.TransportError as error:
|
|
206
|
+
if attempt == self._retries:
|
|
207
|
+
raise GitHubError(0, url, f"network error: {error}") from error
|
|
208
|
+
self._sleep(2**attempt)
|
|
209
|
+
continue
|
|
210
|
+
self.stats.requests += 1 + len(response.history) # each redirect hop is a request
|
|
211
|
+
self._note_rate(response)
|
|
212
|
+
|
|
213
|
+
if response.status_code == 304 and cached:
|
|
214
|
+
self.stats.not_modified += 1
|
|
215
|
+
return cached[1], _next_link(response)
|
|
216
|
+
if response.status_code == 200:
|
|
217
|
+
body = response.json()
|
|
218
|
+
etag = response.headers.get("ETag")
|
|
219
|
+
if etag:
|
|
220
|
+
self._cache.put(url, etag, body)
|
|
221
|
+
return body, _next_link(response)
|
|
222
|
+
if response.status_code == 404:
|
|
223
|
+
raise NotFound(404, url)
|
|
224
|
+
if _is_rate_limited(response):
|
|
225
|
+
raise RateLimited(response.status_code, url, "(rate limit exhausted)")
|
|
226
|
+
if response.status_code >= 500 and attempt < self._retries:
|
|
227
|
+
self._sleep(2**attempt)
|
|
228
|
+
continue
|
|
229
|
+
raise GitHubError(response.status_code, url)
|
|
230
|
+
raise AssertionError("unreachable") # the loop always returns or raises
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _next_link(response: httpx.Response) -> str | None:
|
|
234
|
+
"""The next page's URL, only if it stays on the API host: the token goes with it
|
|
235
|
+
(security review 1, L7)."""
|
|
236
|
+
found = _NEXT_LINK.search(response.headers.get("Link", ""))
|
|
237
|
+
if found is None:
|
|
238
|
+
return None
|
|
239
|
+
url = found.group(1)
|
|
240
|
+
if not url.startswith(API_ROOT + "/"):
|
|
241
|
+
raise GitHubError(response.status_code, url, "(next page is not on the GitHub API)")
|
|
242
|
+
return url
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _is_rate_limited(response: httpx.Response) -> bool:
|
|
246
|
+
"""GitHub signals rate limits with 403 or 429 plus specific headers."""
|
|
247
|
+
if response.status_code not in (403, 429):
|
|
248
|
+
return False
|
|
249
|
+
return (
|
|
250
|
+
response.headers.get("x-ratelimit-remaining") == "0"
|
|
251
|
+
or "retry-after" in response.headers
|
|
252
|
+
or response.status_code == 429
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _unwrap(body: dict[str, Any]) -> list[Any]:
|
|
257
|
+
"""Return the single list inside a wrapped list response (e.g. ``check_runs``)."""
|
|
258
|
+
lists = [value for value in body.values() if isinstance(value, list)]
|
|
259
|
+
if len(lists) != 1:
|
|
260
|
+
raise GitHubError(200, "", "unexpected list response shape")
|
|
261
|
+
return lists[0]
|