gitgatekeeper 0.1.1__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.
Files changed (52) hide show
  1. gitgatekeeper/__init__.py +10 -0
  2. gitgatekeeper/cli/main.py +1074 -0
  3. gitgatekeeper/config/__init__.py +18 -0
  4. gitgatekeeper/config/loader.py +100 -0
  5. gitgatekeeper/config/models.py +205 -0
  6. gitgatekeeper/core/__init__.py +46 -0
  7. gitgatekeeper/core/buffer.py +125 -0
  8. gitgatekeeper/core/commit_engine.py +900 -0
  9. gitgatekeeper/core/detector.py +154 -0
  10. gitgatekeeper/core/discovery.py +172 -0
  11. gitgatekeeper/core/doctor.py +220 -0
  12. gitgatekeeper/core/events.py +89 -0
  13. gitgatekeeper/core/filters.py +79 -0
  14. gitgatekeeper/core/grouping.py +139 -0
  15. gitgatekeeper/core/inactivity.py +154 -0
  16. gitgatekeeper/core/instance.py +202 -0
  17. gitgatekeeper/core/locking.py +85 -0
  18. gitgatekeeper/core/migrate.py +134 -0
  19. gitgatekeeper/core/monitor.py +408 -0
  20. gitgatekeeper/core/project_manager.py +141 -0
  21. gitgatekeeper/core/push_engine.py +441 -0
  22. gitgatekeeper/core/service.py +703 -0
  23. gitgatekeeper/core/systemd.py +223 -0
  24. gitgatekeeper/core/undo.py +104 -0
  25. gitgatekeeper/git/__init__.py +43 -0
  26. gitgatekeeper/git/analyzer.py +96 -0
  27. gitgatekeeper/git/diff.py +252 -0
  28. gitgatekeeper/git/ignore.py +36 -0
  29. gitgatekeeper/git/models.py +118 -0
  30. gitgatekeeper/git/repository.py +123 -0
  31. gitgatekeeper/git/secrets.py +150 -0
  32. gitgatekeeper/git/sensitive.py +114 -0
  33. gitgatekeeper/git/status_parser.py +134 -0
  34. gitgatekeeper/intelligence/__init__.py +23 -0
  35. gitgatekeeper/intelligence/analysis.py +358 -0
  36. gitgatekeeper/intelligence/context.py +57 -0
  37. gitgatekeeper/intelligence/message.py +117 -0
  38. gitgatekeeper/intelligence/profile.py +213 -0
  39. gitgatekeeper/intelligence/provider.py +65 -0
  40. gitgatekeeper/intelligence/rules.py +561 -0
  41. gitgatekeeper/logging_setup.py +122 -0
  42. gitgatekeeper/storage/__init__.py +16 -0
  43. gitgatekeeper/storage/database.py +235 -0
  44. gitgatekeeper/storage/history.py +440 -0
  45. gitgatekeeper/storage/models.py +78 -0
  46. gitgatekeeper/storage/recorder.py +178 -0
  47. gitgatekeeper-0.1.1.dist-info/METADATA +671 -0
  48. gitgatekeeper-0.1.1.dist-info/RECORD +52 -0
  49. gitgatekeeper-0.1.1.dist-info/WHEEL +5 -0
  50. gitgatekeeper-0.1.1.dist-info/entry_points.txt +2 -0
  51. gitgatekeeper-0.1.1.dist-info/licenses/LICENSE +21 -0
  52. gitgatekeeper-0.1.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,235 @@
