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,900 @@
1
+ """Commit Engine: turns a repository's pending changes into one safe commit.
2
+
3
+ Safety model, in order of importance:
4
+
5
+ * **Never touch what the user prepared.** Anything already in the index is the
6
+ user's. The engine only selects files that are *not* staged at all; a file the
7
+ user staged, even partly, is left alone. The commit uses ``git commit --only``
8
+ with an explicit path list, so the user's staged changes stay staged and out
9
+ of the commit.
10
+ * **Prefer doing nothing.** Operations in progress, conflicts, a detached HEAD, a
11
+ locked index, too many files, a possible secret, content that cannot be
12
+ inspected, or any change of state while working all end in a skipped cycle
13
+ with a reason, never in a guess.
14
+ * **Never destroy.** The only undo is ``git reset`` limited to the engine's own
15
+ paths. There is no ``reset --hard``, ``clean``, ``checkout --`` or forced
16
+ operation anywhere, and working-tree files are never rewritten.
17
+ * **Verify.** State is re-read after staging and again after committing.
18
+
19
+ Hooks and signing configured in the repository run as usual: bypassing them
20
+ would defeat checks the user chose to have.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import hashlib
26
+ import logging
27
+ import re
28
+ import subprocess
29
+ from collections.abc import Callable, Sequence
30
+ from dataclasses import dataclass
31
+ from enum import StrEnum
32
+ from fnmatch import fnmatchcase
33
+ from pathlib import Path
34
+ from typing import Any
35
+
36
+ from gitgatekeeper.core.locking import LockHeldError, RepositoryLock
37
+ from gitgatekeeper.git.analyzer import analyze_repository
38
+ from gitgatekeeper.git.diff import DiffSummary, read_staged_diff
39
+ from gitgatekeeper.git.models import ChangeType, FileStatus, RepositorySnapshot
40
+ from gitgatekeeper.git.repository import GitError, find_repository_root, run_git
41
+ from gitgatekeeper.git.secrets import SecretFinding, scan_lines
42
+ from gitgatekeeper.git.sensitive import is_lockfile, is_sensitive_path
43
+ from gitgatekeeper.intelligence.context import add_touched_definitions
44
+ from gitgatekeeper.intelligence.message import CommitMessage
45
+ from gitgatekeeper.intelligence.provider import (
46
+ MessageGenerator,
47
+ generate_commit_message,
48
+ )
49
+
50
+ logger = logging.getLogger(__name__)
51
+
52
+ DEFAULT_MAX_FILES = 50
53
+ GIT_WRITE_TIMEOUT_SECONDS = 30.0
54
+ COMMIT_TIMEOUT_SECONDS = 120.0 # pre-commit hooks can be slow
55
+ _STDERR_TAIL = 500
56
+ _QUERY_BATCH = 200 # paths per read-only git call
57
+
58
+
59
+ class Outcome(StrEnum):
60
+ COMMITTED = "committed"
61
+ NOTHING_TO_COMMIT = "nothing-to-commit"
62
+ SKIPPED = "skipped"
63
+ DRY_RUN = "dry-run"
64
+ HELD = "held" # prepared, waiting for the user's approval
65
+ FAILED = "failed"
66
+
67
+
68
+ class Reason(StrEnum):
69
+ NO_CHANGES = "no-changes"
70
+ ONLY_USER_STAGED = "only-user-staged"
71
+ LOCKED = "locked"
72
+ BLOCKED = "blocked"
73
+ TOO_MANY_FILES = "too-many-files"
74
+ POSSIBLE_SECRET = "possible-secret"
75
+ UNVERIFIABLE_CONTENT = "unverifiable-content"
76
+ CONCURRENT_CHANGE = "concurrent-change"
77
+ DUPLICATE = "duplicate"
78
+ GIT_FAILED = "git-failed"
79
+ COMMIT_REJECTED = "commit-rejected"
80
+ PROTECTED_BRANCH = "protected-branch"
81
+
82
+
83
+ @dataclass(frozen=True, slots=True)
84
+ class CommitResult:
85
+ outcome: Outcome
86
+ repo: Path
87
+ reason: Reason | None = None
88
+ detail: str = ""
89
+ commit: str | None = None # full object id of the new commit
90
+ message: CommitMessage | None = None
91
+ files: tuple[str, ...] = () # paths the commit contains (or would contain)
92
+ skipped_files: tuple[tuple[str, str], ...] = () # (path, why it was left out)
93
+ findings: tuple[SecretFinding, ...] = ()
94
+ warnings: tuple[str, ...] = ()
95
+ fingerprint: str | None = None
96
+ branch: str | None = None
97
+ # Hash of the exact content of ``files`` (without HEAD), for approvals.
98
+ content_digest: str | None = None
99
+
100
+ @property
101
+ def committed(self) -> bool:
102
+ return self.outcome is Outcome.COMMITTED
103
+
104
+
105
+ @dataclass(frozen=True, slots=True)
106
+ class Selection:
107
+ selected: tuple[FileStatus, ...]
108
+ skipped: tuple[tuple[str, str], ...]
109
+
110
+
111
+ def select_files(snapshot: RepositorySnapshot) -> Selection:
112
+ """Choose the files the engine may commit; everything else is left alone."""
113
+ selected: list[FileStatus] = []
114
+ skipped: list[tuple[str, str]] = []
115
+ for status in snapshot.files:
116
+ reason = _exclusion_reason(status)
117
+ if reason is None:
118
+ selected.append(status)
119
+ else:
120
+ skipped.append((status.path, reason))
121
+ return Selection(tuple(selected), tuple(skipped))
122
+
123
+
124
+ def _exclusion_reason(status: FileStatus) -> str | None:
125
+ if status.conflicted:
126
+ return "conflicted"
127
+ if status.staged is not None:
128
+ return "already staged by the user"
129
+ if status.submodule:
130
+ return "submodule"
131
+ if is_sensitive_path(status.path):
132
+ return "sensitive file name"
133
+ if status.unstaged is ChangeType.ADDED and not status.untracked:
134
+ return "marked with intent-to-add by the user"
135
+ return None
136
+
137
+
138
+ Grouper = Callable[[tuple[str, ...]], list[tuple[str, ...]]]
139
+
140
+
141
+ @dataclass(frozen=True, slots=True)
142
+ class _Plan:
143
+ """What one cycle intends to commit (empty before a selection exists)."""
144
+
145
+ root: Path
146
+ paths: tuple[str, ...] = ()
147
+ skipped: tuple[tuple[str, str], ...] = ()
148
+ branch: str | None = None
149
+
150
+
151
+ @dataclass(frozen=True, slots=True)
152
+ class Approval:
153
+ """What the user approved: exactly this content, on this branch, this message."""
154
+
155
+ content_digest: str
156
+ branch: str | None
157
+ message: CommitMessage
158
+
159
+
160
+ def _staged_paths(snapshot: RepositorySnapshot) -> set[str]:
161
+ """Paths touched by the index, counting both ends of a staged rename."""
162
+ return {p for f in snapshot.staged for p in (f.path, f.orig_path) if p}
163
+
164
+
165
+ class _Stop(Exception):
166
+ """Internal: end the cycle with a prepared result."""
167
+
168
+ def __init__(self, result: CommitResult) -> None:
169
+ super().__init__(result.detail)
170
+ self.result = result
171
+
172
+
173
+ class CommitEngine:
174
+ def __init__(
175
+ self,
176
+ *,
177
+ lock_dir: Path,
178
+ generator: MessageGenerator | None = None,
179
+ generator_for: Callable[[Path], MessageGenerator | None] | None = None,
180
+ max_files: int = DEFAULT_MAX_FILES,
181
+ is_duplicate: Callable[[str], bool] | None = None,
182
+ dry_run: bool = False,
183
+ is_protected: Callable[[Path, str], bool] | None = None,
184
+ grouper_for: Callable[[Path], Grouper | None] | None = None,
185
+ max_files_for: Callable[[Path], int] | None = None,
186
+ secret_allow_for: Callable[[Path], Sequence[str]] | None = None,
187
+ hold_for: Callable[[Path], bool] | None = None,
188
+ ) -> None:
189
+ """
190
+ ``lock_dir`` holds the per-repository lock files. ``is_duplicate`` is
191
+ asked about the change-set fingerprint right before committing; return
192
+ True to refuse a change set that was already committed.
193
+ ``generator_for`` picks a message generator per repository (for example
194
+ one that knows the project's architecture); it wins over ``generator``.
195
+ If it fails, the built-in rules are used.
196
+ ``is_protected(root, branch)`` returning True makes the engine refuse to
197
+ commit on that branch. ``grouper_for(root)`` returns a function that
198
+ splits the changed paths into groups for :meth:`run_all`; ``None``
199
+ means one commit for everything. ``hold_for(root)`` returning True
200
+ makes the engine prepare the commit (every check runs) but stop short of
201
+ committing: the result is ``HELD`` and the user decides later through
202
+ :meth:`approve`.
203
+ """
204
+ if max_files < 1:
205
+ raise ValueError("max_files must be at least 1")
206
+ self._lock_dir = lock_dir
207
+ self._generator = generator
208
+ self._generator_for = generator_for
209
+ self._max_files = max_files
210
+ self._is_duplicate = is_duplicate
211
+ self._dry_run = dry_run
212
+ self._is_protected = is_protected
213
+ self._grouper_for = grouper_for
214
+ self._max_files_for = max_files_for
215
+ self._secret_allow_for = secret_allow_for
216
+ self._hold_for = hold_for
217
+
218
+ def _pick_generator(self, root: Path) -> MessageGenerator | None:
219
+ if self._generator_for is None:
220
+ return self._generator
221
+ try:
222
+ return self._generator_for(root)
223
+ except Exception: # a broken profile must never block a commit
224
+ logger.warning("could not build a generator for %s", root, exc_info=True)
225
+ return None
226
+
227
+ def run(self, repo: Path) -> CommitResult:
228
+ """Run one commit cycle for ``repo``. Never raises for Git problems."""
229
+ try:
230
+ root = find_repository_root(repo)
231
+ if root is None:
232
+ return CommitResult(
233
+ Outcome.FAILED,
234
+ repo,
235
+ Reason.GIT_FAILED,
236
+ f"not a Git repository: {repo}",
237
+ )
238
+ try:
239
+ with RepositoryLock(self._lock_dir, root):
240
+ return self._cycle(root)
241
+ except LockHeldError as exc:
242
+ return CommitResult(Outcome.SKIPPED, root, Reason.LOCKED, str(exc))
243
+ except (GitError, OSError) as exc:
244
+ logger.error("commit cycle failed for %s: %s", repo, exc)
245
+ return CommitResult(Outcome.FAILED, repo, Reason.GIT_FAILED, str(exc))
246
+
247
+ def approve(
248
+ self,
249
+ repo: Path,
250
+ paths: Sequence[str],
251
+ approval: Approval,
252
+ ) -> CommitResult:
253
+ """Commit ``paths`` once, if they are exactly what the user approved.
254
+
255
+ Every guard of a normal cycle still applies (protected branch, secret
256
+ scan, conflict markers, locks). In addition the branch and the content
257
+ of the files must be the same as when the commit was proposed; if
258
+ anything differs, nothing is committed.
259
+ """
260
+ try:
261
+ root = find_repository_root(repo)
262
+ if root is None:
263
+ return CommitResult(
264
+ Outcome.FAILED,
265
+ repo,
266
+ Reason.GIT_FAILED,
267
+ f"not a Git repository: {repo}",
268
+ )
269
+ try:
270
+ with RepositoryLock(self._lock_dir, root):
271
+ return self._cycle(root, only=frozenset(paths), approval=approval)
272
+ except LockHeldError as exc:
273
+ return CommitResult(Outcome.SKIPPED, root, Reason.LOCKED, str(exc))
274
+ except (GitError, OSError) as exc:
275
+ logger.error("approved commit failed for %s: %s", repo, exc)
276
+ return CommitResult(Outcome.FAILED, repo, Reason.GIT_FAILED, str(exc))
277
+
278
+ def run_all(self, repo: Path) -> list[CommitResult]:
279
+ """Like :meth:`run`, but one commit per group of related files.
280
+
281
+ Everything happens under a single lock. The loop stops at the first
282
+ group that is not committed; whatever is left is picked up by the next
283
+ cycle, so nothing is lost and nothing is forced.
284
+ """
285
+ try:
286
+ root = find_repository_root(repo)
287
+ if root is None:
288
+ return [self.run(repo)]
289
+ try:
290
+ with RepositoryLock(self._lock_dir, root):
291
+ return self._cycle_groups(root)
292
+ except LockHeldError as exc:
293
+ return [CommitResult(Outcome.SKIPPED, root, Reason.LOCKED, str(exc))]
294
+ except (GitError, OSError) as exc:
295
+ logger.error("commit cycle failed for %s: %s", repo, exc)
296
+ return [CommitResult(Outcome.FAILED, repo, Reason.GIT_FAILED, str(exc))]
297
+
298
+ def _cycle_groups(self, root: Path) -> list[CommitResult]:
299
+ groups = self._plan_groups(root)
300
+ if len(groups) <= 1:
301
+ return [self._cycle(root)]
302
+ results: list[CommitResult] = []
303
+ for group in groups:
304
+ result = self._cycle(root, only=frozenset(group))
305
+ if result.outcome is Outcome.NOTHING_TO_COMMIT and results:
306
+ continue # that group vanished meanwhile; the rest may go on
307
+ results.append(result)
308
+ # A held group leaves the repository untouched, so the next group
309
+ # can be prepared too; anything else ends the cycle.
310
+ if result.outcome not in (Outcome.COMMITTED, Outcome.HELD):
311
+ break
312
+ return results
313
+
314
+ def _plan_groups(self, root: Path) -> list[tuple[str, ...]]:
315
+ if self._grouper_for is None:
316
+ return []
317
+ snapshot = analyze_repository(root)
318
+ if snapshot.blockers or self._protected(root, snapshot):
319
+ return []
320
+ selected = select_files(snapshot).selected
321
+ if not selected or len(selected) > self._limit(root):
322
+ return [] # the plain cycle reports these cases
323
+ try:
324
+ grouper = self._grouper_for(root)
325
+ if grouper is None:
326
+ return []
327
+ groups = grouper(tuple(f.path for f in selected))
328
+ except Exception: # grouping is a nicety, never a reason to fail
329
+ logger.warning("could not group changes for %s", root, exc_info=True)
330
+ return []
331
+ # Defensive: the groups must be an exact partition of the selection.
332
+ flat = [p for g in groups for p in g]
333
+ if sorted(flat) != sorted(f.path for f in selected):
334
+ logger.warning("ignoring an inconsistent grouping for %s", root)
335
+ return []
336
+ return groups
337
+
338
+ def _secret_allow(self, root: Path) -> tuple[str, ...]:
339
+ if self._secret_allow_for is None:
340
+ return ()
341
+ try:
342
+ return tuple(self._secret_allow_for(root))
343
+ except Exception: # a broken setting must not weaken the scan
344
+ logger.warning("secret allow list failed for %s", root, exc_info=True)
345
+ return ()
346
+
347
+ def _limit(self, root: Path) -> int:
348
+ """The file limit for ``root``: its own setting, else the engine's."""
349
+ if self._max_files_for is not None:
350
+ try:
351
+ return max(1, int(self._max_files_for(root)))
352
+ except Exception: # a broken setting must not lift the guard
353
+ logger.warning("max_files lookup failed for %s", root, exc_info=True)
354
+ return self._max_files
355
+
356
+ def _protected(self, root: Path, snapshot: RepositorySnapshot) -> str | None:
357
+ name = snapshot.branch.name
358
+ if self._is_protected is None or name is None:
359
+ return None
360
+ try:
361
+ return name if self._is_protected(root, name) else None
362
+ except Exception: # unknown policy: refuse rather than guess
363
+ logger.warning("protection check failed for %s", root, exc_info=True)
364
+ return name
365
+
366
+ # -- the cycle -------------------------------------------------------------
367
+ def _holds(self, root: Path) -> bool:
368
+ if self._hold_for is None:
369
+ return False
370
+ try:
371
+ return bool(self._hold_for(root))
372
+ except Exception: # unknown policy: hold rather than commit
373
+ logger.warning("approval policy failed for %s", root, exc_info=True)
374
+ return True
375
+
376
+ def _cycle(
377
+ self,
378
+ root: Path,
379
+ only: frozenset[str] | None = None,
380
+ approval: Approval | None = None,
381
+ ) -> CommitResult:
382
+ snapshot = analyze_repository(root)
383
+ if snapshot.blockers:
384
+ return self._result(
385
+ _Plan(root),
386
+ Outcome.SKIPPED,
387
+ Reason.BLOCKED,
388
+ "; ".join(snapshot.blockers),
389
+ )
390
+ if approval is not None and snapshot.branch.name != approval.branch:
391
+ return self._result(
392
+ _Plan(root, branch=snapshot.branch.name),
393
+ Outcome.SKIPPED,
394
+ Reason.CONCURRENT_CHANGE,
395
+ f"the branch changed since the proposal "
396
+ f"(was {approval.branch!r}, now {snapshot.branch.name!r})",
397
+ )
398
+
399
+ selection = select_files(snapshot)
400
+ if only is not None:
401
+ selection = Selection(
402
+ tuple(f for f in selection.selected if f.path in only),
403
+ selection.skipped,
404
+ )
405
+ if not selection.selected:
406
+ only_user = any(
407
+ r == "already staged by the user" for _, r in selection.skipped
408
+ )
409
+ return self._result(
410
+ _Plan(root, skipped=selection.skipped),
411
+ Outcome.NOTHING_TO_COMMIT,
412
+ Reason.ONLY_USER_STAGED if only_user else Reason.NO_CHANGES,
413
+ "",
414
+ )
415
+ protected = self._protected(root, snapshot)
416
+ if protected is not None:
417
+ return self._result(
418
+ _Plan(root, skipped=selection.skipped, branch=protected),
419
+ Outcome.SKIPPED,
420
+ Reason.PROTECTED_BRANCH,
421
+ f"branch {protected!r} is protected; commit on another branch",
422
+ )
423
+ limit = self._limit(root)
424
+ if len(selection.selected) > limit:
425
+ return self._result(
426
+ _Plan(root, skipped=selection.skipped),
427
+ Outcome.SKIPPED,
428
+ Reason.TOO_MANY_FILES,
429
+ f"{len(selection.selected)} files exceed the limit of {limit}",
430
+ )
431
+
432
+ paths = tuple(f.path for f in selection.selected)
433
+ user_paths = tuple(sorted(_staged_paths(snapshot)))
434
+ user_entries = self._index_entries(root, user_paths)
435
+
436
+ try:
437
+ return self._stage_and_commit(
438
+ root,
439
+ snapshot,
440
+ paths,
441
+ user_paths,
442
+ user_entries,
443
+ selection.skipped,
444
+ approval,
445
+ )
446
+ except _Stop as stop:
447
+ return stop.result
448
+
449
+ def _stage_and_commit(
450
+ self,
451
+ root: Path,
452
+ snapshot: RepositorySnapshot,
453
+ paths: tuple[str, ...],
454
+ user_paths: tuple[str, ...],
455
+ user_entries: str,
456
+ skipped: tuple[tuple[str, str], ...],
457
+ approval: Approval | None = None,
458
+ ) -> CommitResult:
459
+ plan = _Plan(root, paths, skipped, snapshot.branch.name)
460
+
461
+ # Last look, right before touching the index: none of our paths may have
462
+ # been staged by the user in the meantime. Nothing of ours is staged yet.
463
+ if self._staged_now(root, paths):
464
+ return self._result(
465
+ plan,
466
+ Outcome.SKIPPED,
467
+ Reason.CONCURRENT_CHANGE,
468
+ "files were staged by the user while the engine was working",
469
+ )
470
+
471
+ added = self._git(
472
+ root,
473
+ [
474
+ "--literal-pathspecs",
475
+ "add",
476
+ "--pathspec-from-file=-",
477
+ "--pathspec-file-nul",
478
+ ],
479
+ input_text=_nul_join(paths),
480
+ )
481
+ if added.returncode != 0:
482
+ detail = _tail(added.stderr)
483
+ if "index.lock" in detail:
484
+ raise self._abort(
485
+ plan, Outcome.SKIPPED, Reason.BLOCKED, "index is locked"
486
+ )
487
+ raise self._abort(
488
+ plan, Outcome.FAILED, Reason.GIT_FAILED, f"git add failed: {detail}"
489
+ )
490
+
491
+ after = analyze_repository(root)
492
+ expected = set(paths) | _staged_paths(snapshot)
493
+ problem = self._state_problem(snapshot, after, expected)
494
+ if problem:
495
+ raise self._abort(plan, Outcome.SKIPPED, Reason.CONCURRENT_CHANGE, problem)
496
+ if self._index_entries(root, user_paths) != user_entries:
497
+ raise self._abort(
498
+ plan,
499
+ Outcome.SKIPPED,
500
+ Reason.CONCURRENT_CHANGE,
501
+ "the user's staged changes were modified",
502
+ )
503
+
504
+ digest = self._content_digest(root, paths)
505
+ if approval is not None and digest != approval.content_digest:
506
+ raise self._abort(
507
+ plan,
508
+ Outcome.SKIPPED,
509
+ Reason.CONCURRENT_CHANGE,
510
+ "the files changed since the commit was proposed",
511
+ )
512
+
513
+ summary = read_staged_diff(root, paths, max_content_files=self._limit(root))
514
+ if not summary.files:
515
+ raise self._abort(
516
+ plan, Outcome.NOTHING_TO_COMMIT, Reason.NO_CHANGES, "nothing staged"
517
+ )
518
+
519
+ markers = _conflict_markers(summary)
520
+ if markers:
521
+ raise self._abort(
522
+ plan,
523
+ Outcome.SKIPPED,
524
+ Reason.BLOCKED,
525
+ f"unresolved conflict markers in {', '.join(markers[:4])}",
526
+ )
527
+ findings, unverifiable = _inspect(summary, self._secret_allow(root))
528
+ if findings:
529
+ raise self._abort(
530
+ plan,
531
+ Outcome.SKIPPED,
532
+ Reason.POSSIBLE_SECRET,
533
+ _describe_findings(findings),
534
+ findings=tuple(findings),
535
+ )
536
+ if unverifiable:
537
+ raise self._abort(
538
+ plan,
539
+ Outcome.SKIPPED,
540
+ Reason.UNVERIFIABLE_CONTENT,
541
+ f"cannot inspect: {', '.join(unverifiable)}",
542
+ )
543
+
544
+ if approval is not None:
545
+ message = approval.message # exactly what the user was shown
546
+ else:
547
+ summary = add_touched_definitions(summary, root)
548
+ message = generate_commit_message(
549
+ summary, generator=self._pick_generator(root)
550
+ )
551
+ fingerprint = self._fingerprint(root, snapshot, paths)
552
+ if self._is_duplicate is not None and self._is_duplicate(fingerprint):
553
+ raise self._abort(
554
+ plan,
555
+ Outcome.SKIPPED,
556
+ Reason.DUPLICATE,
557
+ "this change set was already committed",
558
+ message=message,
559
+ fingerprint=fingerprint,
560
+ )
561
+ if self._dry_run:
562
+ raise self._abort(
563
+ plan,
564
+ Outcome.DRY_RUN,
565
+ None,
566
+ "dry run: nothing was committed",
567
+ message=message,
568
+ fingerprint=fingerprint,
569
+ )
570
+ if approval is None and self._holds(root):
571
+ raise self._abort(
572
+ plan,
573
+ Outcome.HELD,
574
+ None,
575
+ "waiting for your approval (gitgatekeeper pending)",
576
+ message=message,
577
+ fingerprint=fingerprint,
578
+ content_digest=digest,
579
+ )
580
+
581
+ # --literal-pathspecs matters: without it a file named ":!x" or ":(top)y"
582
+ # is read as pathspec syntax and can drag the user's staged files in.
583
+ # --only is what ``git commit -- <paths>`` does anyway; it is spelled out
584
+ # so the intent (leave everything else in the index alone) is explicit.
585
+ args = [
586
+ "--literal-pathspecs",
587
+ "commit",
588
+ "--quiet",
589
+ "--only",
590
+ "-m",
591
+ message.header,
592
+ ]
593
+ if message.body:
594
+ args += ["-m", message.body]
595
+ args += ["--pathspec-from-file=-", "--pathspec-file-nul"]
596
+ done = self._git(
597
+ root, args, input_text=_nul_join(paths), timeout=COMMIT_TIMEOUT_SECONDS
598
+ )
599
+ if done.returncode != 0:
600
+ raise self._abort(
601
+ plan,
602
+ Outcome.FAILED,
603
+ Reason.COMMIT_REJECTED,
604
+ f"git commit failed: {_tail(done.stderr or done.stdout)}",
605
+ message=message,
606
+ fingerprint=fingerprint,
607
+ )
608
+
609
+ warnings = self._verify_commit(root, snapshot, paths, user_paths, user_entries)
610
+ new_head = self._rev_parse(root, "HEAD")
611
+ logger.info(
612
+ "commit created repo=%s commit=%s files=%d header=%r",
613
+ root,
614
+ new_head,
615
+ len(paths),
616
+ message.header,
617
+ )
618
+ return self._result(
619
+ plan,
620
+ Outcome.COMMITTED,
621
+ None,
622
+ "",
623
+ commit=new_head,
624
+ message=message,
625
+ warnings=tuple(warnings),
626
+ fingerprint=fingerprint,
627
+ content_digest=digest,
628
+ )
629
+
630
+ def _abort(
631
+ self,
632
+ plan: _Plan,
633
+ outcome: Outcome,
634
+ reason: Reason | None,
635
+ detail: str,
636
+ **extra: Any,
637
+ ) -> _Stop:
638
+ """Undo the engine's own staging and build the result that ends the cycle."""
639
+ warnings = tuple(extra.pop("warnings", ()))
640
+ if not self._unstage(plan.root, plan.paths):
641
+ warnings += ("could not unstage the engine's own changes",)
642
+ return _Stop(
643
+ self._result(plan, outcome, reason, detail, warnings=warnings, **extra)
644
+ )
645
+
646
+ @staticmethod
647
+ def _result(
648
+ plan: _Plan,
649
+ outcome: Outcome,
650
+ reason: Reason | None,
651
+ detail: str,
652
+ *,
653
+ commit: str | None = None,
654
+ message: CommitMessage | None = None,
655
+ findings: tuple[SecretFinding, ...] = (),
656
+ warnings: tuple[str, ...] = (),
657
+ fingerprint: str | None = None,
658
+ content_digest: str | None = None,
659
+ ) -> CommitResult:
660
+ if outcome in (Outcome.SKIPPED, Outcome.FAILED):
661
+ logger.warning(
662
+ "commit cycle %s repo=%s reason=%s detail=%s",
663
+ outcome.value,
664
+ plan.root,
665
+ reason.value if reason else "-",
666
+ detail,
667
+ )
668
+ return CommitResult(
669
+ outcome,
670
+ plan.root,
671
+ reason,
672
+ detail,
673
+ commit=commit,
674
+ message=message,
675
+ files=plan.paths,
676
+ skipped_files=plan.skipped,
677
+ findings=findings,
678
+ warnings=warnings,
679
+ fingerprint=fingerprint,
680
+ branch=plan.branch,
681
+ content_digest=content_digest,
682
+ )
683
+
684
+ # -- verification ----------------------------------------------------------
685
+ @staticmethod
686
+ def _state_problem(
687
+ before: RepositorySnapshot, after: RepositorySnapshot, expected_staged: set[str]
688
+ ) -> str | None:
689
+ if after.blockers:
690
+ return "; ".join(after.blockers)
691
+ if (
692
+ after.branch.oid != before.branch.oid
693
+ or after.branch.name != before.branch.name
694
+ ):
695
+ return "HEAD moved while the engine was working"
696
+ staged = _staged_paths(after)
697
+ if staged != expected_staged:
698
+ extra = sorted(staged - expected_staged)
699
+ missing = sorted(expected_staged - staged)
700
+ return (
701
+ f"index differs from the plan (unexpected: {extra}, missing: {missing})"
702
+ )
703
+ return None
704
+
705
+ def _verify_commit(
706
+ self,
707
+ root: Path,
708
+ snapshot: RepositorySnapshot,
709
+ paths: tuple[str, ...],
710
+ user_paths: tuple[str, ...],
711
+ user_entries: str,
712
+ ) -> list[str]:
713
+ """Check the finished commit; problems become warnings (it cannot be undone)."""
714
+ warnings: list[str] = []
715
+ new_head = self._rev_parse(root, "HEAD")
716
+ if new_head is None or new_head == snapshot.branch.oid:
717
+ warnings.append("HEAD did not advance after committing")
718
+ return warnings
719
+ if snapshot.branch.oid is not None:
720
+ parent = self._rev_parse(root, "HEAD^")
721
+ if parent != snapshot.branch.oid:
722
+ warnings.append("the new commit's parent is not the previous HEAD")
723
+ listed = self._git(
724
+ root,
725
+ [
726
+ "diff-tree",
727
+ "--no-commit-id",
728
+ "--name-only",
729
+ "-r",
730
+ "-z",
731
+ "--root",
732
+ "HEAD",
733
+ ],
734
+ )
735
+ if listed.returncode == 0:
736
+ committed = {p for p in listed.stdout.split("\0") if p}
737
+ if committed != set(paths):
738
+ warnings.append(
739
+ "the commit's files differ from the plan "
740
+ f"(extra: {sorted(committed - set(paths))}, "
741
+ f"missing: {sorted(set(paths) - committed)})"
742
+ )
743
+ if self._index_entries(root, user_paths) != user_entries:
744
+ warnings.append("the user's staged changes changed during the commit")
745
+ for warning in warnings:
746
+ logger.warning("commit verification: %s (repo=%s)", warning, root)
747
+ return warnings
748
+
749
+ # -- git helpers -----------------------------------------------------------
750
+ def _git(
751
+ self,
752
+ root: Path,
753
+ args: list[str],
754
+ *,
755
+ input_text: str | None = None,
756
+ timeout: float = GIT_WRITE_TIMEOUT_SECONDS,
757
+ ) -> subprocess.CompletedProcess[str]:
758
+ return run_git(args, cwd=root, input_text=input_text, timeout=timeout)
759
+
760
+ def _rev_parse(self, root: Path, rev: str) -> str | None:
761
+ result = self._git(root, ["rev-parse", "--verify", "--quiet", rev])
762
+ return result.stdout.strip() or None if result.returncode == 0 else None
763
+
764
+ def _query_paths(self, root: Path, args: list[str], paths: tuple[str, ...]) -> str:
765
+ """Run a read-only command limited to ``paths`` and join its output.
766
+
767
+ Only ``add``, ``commit`` and ``reset`` accept ``--pathspec-from-file``,
768
+ so these queries pass the paths as arguments, in batches.
769
+ """
770
+ output: list[str] = []
771
+ for start in range(0, len(paths), _QUERY_BATCH):
772
+ batch = paths[start : start + _QUERY_BATCH]
773
+ result = self._git(root, ["--literal-pathspecs", *args, "--", *batch])
774
+ if result.returncode != 0:
775
+ raise GitError(f"git {args[0]} failed: {_tail(result.stderr)}")
776
+ output.append(result.stdout)
777
+ return "".join(output)
778
+
779
+ def _index_entries(self, root: Path, paths: tuple[str, ...]) -> str:
780
+ """Mode, object id and stage of ``paths`` in the index (``""`` if none)."""
781
+ return self._query_paths(root, ["ls-files", "-s", "-z"], paths)
782
+
783
+ def _staged_now(self, root: Path, paths: tuple[str, ...]) -> bool:
784
+ out = self._query_paths(root, ["diff", "--cached", "--name-only", "-z"], paths)
785
+ return bool(out.strip("\0"))
786
+
787
+ def _fingerprint(
788
+ self, root: Path, snapshot: RepositorySnapshot, paths: tuple[str, ...]
789
+ ) -> str:
790
+ digest = hashlib.sha256()
791
+ digest.update((snapshot.branch.oid or "unborn").encode())
792
+ digest.update(b"\0")
793
+ digest.update(
794
+ self._index_entries(root, tuple(sorted(paths))).encode(
795
+ "utf-8", "surrogateescape"
796
+ )
797
+ )
798
+ return digest.hexdigest()
799
+
800
+ def _content_digest(self, root: Path, paths: tuple[str, ...]) -> str:
801
+ """Hash of the staged content of ``paths``; independent of HEAD."""
802
+ entries = self._index_entries(root, tuple(sorted(paths)))
803
+ return hashlib.sha256(entries.encode("utf-8", "surrogateescape")).hexdigest()
804
+
805
+ def _unstage(self, root: Path, paths: tuple[str, ...]) -> bool:
806
+ """Undo the engine's own ``git add`` for ``paths`` (index only)."""
807
+ try:
808
+ result = self._git(
809
+ root,
810
+ [
811
+ "--literal-pathspecs",
812
+ "reset",
813
+ "--quiet",
814
+ "--pathspec-from-file=-",
815
+ "--pathspec-file-nul",
816
+ ],
817
+ input_text=_nul_join(paths),
818
+ )
819
+ except GitError:
820
+ logger.exception("could not unstage %d paths in %s", len(paths), root)
821
+ return False
822
+ if result.returncode != 0:
823
+ logger.error("git reset failed in %s: %s", root, _tail(result.stderr))
824
+ return False
825
+ return True
826
+
827
+
828
+ def _allowed(path: str, patterns: Sequence[str]) -> bool:
829
+ return any(
830
+ fnmatchcase(path, p) or (p.endswith("/") and path.startswith(p))
831
+ for p in patterns
832
+ )
833
+
834
+
835
+ def _inspect(
836
+ summary: DiffSummary, allow: Sequence[str] = ()
837
+ ) -> tuple[list[SecretFinding], list[str]]:
838
+ """Scan added lines for secrets; list files whose content could not be read."""
839
+ findings: list[SecretFinding] = []
840
+ unverifiable: list[str] = []
841
+ for file in summary.files:
842
+ if file.sensitive:
843
+ findings.append(SecretFinding(file.path, "sensitive-file-name"))
844
+ continue
845
+ if file.binary:
846
+ continue
847
+ truncated = file.added is not None and len(file.added_lines) < file.added
848
+ if (not file.content_read or truncated) and not is_lockfile(file.path):
849
+ unverifiable.append(file.path)
850
+ continue
851
+ # A lockfile too big to read whole is machine-written: vet what was read.
852
+ findings.extend(
853
+ scan_lines(
854
+ file.path,
855
+ file.added_lines,
856
+ file.added_line_numbers,
857
+ allow_hardcoded=_allowed(file.path, allow),
858
+ )
859
+ )
860
+ return findings, unverifiable
861
+
862
+
863
+ _CONFLICT_START = re.compile(r"^<{7}(?:\s.*)?$")
864
+ _CONFLICT_END = re.compile(r"^>{7}(?:\s.*)?$")
865
+
866
+
867
+ def _conflict_markers(summary: DiffSummary) -> list[str]:
868
+ """``path:line`` of each file that adds a ``<<<<<<<`` ... ``>>>>>>>`` block."""
869
+ found: list[str] = []
870
+ for file in summary.files:
871
+ if file.binary or not file.content_read:
872
+ continue
873
+ numbers = file.added_line_numbers
874
+ known = len(numbers) == len(file.added_lines)
875
+ start: int | None = None
876
+ for index, line in enumerate(file.added_lines):
877
+ if start is None and _CONFLICT_START.match(line):
878
+ start = numbers[index] if known else 0
879
+ elif start is not None and _CONFLICT_END.match(line):
880
+ found.append(f"{file.path}:{start}" if known else file.path)
881
+ break
882
+ return found
883
+
884
+
885
+ def _describe_findings(findings: list[SecretFinding], limit: int = 4) -> str:
886
+ """Where to look (file:line and rule), never the matched text."""
887
+ ordered = sorted(findings, key=lambda f: (f.path, f.line or 0, f.rule))
888
+ shown = "; ".join(f.describe() for f in ordered[:limit])
889
+ more = len(ordered) - limit
890
+ suffix = f"; and {more} more" if more > 0 else ""
891
+ return f"possible secret in staged changes: {shown}{suffix}"
892
+
893
+
894
+ def _nul_join(paths: tuple[str, ...]) -> str:
895
+ return "".join(f"{p}\0" for p in paths)
896
+
897
+
898
+ def _tail(text: str) -> str:
899
+ text = text.strip()
900
+ return text if len(text) <= _STDERR_TAIL else "..." + text[-_STDERR_TAIL:]