1
+ """SQLite access: private file, versioned schema, short-lived connections.
2
+
3
+ Every operation opens its own connection, so the database is safe to use from
4
+ the detector's worker threads and from the CLI at the same time as the running
5
+ service (WAL mode, a busy timeout, ``BEGIN IMMEDIATE`` for writes).
6
+
7
+ Nothing here deletes or repairs a damaged database: it reports the problem and
8
+ leaves the file for the user to inspect.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import contextlib
14
+ import os
15
+ import random
16
+ import sqlite3
17
+ import time
18
+ from collections.abc import Iterator
19
+ from pathlib import Path
20
+
21
+ SCHEMA_VERSION = 3
22
+ BUSY_TIMEOUT_SECONDS = 5.0
23
+
24
+ _MIGRATIONS: dict[int, tuple[str, ...]] = {
25
+ 1: (
26
+ """
27
+ CREATE TABLE commits (
28
+ id INTEGER PRIMARY KEY,
29
+ created_at TEXT NOT NULL,
30
+ project TEXT NOT NULL,
31
+ repo TEXT NOT NULL,
32
+ oid TEXT NOT NULL,
33
+ branch TEXT,
34
+ type TEXT NOT NULL,
35
+ scope TEXT,
36
+ subject TEXT NOT NULL,
37
+ body TEXT NOT NULL DEFAULT '',
38
+ confidence TEXT NOT NULL,
39
+ files TEXT NOT NULL,
40
+ fingerprint TEXT NOT NULL,
41
+ pushed_at TEXT,
42
+ push_remote TEXT,
43
+ push_ref TEXT,
44
+ UNIQUE (repo, oid),
45
+ UNIQUE (repo, fingerprint)
46
+ )
47
+ """,
48
+ "CREATE INDEX commits_project ON commits (project, id DESC)",
49
+ "CREATE INDEX commits_oid ON commits (oid)",
50
+ "CREATE INDEX commits_fingerprint ON commits (fingerprint)",
51
+ """
52
+ CREATE TABLE events (
53
+ id INTEGER PRIMARY KEY,
54
+ created_at TEXT NOT NULL,
55
+ project TEXT NOT NULL,
56
+ kind TEXT NOT NULL CHECK (kind IN ('commit', 'push')),
57
+ outcome TEXT NOT NULL,
58
+ reason TEXT,
59
+ detail TEXT NOT NULL DEFAULT '',
60
+ commit_oid TEXT
61
+ )
62
+ """,
63
+ "CREATE INDEX events_project ON events (project, id DESC)",
64
+ ),
65
+ 2: (
66
+ # Commits GitGatekeeper prepared and is holding until the user decides.
67
+ """
68
+ CREATE TABLE pending (
69
+ id INTEGER PRIMARY KEY,
70
+ created_at TEXT NOT NULL,
71
+ decided_at TEXT,
72
+ project TEXT NOT NULL,
73
+ repo TEXT NOT NULL,
74
+ branch TEXT,
75
+ type TEXT NOT NULL,
76
+ scope TEXT,
77
+ subject TEXT NOT NULL,
78
+ body TEXT NOT NULL DEFAULT '',
79
+ confidence TEXT NOT NULL,
80
+ files TEXT NOT NULL,
81
+ content_digest TEXT NOT NULL,
82
+ status TEXT NOT NULL DEFAULT 'pending'
83
+ CHECK (status IN ('pending', 'approved', 'rejected', 'stale')),
84
+ note TEXT NOT NULL DEFAULT '',
85
+ commit_oid TEXT,
86
+ UNIQUE (repo, content_digest)
87
+ )
88
+ """,
89
+ "CREATE INDEX pending_status ON pending (status, id)",
90
+ ),
91
+ 3: (
92
+ # A commit the user took back with `gitgatekeeper undo`.
93
+ "ALTER TABLE commits ADD COLUMN undone_at TEXT",
94
+ ),
95
+ }
96
+
97
+
98
+ class StorageError(Exception):
99
+ """The history database cannot be opened, read or written."""
100
+
101
+
102
+ class Database:
103
+ def __init__(
104
+ self, path: Path, *, busy_timeout: float = BUSY_TIMEOUT_SECONDS
105
+ ) -> None:
106
+ self._path = path
107
+ self._busy_timeout = busy_timeout
108
+
109
+ @property
110
+ def path(self) -> Path:
111
+ return self._path
112
+
113
+ def initialize(self) -> None:
114
+ """Create the private file if needed and bring the schema up to date."""
115
+ try:
116
+ self._path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
117
+ fd = os.open(self._path, os.O_RDWR | os.O_CREAT | os.O_CLOEXEC, 0o600)
118
+ os.close(fd)
119
+ except OSError as exc:
120
+ raise StorageError(f"cannot create {self._path}: {exc}") from exc
121
+
122
+ with self._connect() as connection:
123
+ self._check_integrity(connection)
124
+ self._enable_wal(connection)
125
+ self._migrate(connection)
126
+
127
+ @contextlib.contextmanager
128
+ def connection(self) -> Iterator[sqlite3.Connection]:
129
+ """A connection for reading (autocommit)."""
130
+ with self._connect() as connection:
131
+ yield connection
132
+
133
+ @contextlib.contextmanager
134
+ def transaction(self) -> Iterator[sqlite3.Connection]:
135
+ """A connection inside one write transaction (committed on success)."""
136
+ with self._connect() as connection:
137
+ try:
138
+ connection.execute("BEGIN IMMEDIATE")
139
+ except sqlite3.Error as exc:
140
+ raise StorageError(f"cannot start a transaction: {exc}") from exc
141
+ try:
142
+ yield connection
143
+ except BaseException:
144
+ with contextlib.suppress(sqlite3.Error):
145
+ connection.execute("ROLLBACK")
146
+ raise
147
+ try:
148
+ connection.execute("COMMIT")
149
+ except sqlite3.Error as exc:
150
+ with contextlib.suppress(sqlite3.Error):
151
+ connection.execute("ROLLBACK")
152
+ raise StorageError(f"cannot commit: {exc}") from exc
153
+
154
+ # -- internals --
155
+ @contextlib.contextmanager
156
+ def _connect(self) -> Iterator[sqlite3.Connection]:
157
+ try:
158
+ connection = sqlite3.connect(
159
+ self._path,
160
+ timeout=self._busy_timeout,
161
+ isolation_level=None, # explicit transactions only
162
+ )
163
+ except sqlite3.Error as exc:
164
+ raise StorageError(f"cannot open {self._path}: {exc}") from exc
165
+ try:
166
+ connection.row_factory = sqlite3.Row
167
+ try:
168
+ connection.execute("PRAGMA foreign_keys = ON")
169
+ except sqlite3.Error as exc:
170
+ raise StorageError(f"cannot use {self._path}: {exc}") from exc
171
+ yield connection
172
+ except sqlite3.Error as exc:
173
+ raise StorageError(f"database error in {self._path}: {exc}") from exc
174
+ finally:
175
+ connection.close()
176
+
177
+ def _enable_wal(self, connection: sqlite3.Connection) -> None:
178
+ """Switch to WAL, tolerating other processes doing the same right now.
179
+
180
+ SQLite may answer "database is locked" to this particular PRAGMA at once,
181
+ without waiting for the busy timeout, when another connection is
182
+ switching modes (several processes opening a new file together). It is
183
+ harmless to try again, and a no-op once somebody else has finished.
184
+ """
185
+ deadline = time.monotonic() + self._busy_timeout
186
+ while True:
187
+ try:
188
+ row = connection.execute("PRAGMA journal_mode").fetchone()
189
+ if row is not None and str(row[0]).lower() == "wal":
190
+ return
191
+ connection.execute("PRAGMA journal_mode = WAL")
192
+ return
193
+ except sqlite3.OperationalError as exc:
194
+ text = str(exc).lower()
195
+ busy = "locked" in text or "busy" in text
196
+ if not busy or time.monotonic() >= deadline:
197
+ raise
198
+ time.sleep(random.uniform(0.01, 0.05))
199
+
200
+ def _check_integrity(self, connection: sqlite3.Connection) -> None:
201
+ try:
202
+ result = connection.execute("PRAGMA quick_check").fetchone()
203
+ except sqlite3.DatabaseError as exc:
204
+ raise StorageError(
205
+ f"{self._path} is not a valid database ({exc}); "
206
+ "move it aside to start a fresh history"
207
+ ) from exc
208
+ if result is None or result[0] != "ok":
209
+ raise StorageError(
210
+ f"{self._path} is damaged ({result[0] if result else 'no result'}); "
211
+ "move it aside to start a fresh history"
212
+ )
213
+
214
+ def _migrate(self, connection: sqlite3.Connection) -> None:
215
+ current = connection.execute("PRAGMA user_version").fetchone()[0]
216
+ if current > SCHEMA_VERSION:
217
+ raise StorageError(
218
+ f"{self._path} was written by a newer GitGatekeeper "
219
+ f"(schema {current}, this version understands {SCHEMA_VERSION})"
220
+ )
221
+ if current == SCHEMA_VERSION:
222
+ return
223
+ connection.execute("BEGIN IMMEDIATE")
224
+ try:
225
+ # Re-read inside the lock: another process may have migrated already.
226
+ current = connection.execute("PRAGMA user_version").fetchone()[0]
227
+ for version in range(current + 1, SCHEMA_VERSION + 1):
228
+ for statement in _MIGRATIONS[version]:
229
+ connection.execute(statement)
230
+ connection.execute(f"PRAGMA user_version = {int(version)}")
231
+ connection.execute("COMMIT")
232
+ except BaseException:
233
+ with contextlib.suppress(sqlite3.Error):
234
+ connection.execute("ROLLBACK")
235
+ raise
@@ -0,0 +1,440 @@
1
+ """History of what GitGatekeeper did, kept in SQLite.
2
+
3
+ Stores commit metadata (message, branch, file *names*) and one event per cycle,
4
+ including skipped and failed ones. It never stores file contents or diffs.
5
+ All queries are parameterised.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import sqlite3
12
+ from collections.abc import Callable, Collection
13
+ from datetime import UTC, datetime
14
+ from pathlib import Path
15
+
16
+ from gitgatekeeper.storage.database import Database, StorageError
17
+ from gitgatekeeper.storage.models import CommitRecord, EventRecord, PendingRecord
18
+
19
+ DEFAULT_EVENT_LIMIT = 50
20
+ DEFAULT_COMMIT_LIMIT = 20
21
+ MAX_DETAIL_LENGTH = 1000
22
+
23
+ Clock = Callable[[], datetime]
24
+
25
+
26
+ def _utc_now() -> datetime:
27
+ return datetime.now(UTC)
28
+
29
+
30
+ def _stamp(clock: Clock) -> str:
31
+ return clock().astimezone(UTC).isoformat(timespec="seconds")
32
+
33
+
34
+ class HistoryStore:
35
+ def __init__(self, database: Database, *, clock: Clock = _utc_now) -> None:
36
+ self._db = database
37
+ self._clock = clock
38
+
39
+ @classmethod
40
+ def open(cls, path: Path, *, clock: Clock = _utc_now) -> HistoryStore:
41
+ """Open (creating if needed) the history database at ``path``."""
42
+ database = Database(path)
43
+ database.initialize()
44
+ return cls(database, clock=clock)
45
+
46
+ # -- writing --
47
+ def add_commit(
48
+ self,
49
+ *,
50
+ project: str,
51
+ repo: Path | str,
52
+ oid: str,
53
+ branch: str | None,
54
+ type: str,
55
+ scope: str | None,
56
+ subject: str,
57
+ body: str,
58
+ confidence: str,
59
+ files: Collection[str],
60
+ fingerprint: str,
61
+ ) -> bool:
62
+ """Record a commit. Returns False if this commit or change set is known."""
63
+ with self._db.transaction() as connection:
64
+ cursor = connection.execute(
65
+ """
66
+ INSERT OR IGNORE INTO commits
67
+ (created_at, project, repo, oid, branch, type, scope, subject,
68
+ body, confidence, files, fingerprint)
69
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
70
+ """,
71
+ (
72
+ _stamp(self._clock),
73
+ project,
74
+ str(repo),
75
+ oid,
76
+ branch,
77
+ type,
78
+ scope,
79
+ subject,
80
+ body,
81
+ confidence,
82
+ json.dumps(sorted(files), ensure_ascii=False),
83
+ fingerprint,
84
+ ),
85
+ )
86
+ return cursor.rowcount == 1
87
+
88
+ def add_event(
89
+ self,
90
+ *,
91
+ project: str,
92
+ kind: str,
93
+ outcome: str,
94
+ reason: str | None = None,
95
+ detail: str = "",
96
+ commit_oid: str | None = None,
97
+ ) -> int:
98
+ if len(detail) > MAX_DETAIL_LENGTH:
99
+ detail = detail[: MAX_DETAIL_LENGTH - 3] + "..."
100
+ with self._db.transaction() as connection:
101
+ cursor = connection.execute(
102
+ """
103
+ INSERT INTO events
104
+ (created_at, project, kind, outcome, reason, detail, commit_oid)
105
+ VALUES (?, ?, ?, ?, ?, ?, ?)
106
+ """,
107
+ (
108
+ _stamp(self._clock),
109
+ project,
110
+ kind,
111
+ outcome,
112
+ reason,
113
+ detail,
114
+ commit_oid,
115
+ ),
116
+ )
117
+ return int(cursor.lastrowid or 0)
118
+
119
+ def mark_pushed(
120
+ self, repo: Path | str, oids: Collection[str], *, remote: str, ref: str
121
+ ) -> int:
122
+ """Mark recorded commits as published; returns how many were updated."""
123
+ updated = 0
124
+ stamp = _stamp(self._clock)
125
+ with self._db.transaction() as connection:
126
+ for oid in oids:
127
+ cursor = connection.execute(
128
+ """
129
+ UPDATE commits SET pushed_at = ?, push_remote = ?, push_ref = ?
130
+ WHERE repo = ? AND oid = ? AND pushed_at IS NULL
131
+ """,
132
+ (stamp, remote, ref, str(repo), oid),
133
+ )
134
+ updated += cursor.rowcount
135
+ return updated
136
+
137
+ # -- commits held for approval --
138
+ def add_pending(
139
+ self,
140
+ *,
141
+ project: str,
142
+ repo: Path | str,
143
+ branch: str | None,
144
+ type: str,
145
+ scope: str | None,
146
+ subject: str,
147
+ body: str,
148
+ confidence: str,
149
+ files: Collection[str],
150
+ content_digest: str,
151
+ ) -> int | None:
152
+ """Hold a prepared commit. Returns its id, or None if it is already known.
153
+
154
+ A proposal that is still waiting, or that the user rejected, is not
155
+ added again: a rejection holds until the files change. One that was
156
+ approved (or went stale) earlier and now reappears is opened anew.
157
+ """
158
+ fields = (
159
+ branch,
160
+ type,
161
+ scope,
162
+ subject,
163
+ body,
164
+ confidence,
165
+ json.dumps(sorted(files), ensure_ascii=False),
166
+ )
167
+ with self._db.transaction() as connection:
168
+ row = connection.execute(
169
+ "SELECT id, status FROM pending WHERE repo = ? AND content_digest = ?",
170
+ (str(repo), content_digest),
171
+ ).fetchone()
172
+ if row is None:
173
+ cursor = connection.execute(
174
+ """
175
+ INSERT INTO pending
176
+ (created_at, project, repo, branch, type, scope, subject,
177
+ body, confidence, files, content_digest)
178
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
179
+ """,
180
+ (_stamp(self._clock), project, str(repo), *fields, content_digest),
181
+ )
182
+ return int(cursor.lastrowid or 0)
183
+ if row["status"] in ("pending", "rejected"):
184
+ return None
185
+ connection.execute(
186
+ """
187
+ UPDATE pending SET created_at = ?, decided_at = NULL, note = '',
188
+ commit_oid = NULL, status = 'pending', project = ?, branch = ?,
189
+ type = ?, scope = ?, subject = ?, body = ?, confidence = ?,
190
+ files = ?
191
+ WHERE id = ?
192
+ """,
193
+ (_stamp(self._clock), project, *fields, row["id"]),
194
+ )
195
+ return int(row["id"])
196
+
197
+ def decide_pending(
198
+ self,
199
+ pending_id: int,
200
+ status: str,
201
+ *,
202
+ note: str = "",
203
+ commit_oid: str | None = None,
204
+ ) -> bool:
205
+ """Close a waiting proposal. False if it is not waiting any more."""
206
+ if status not in ("approved", "rejected", "stale"):
207
+ raise ValueError(f"cannot close a proposal as {status!r}")
208
+ with self._db.transaction() as connection:
209
+ cursor = connection.execute(
210
+ """
211
+ UPDATE pending SET status = ?, decided_at = ?, note = ?, commit_oid = ?
212
+ WHERE id = ? AND status = 'pending'
213
+ """,
214
+ (
215
+ status,
216
+ _stamp(self._clock),
217
+ note[:MAX_DETAIL_LENGTH],
218
+ commit_oid,
219
+ pending_id,
220
+ ),
221
+ )
222
+ return cursor.rowcount == 1
223
+
224
+ def stale_pending(
225
+ self, repo: Path | str, keep: Collection[str], note: str = "files changed"
226
+ ) -> int:
227
+ """Close the waiting proposals of ``repo`` whose digest is not in ``keep``."""
228
+ keep = tuple(keep)
229
+ marks = ", ".join("?" for _ in keep)
230
+ guard = f" AND content_digest NOT IN ({marks})" if keep else ""
231
+ with self._db.transaction() as connection:
232
+ cursor = connection.execute(
233
+ f"""
234
+ UPDATE pending SET status = 'stale', decided_at = ?, note = ?
235
+ WHERE repo = ? AND status = 'pending'{guard}
236
+ """,
237
+ (_stamp(self._clock), note, str(repo), *keep),
238
+ )
239
+ return cursor.rowcount
240
+
241
+ def prune_events(self, keep: int) -> int:
242
+ """Delete all but the newest ``keep`` events. Commits are never pruned."""
243
+ if keep < 0:
244
+ raise ValueError("keep must not be negative")
245
+ with self._db.transaction() as connection:
246
+ cursor = connection.execute(
247
+ """
248
+ DELETE FROM events WHERE id NOT IN
249
+ (SELECT id FROM events ORDER BY id DESC LIMIT ?)
250
+ """,
251
+ (keep,),
252
+ )
253
+ return cursor.rowcount
254
+
255
+ # -- lookups used by the engines --
256
+ def owns_commit(self, oid: str) -> bool:
257
+ """True if GitGatekeeper recorded creating commit ``oid``."""
258
+ with self._db.connection() as connection:
259
+ row = connection.execute(
260
+ "SELECT 1 FROM commits WHERE oid = ? LIMIT 1", (oid,)
261
+ ).fetchone()
262
+ return row is not None
263
+
264
+ def has_fingerprint(self, fingerprint: str) -> bool:
265
+ """True if a change set with this fingerprint was already committed."""
266
+ with self._db.connection() as connection:
267
+ row = connection.execute(
268
+ "SELECT 1 FROM commits WHERE fingerprint = ? LIMIT 1", (fingerprint,)
269
+ ).fetchone()
270
+ return row is not None
271
+
272
+ # -- queries for the CLI --
273
+ def recent_commits(
274
+ self, project: str | None = None, limit: int = DEFAULT_COMMIT_LIMIT
275
+ ) -> list[CommitRecord]:
276
+ sql = "SELECT * FROM commits"
277
+ params: list[object] = []
278
+ if project is not None:
279
+ sql += " WHERE project = ?"
280
+ params.append(project)
281
+ sql += " ORDER BY id DESC LIMIT ?"
282
+ params.append(_limit(limit))
283
+ with self._db.connection() as connection:
284
+ return [_commit(row) for row in connection.execute(sql, params)]
285
+
286
+ def unpushed_commits(self, repo: Path | str) -> list[CommitRecord]:
287
+ with self._db.connection() as connection:
288
+ rows = connection.execute(
289
+ "SELECT * FROM commits WHERE repo = ? AND pushed_at IS NULL "
290
+ "AND undone_at IS NULL ORDER BY id DESC",
291
+ (str(repo),),
292
+ )
293
+ return [_commit(row) for row in rows]
294
+
295
+ def recent_events(
296
+ self,
297
+ project: str | None = None,
298
+ *,
299
+ kind: str | None = None,
300
+ limit: int = DEFAULT_EVENT_LIMIT,
301
+ ) -> list[EventRecord]:
302
+ clauses: list[str] = []
303
+ params: list[object] = []
304
+ if project is not None:
305
+ clauses.append("project = ?")
306
+ params.append(project)
307
+ if kind is not None:
308
+ clauses.append("kind = ?")
309
+ params.append(kind)
310
+ where = f" WHERE {' AND '.join(clauses)}" if clauses else ""
311
+ params.append(_limit(limit))
312
+ with self._db.connection() as connection:
313
+ rows = connection.execute(
314
+ f"SELECT * FROM events{where} ORDER BY id DESC LIMIT ?", params
315
+ )
316
+ return [_event(row) for row in rows]
317
+
318
+ def pending(
319
+ self, project: str | None = None, *, limit: int = 200
320
+ ) -> list[PendingRecord]:
321
+ """Proposals waiting for a decision, oldest first."""
322
+ sql = "SELECT * FROM pending WHERE status = 'pending'"
323
+ params: list[object] = []
324
+ if project is not None:
325
+ sql += " AND project = ?"
326
+ params.append(project)
327
+ sql += " ORDER BY id LIMIT ?"
328
+ params.append(_limit(limit))
329
+ with self._db.connection() as connection:
330
+ return [_pending(row) for row in connection.execute(sql, params)]
331
+
332
+ def get_pending(self, pending_id: int) -> PendingRecord | None:
333
+ with self._db.connection() as connection:
334
+ row = connection.execute(
335
+ "SELECT * FROM pending WHERE id = ?", (pending_id,)
336
+ ).fetchone()
337
+ return _pending(row) if row is not None else None
338
+
339
+ def has_commit_since(self, project: str, since: datetime) -> bool:
340
+ """True if a commit was recorded for ``project`` at or after ``since``."""
341
+ with self._db.connection() as connection:
342
+ row = connection.execute(
343
+ "SELECT 1 FROM commits WHERE project = ? AND created_at >= ? LIMIT 1",
344
+ (project, _stamp(lambda: since)),
345
+ ).fetchone()
346
+ return row is not None
347
+
348
+ def last_commit(self, project: str) -> CommitRecord | None:
349
+ """The newest commit of ``project`` that was not taken back."""
350
+ with self._db.connection() as connection:
351
+ row = connection.execute(
352
+ "SELECT * FROM commits WHERE project = ? AND undone_at IS NULL "
353
+ "ORDER BY id DESC LIMIT 1",
354
+ (project,),
355
+ ).fetchone()
356
+ return _commit(row) if row else None
357
+
358
+ def mark_undone(self, commit_id: int) -> bool:
359
+ """Remember that a commit was taken back. The row is kept on purpose: its
360
+ fingerprint stops the same change set from being committed again."""
361
+ with self._db.transaction() as connection:
362
+ cursor = connection.execute(
363
+ "UPDATE commits SET undone_at = ? WHERE id = ? AND undone_at IS NULL",
364
+ (_stamp(self._clock), commit_id),
365
+ )
366
+ return cursor.rowcount == 1
367
+
368
+ def last_event(self, project: str, kind: str | None = None) -> EventRecord | None:
369
+ found = self.recent_events(project, kind=kind, limit=1)
370
+ return found[0] if found else None
371
+
372
+
373
+ def _limit(value: int) -> int:
374
+ if value < 1:
375
+ raise ValueError("limit must be at least 1")
376
+ return value
377
+
378
+
379
+ def _commit(row: sqlite3.Row) -> CommitRecord:
380
+ try:
381
+ files = tuple(json.loads(row["files"]))
382
+ except (TypeError, ValueError) as exc:
383
+ raise StorageError(f"commit {row['id']} has unreadable file list") from exc
384
+ return CommitRecord(
385
+ id=row["id"],
386
+ created_at=row["created_at"],
387
+ project=row["project"],
388
+ repo=row["repo"],
389
+ oid=row["oid"],
390
+ branch=row["branch"],
391
+ type=row["type"],
392
+ scope=row["scope"],
393
+ subject=row["subject"],
394
+ body=row["body"],
395
+ confidence=row["confidence"],
396
+ files=files,
397
+ fingerprint=row["fingerprint"],
398
+ pushed_at=row["pushed_at"],
399
+ push_remote=row["push_remote"],
400
+ push_ref=row["push_ref"],
401
+ undone_at=row["undone_at"],
402
+ )
403
+
404
+
405
+ def _event(row: sqlite3.Row) -> EventRecord:
406
+ return EventRecord(
407
+ id=row["id"],
408
+ created_at=row["created_at"],
409
+ project=row["project"],
410
+ kind=row["kind"],
411
+ outcome=row["outcome"],
412
+ reason=row["reason"],
413
+ detail=row["detail"],
414
+ commit_oid=row["commit_oid"],
415
+ )
416
+
417
+
418
+ def _pending(row: sqlite3.Row) -> PendingRecord:
419
+ try:
420
+ files = tuple(json.loads(row["files"]))
421
+ except (TypeError, ValueError) as exc:
422
+ raise StorageError(f"proposal {row['id']} has unreadable file list") from exc
423
+ return PendingRecord(
424
+ id=row["id"],
425
+ created_at=row["created_at"],
426
+ decided_at=row["decided_at"],
427
+ project=row["project"],
428
+ repo=row["repo"],
429
+ branch=row["branch"],
430
+ type=row["type"],
431
+ scope=row["scope"],
432
+ subject=row["subject"],
433
+ body=row["body"],
434
+ confidence=row["confidence"],
435
+ files=files,
436
+ content_digest=row["content_digest"],
437
+ status=row["status"],
438
+ note=row["note"],
439
+ commit_oid=row["commit_oid"],
440
+ )