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,703 @@
1
+ """The GitGatekeeper service: watches projects and runs the commit/push cycle.
2
+
3
+ Flow for each project::
4
+
5
+ file change ─▶ monitor ─▶ inactivity detector ─(quiet for N minutes)─▶ cycle
6
+ cycle: commit engine ─▶ [push engine if auto_push] ─▶ history
7
+
8
+ It runs in the foreground until :meth:`GitGatekeeperService.request_stop` is called
9
+ (the CLI wires that to SIGINT/SIGTERM). Running it in the background is the job
10
+ of a supervisor such as systemd, not of this class.
11
+
12
+ Restarts lose nothing: on start every project is scanned, and one with pending
13
+ changes (or, with auto-push, unpublished commits) is queued again as if it had
14
+ just been touched.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import contextlib
20
+ import json
21
+ import logging
22
+ import os
23
+ import threading
24
+ import time
25
+ from collections.abc import Callable, Mapping
26
+ from dataclasses import dataclass
27
+ from datetime import UTC, date, datetime
28
+ from datetime import time as clock_time
29
+ from fnmatch import fnmatchcase
30
+ from pathlib import Path
31
+
32
+ from gitgatekeeper.config import AppConfig, ProjectConfig
33
+ from gitgatekeeper.core.commit_engine import (
34
+ Approval,
35
+ CommitEngine,
36
+ CommitResult,
37
+ Grouper,
38
+ Outcome,
39
+ Reason,
40
+ )
41
+ from gitgatekeeper.core.detector import InactivityDetector
42
+ from gitgatekeeper.core.grouping import group_paths
43
+ from gitgatekeeper.core.inactivity import thresholds_from_config
44
+ from gitgatekeeper.core.instance import InstanceLock
45
+ from gitgatekeeper.core.monitor import (
46
+ MonitoredProject,
47
+ ProjectActivity,
48
+ RepositoryMonitor,
49
+ )
50
+ from gitgatekeeper.core.push_engine import (
51
+ PushEngine,
52
+ PushOutcome,
53
+ PushReason,
54
+ PushResult,
55
+ )
56
+ from gitgatekeeper.git.analyzer import analyze_repository
57
+ from gitgatekeeper.git.models import FileStatus
58
+ from gitgatekeeper.git.repository import GitError
59
+ from gitgatekeeper.intelligence import CommitType, RuleBasedGenerator
60
+ from gitgatekeeper.intelligence.message import CommitMessage, Confidence
61
+ from gitgatekeeper.intelligence.profile import detect_profile
62
+ from gitgatekeeper.storage import (
63
+ HistoryRecorder,
64
+ HistoryStore,
65
+ StorageError,
66
+ )
67
+
68
+ logger = logging.getLogger(__name__)
69
+
70
+
71
+ def _same_repo(configured: Path, root: Path) -> bool:
72
+ try:
73
+ return configured.resolve() == root.resolve()
74
+ except OSError:
75
+ return False
76
+
77
+
78
+ DB_FILE_NAME = "gitgatekeeper.db"
79
+ STATUS_FILE_NAME = "status.json"
80
+ DEFAULT_STATUS_INTERVAL_SECONDS = 5.0
81
+ # Waits (seconds) before each new attempt after a transient push failure.
82
+ DEFAULT_RETRY_DELAYS = (60.0, 300.0, 900.0, 1800.0, 1800.0, 1800.0)
83
+ TRANSIENT_PUSH_REASONS = frozenset({PushReason.NETWORK, PushReason.TIMEOUT})
84
+
85
+
86
+ class ServiceError(Exception):
87
+ """The service cannot start (nothing to monitor, history unavailable...)."""
88
+
89
+
90
+ def _local_now() -> datetime:
91
+ return datetime.now().astimezone()
92
+
93
+
94
+ def _modified_since(root: Path, files: tuple[FileStatus, ...], since: datetime) -> bool:
95
+ """True if any pending file was written at or after ``since``."""
96
+ cutoff = since.timestamp()
97
+ for item in files:
98
+ try:
99
+ if (root / item.path).stat().st_mtime >= cutoff:
100
+ return True
101
+ except OSError:
102
+ continue # deleted files carry no timestamp
103
+ return False
104
+
105
+
106
+ def _describe_reload(
107
+ added: tuple[str, ...], removed: tuple[str, ...], changed: tuple[str, ...]
108
+ ) -> str:
109
+ parts = [
110
+ f"{label}: {', '.join(names)}"
111
+ for label, names in (
112
+ ("added", added),
113
+ ("removed", removed),
114
+ ("changed", changed),
115
+ )
116
+ if names
117
+ ]
118
+ return "; ".join(parts) or "settings updated"
119
+
120
+
121
+ def history_path(state_dir: Path) -> Path:
122
+ return state_dir / DB_FILE_NAME
123
+
124
+
125
+ def status_path(state_dir: Path) -> Path:
126
+ return state_dir / STATUS_FILE_NAME
127
+
128
+
129
+ @dataclass(frozen=True, slots=True)
130
+ class ReloadResult:
131
+ """What a configuration reload did. On failure the old configuration stays."""
132
+
133
+ ok: bool
134
+ detail: str
135
+ added: tuple[str, ...] = ()
136
+ removed: tuple[str, ...] = ()
137
+ changed: tuple[str, ...] = ()
138
+
139
+
140
+ @dataclass(frozen=True, slots=True)
141
+ class CycleReport:
142
+ project: str
143
+ commit: CommitResult
144
+ push: PushResult | None
145
+ commits: tuple[CommitResult, ...] = ()
146
+
147
+
148
+ class GitGatekeeperService:
149
+ def __init__(
150
+ self,
151
+ config: AppConfig,
152
+ *,
153
+ state_dir: Path,
154
+ store: HistoryStore | None = None,
155
+ commit_engine: CommitEngine | None = None,
156
+ push_engine: PushEngine | None = None,
157
+ thresholds: Mapping[str, float] | None = None,
158
+ debounce: float = 2.0,
159
+ max_wait: float = 10.0,
160
+ status_interval: float = DEFAULT_STATUS_INTERVAL_SECONDS,
161
+ retry_delays: tuple[float, ...] = DEFAULT_RETRY_DELAYS,
162
+ clock: Callable[[], datetime] = _local_now,
163
+ config_loader: Callable[[], AppConfig] | None = None,
164
+ ) -> None:
165
+ self._config = config
166
+ self._config_loader = config_loader
167
+ self._fixed_thresholds = thresholds is not None
168
+ self._reload_requested = threading.Event()
169
+ self._reload_count = 0
170
+ self._last_reload: dict[str, object] | None = None
171
+ self._clock = clock
172
+ self._state_dir = state_dir
173
+ self._projects: dict[str, ProjectConfig] = {
174
+ p.name: p for p in config.projects if p.enabled
175
+ }
176
+ if not self._projects:
177
+ raise ServiceError("no enabled projects to monitor")
178
+ if status_interval <= 0:
179
+ raise ValueError("status_interval must be positive")
180
+ self._debounce = debounce
181
+ self._max_wait = max_wait
182
+ self._status_interval = status_interval
183
+ self._thresholds = dict(thresholds or thresholds_from_config(config))
184
+
185
+ if store is None:
186
+ try:
187
+ store = HistoryStore.open(history_path(state_dir))
188
+ except StorageError as exc:
189
+ raise ServiceError(f"history database unavailable: {exc}") from exc
190
+ self._store = store
191
+ self._recorder = HistoryRecorder(store)
192
+ locks = state_dir / "locks"
193
+ self._commit_engine = commit_engine or CommitEngine(
194
+ lock_dir=locks,
195
+ is_duplicate=self._recorder.is_duplicate,
196
+ generator_for=self._generator_for,
197
+ is_protected=self._is_protected,
198
+ grouper_for=self._grouper_for,
199
+ max_files_for=self._max_files_for,
200
+ secret_allow_for=self._secret_allow_for,
201
+ hold_for=self._hold_for,
202
+ )
203
+ self._push_engine = push_engine or PushEngine(
204
+ lock_dir=locks,
205
+ owns_commit=self._recorder.owns_commit,
206
+ is_protected=self._is_protected,
207
+ )
208
+
209
+ self._retry_delays = tuple(retry_delays)
210
+ self._retry_lock = threading.Lock()
211
+ self._retry_due: dict[str, tuple[float, int]] = {} # name -> (when, attempt)
212
+ self._retry_running: set[str] = set()
213
+ self._retry_threads: list[threading.Thread] = []
214
+
215
+ self._touched: dict[str, date] = {} # project -> last day we saw activity
216
+ self._daily_done: date | None = None
217
+ self._daily_thread: threading.Thread | None = None
218
+
219
+ self._stop = threading.Event()
220
+ self._started_at: datetime | None = None
221
+ self._monitor: RepositoryMonitor | None = None
222
+ self._detector: InactivityDetector | None = None
223
+
224
+ # -- lifecycle ---------------------------------------------------------------
225
+ def request_stop(self) -> None:
226
+ """Ask :meth:`run` to return. Safe from a signal handler or any thread."""
227
+ self._stop.set()
228
+
229
+ def request_reload(self) -> None:
230
+ """Ask :meth:`run` to re-read the configuration. Safe in a signal handler."""
231
+ self._reload_requested.set()
232
+
233
+ def run(self) -> None:
234
+ """Run until :meth:`request_stop`. Raises if another instance is running."""
235
+ with InstanceLock(self._state_dir):
236
+ self._stop.clear()
237
+ self._started_at = datetime.now(UTC)
238
+ try:
239
+ self._start()
240
+ self._write_status()
241
+ while not self._stop.wait(self._status_interval):
242
+ if self._reload_requested.is_set():
243
+ self._reload_requested.clear()
244
+ self.reload()
245
+ self._write_status()
246
+ self._start_due_retries()
247
+ self._start_daily_commit()
248
+ finally:
249
+ self._shutdown()
250
+
251
+ def _start(self) -> None:
252
+ detector = InactivityDetector(
253
+ {n: t for n, t in self._thresholds.items() if n in self._projects},
254
+ self.process,
255
+ )
256
+
257
+ def on_activity(activity: ProjectActivity) -> None:
258
+ self._touched[activity.project] = self._clock().date()
259
+ detector.handle_activity(activity)
260
+
261
+ monitor = RepositoryMonitor(
262
+ [MonitoredProject(p.name, p.path) for p in self._projects.values()],
263
+ on_activity,
264
+ debounce=self._debounce,
265
+ max_wait=self._max_wait,
266
+ )
267
+ detector.start()
268
+ try:
269
+ monitor.start()
270
+ except BaseException:
271
+ detector.stop()
272
+ raise
273
+ self._detector, self._monitor = detector, monitor
274
+ for name, reason in monitor.errors.items():
275
+ logger.error("cannot watch project %s: %s", name, reason)
276
+ logger.info(
277
+ "GitGatekeeper started: watching %s", ", ".join(monitor.watched_projects)
278
+ )
279
+ self._scan_pending(monitor.watched_projects)
280
+
281
+ def _stop_watchers(self) -> None:
282
+ monitor, detector = self._monitor, self._detector
283
+ # Monitor first, so its last pending batch still reaches the detector;
284
+ # the detector then lets any running cycle finish.
285
+ if monitor is not None:
286
+ monitor.stop()
287
+ if detector is not None:
288
+ detector.stop()
289
+ self._monitor = self._detector = None
290
+
291
+ def _shutdown(self) -> None:
292
+ logger.info("GitGatekeeper stopping")
293
+ self._stop_watchers()
294
+ for thread in list(self._retry_threads):
295
+ thread.join(timeout=5.0)
296
+ if self._daily_thread is not None:
297
+ self._daily_thread.join(timeout=5.0)
298
+ with contextlib.suppress(OSError):
299
+ status_path(self._state_dir).unlink()
300
+ logger.info("GitGatekeeper stopped")
301
+
302
+ # -- configuration reload ------------------------------------------------------
303
+ def reload(self) -> ReloadResult:
304
+ """Re-read the configuration file and apply it without a restart.
305
+
306
+ Never raises for a bad file: the current configuration stays in force
307
+ and the result says why. The outcome is also published in the status
308
+ file so ``gitgatekeeper reload`` can report it.
309
+ """
310
+ try:
311
+ result = self._reload()
312
+ except Exception as exc: # the service must survive any reload problem
313
+ logger.exception("configuration reload failed")
314
+ result = ReloadResult(False, f"reload failed: {exc}")
315
+ self._reload_count += 1
316
+ self._last_reload = {
317
+ "seq": self._reload_count,
318
+ "at": datetime.now(UTC).isoformat(timespec="seconds"),
319
+ "ok": result.ok,
320
+ "detail": result.detail,
321
+ }
322
+ if result.ok:
323
+ logger.info("configuration reloaded: %s", result.detail)
324
+ else:
325
+ logger.error("configuration not reloaded: %s", result.detail)
326
+ self._write_status()
327
+ return result
328
+
329
+ def _reload(self) -> ReloadResult:
330
+ if self._config_loader is None:
331
+ return ReloadResult(False, "this instance cannot reload its configuration")
332
+ try:
333
+ new = self._config_loader()
334
+ except Exception as exc:
335
+ return ReloadResult(False, f"cannot read the configuration: {exc}")
336
+ enabled = {p.name: p for p in new.projects if p.enabled}
337
+ if not enabled:
338
+ return ReloadResult(
339
+ False, "the configuration enables no project; keeping the current one"
340
+ )
341
+ if new == self._config:
342
+ return ReloadResult(True, "nothing changed")
343
+
344
+ old = self._projects
345
+ added = tuple(sorted(set(enabled) - set(old)))
346
+ removed = tuple(sorted(set(old) - set(enabled)))
347
+ changed = tuple(
348
+ sorted(n for n in set(enabled) & set(old) if enabled[n] != old[n])
349
+ )
350
+ thresholds = thresholds_from_config(new)
351
+ if self._fixed_thresholds: # explicit windows win; new projects use the config
352
+ thresholds = {**thresholds, **self._thresholds}
353
+ same_watch = {n: p.path for n, p in enabled.items()} == {
354
+ n: p.path for n, p in old.items()
355
+ } and {n: thresholds.get(n) for n in enabled} == {
356
+ n: self._thresholds.get(n) for n in enabled
357
+ }
358
+ previous = (self._config, self._projects, self._thresholds)
359
+ if same_watch: # only settings changed: nothing to re-watch
360
+ self._config, self._projects, self._thresholds = new, enabled, thresholds
361
+ else:
362
+ self._stop_watchers()
363
+ self._config, self._projects, self._thresholds = new, enabled, thresholds
364
+ try:
365
+ self._start()
366
+ except Exception as exc:
367
+ logger.exception("cannot watch the new configuration; rolling back")
368
+ self._config, self._projects, self._thresholds = previous
369
+ self._start() # if even this fails the service stops: let it raise
370
+ return ReloadResult(False, f"cannot apply the configuration: {exc}")
371
+ with self._retry_lock:
372
+ for name in removed:
373
+ self._retry_due.pop(name, None)
374
+ return ReloadResult(
375
+ True, _describe_reload(added, removed, changed), added, removed, changed
376
+ )
377
+
378
+ def _scan_pending(self, watched: list[str]) -> None:
379
+ """Queue projects that already have work waiting (restart recovery)."""
380
+ detector = self._detector
381
+ assert detector is not None
382
+ for name in watched:
383
+ project = self._projects[name]
384
+ try:
385
+ snapshot = analyze_repository(project.path)
386
+ except GitError as exc:
387
+ logger.error("startup scan of %s failed: %s", name, exc)
388
+ continue
389
+ unpublished = self._config.effective_auto_push(project) and bool(
390
+ snapshot.branch.ahead
391
+ )
392
+ if snapshot.files or unpublished:
393
+ logger.info("project %s has pending work; queued", name)
394
+ detector.record_activity(name)
395
+
396
+ def _generator_for(self, root: Path) -> RuleBasedGenerator:
397
+ """A message generator that knows the architecture of the repository."""
398
+ project = next(
399
+ (p for p in self._projects.values() if _same_repo(p.path, root)), None
400
+ )
401
+ modules = project.modules if project else {}
402
+ return RuleBasedGenerator(profile=detect_profile(root, modules))
403
+
404
+ def _project_for(self, root: Path) -> ProjectConfig | None:
405
+ return next(
406
+ (p for p in self._projects.values() if _same_repo(p.path, root)), None
407
+ )
408
+
409
+ def _is_protected(self, root: Path, branch: str) -> bool:
410
+ project = self._project_for(root)
411
+ if project is None: # not one of ours: be conservative
412
+ patterns = self._config.protected_branches
413
+ else:
414
+ patterns = self._config.effective_protected_branches(project)
415
+ return any(fnmatchcase(branch, pattern) for pattern in patterns)
416
+
417
+ def _secret_allow_for(self, root: Path) -> list[str]:
418
+ project = self._project_for(root)
419
+ return list(project.secret_scan_allow) if project else []
420
+
421
+ def _max_files_for(self, root: Path) -> int:
422
+ project = self._project_for(root)
423
+ if project is None:
424
+ return self._config.max_files_per_commit
425
+ return self._config.effective_max_files(project)
426
+
427
+ def _hold_for(self, root: Path) -> bool:
428
+ project = self._project_for(root)
429
+ if project is None: # not one of ours: never commit unasked
430
+ return True
431
+ return self._config.effective_require_approval(project)
432
+
433
+ def _grouper_for(self, root: Path) -> Grouper | None:
434
+ project = self._project_for(root)
435
+ if project is None or not self._config.effective_split_commits(project):
436
+ return None
437
+ profile = detect_profile(root, project.modules)
438
+ return lambda paths: group_paths(paths, profile.module_for)
439
+
440
+ # -- one cycle -----------------------------------------------------------------
441
+ def process(self, name: str) -> CycleReport:
442
+ """Run the commit (and, if enabled, push) cycle for one project."""
443
+ project = self._projects[name]
444
+ commits = self._commit_engine.run_all(project.path)
445
+ self._recorder.record_held(name, commits)
446
+ for item in commits:
447
+ if item.outcome is Outcome.HELD:
448
+ continue # recorded above, once per proposal
449
+ if item.outcome is not Outcome.NOTHING_TO_COMMIT: # quiet is not news
450
+ self._recorder.record_commit(name, item)
451
+ elif item.reason is Reason.NO_CHANGES:
452
+ self._recorder.record_clean(item.repo)
453
+ commit = commits[-1]
454
+
455
+ push = self._publish(name, project)
456
+ logger.info(
457
+ "cycle %s: commit=%s push=%s",
458
+ name,
459
+ ",".join(c.outcome.value for c in commits),
460
+ push.outcome.value if push else "disabled",
461
+ )
462
+ return CycleReport(name, commit, push, tuple(commits))
463
+
464
+ def _publish(
465
+ self, name: str, project: ProjectConfig, *, plan_retry: bool = True
466
+ ) -> PushResult | None:
467
+ """Push if ``auto_push`` is on for the project; record the outcome."""
468
+ if not self._config.effective_auto_push(project):
469
+ return None
470
+ push = self._push_engine.run(project.path)
471
+ if push.outcome is not PushOutcome.NOTHING_TO_PUSH:
472
+ self._recorder.record_push(name, push)
473
+ if plan_retry:
474
+ self._plan_retry(name, push, attempt=0)
475
+ return push
476
+
477
+ # -- approvals ---------------------------------------------------------------
478
+ def approve(self, pending_id: int) -> tuple[CommitResult, PushResult | None]:
479
+ """Commit a held proposal if nothing changed since it was prepared.
480
+
481
+ Raises :class:`ServiceError` for an unknown or already closed proposal.
482
+ A proposal whose files or branch changed is closed as stale and nothing
483
+ is committed; one blocked for another reason stays open.
484
+ """
485
+ record = self._store.get_pending(pending_id)
486
+ if record is None:
487
+ raise ServiceError(f"no held commit #{pending_id}")
488
+ if record.status != "pending":
489
+ raise ServiceError(f"commit #{pending_id} was already {record.status}")
490
+ project = self._projects.get(record.project)
491
+ if project is None:
492
+ raise ServiceError(
493
+ f"project {record.project!r} is not enabled in the configuration"
494
+ )
495
+ message = CommitMessage(
496
+ type=CommitType(record.type),
497
+ subject=record.subject,
498
+ scope=record.scope,
499
+ body=record.body,
500
+ confidence=Confidence(record.confidence),
501
+ )
502
+ result = self._commit_engine.approve(
503
+ Path(record.repo),
504
+ record.files,
505
+ Approval(record.content_digest, record.branch, message),
506
+ )
507
+ if result.outcome is not Outcome.NOTHING_TO_COMMIT:
508
+ self._recorder.record_commit(record.project, result)
509
+ if result.committed:
510
+ self._store.decide_pending(pending_id, "approved", commit_oid=result.commit)
511
+ return result, self._publish(record.project, project, plan_retry=False)
512
+ gone = result.outcome is Outcome.NOTHING_TO_COMMIT
513
+ if gone or result.reason is Reason.CONCURRENT_CHANGE:
514
+ self._store.decide_pending(
515
+ pending_id, "stale", note=result.detail or "the changes are gone"
516
+ )
517
+ return result, None
518
+
519
+ # -- push retries -------------------------------------------------------
520
+ def _plan_retry(self, name: str, push: PushResult, attempt: int) -> None:
521
+ """Schedule another push attempt after a transient failure, else clear."""
522
+ transient = push.reason in TRANSIENT_PUSH_REASONS
523
+ with self._retry_lock:
524
+ if not transient or attempt >= len(self._retry_delays):
525
+ if transient:
526
+ logger.warning(
527
+ "giving up retrying the push of %s; the next cycle or "
528
+ "restart will try again",
529
+ name,
530
+ )
531
+ self._retry_due.pop(name, None)
532
+ return
533
+ delay = self._retry_delays[attempt]
534
+ self._retry_due[name] = (time.monotonic() + delay, attempt + 1)
535
+ logger.info("push of %s failed (%s); retrying in %ds", name, push.reason, delay)
536
+
537
+ def _start_due_retries(self) -> None:
538
+ now = time.monotonic()
539
+ with self._retry_lock:
540
+ due = [
541
+ (n, a)
542
+ for n, (when, a) in self._retry_due.items()
543
+ if when <= now and n not in self._retry_running
544
+ ]
545
+ for name, _ in due:
546
+ self._retry_running.add(name)
547
+ self._retry_threads = [t for t in self._retry_threads if t.is_alive()]
548
+ for name, attempt in due:
549
+ thread = threading.Thread(
550
+ target=self._retry_push,
551
+ args=(name, attempt),
552
+ name=f"gitgatekeeper-push-retry-{name}",
553
+ daemon=True,
554
+ )
555
+ with self._retry_lock:
556
+ self._retry_threads.append(thread)
557
+ thread.start()
558
+
559
+ def _retry_push(self, name: str, attempt: int) -> None:
560
+ try:
561
+ project = self._projects[name]
562
+ if not self._config.effective_auto_push(project):
563
+ with self._retry_lock:
564
+ self._retry_due.pop(name, None)
565
+ return
566
+ result = self._push_engine.run(project.path)
567
+ if result.outcome is not PushOutcome.NOTHING_TO_PUSH:
568
+ self._recorder.record_push(name, result)
569
+ self._plan_retry(name, result, attempt=attempt)
570
+ except Exception:
571
+ logger.exception("push retry for %s crashed", name)
572
+ with self._retry_lock:
573
+ self._retry_due.pop(name, None)
574
+ finally:
575
+ with self._retry_lock:
576
+ self._retry_running.discard(name)
577
+
578
+ # -- end-of-day commit --------------------------------------------------------
579
+ def daily_commit_due(self, now: datetime) -> bool:
580
+ """True once per local day, from ``daily_commit_time`` onwards."""
581
+ if not any(
582
+ self._config.effective_daily_commit(p) for p in self._projects.values()
583
+ ):
584
+ return False
585
+ if self._daily_done == now.date():
586
+ return False
587
+ hour, minute = map(int, self._config.daily_commit_time.split(":"))
588
+ return now.time() >= clock_time(hour, minute)
589
+
590
+ def _start_daily_commit(self) -> None:
591
+ now = self._clock()
592
+ thread = self._daily_thread
593
+ if (thread is not None and thread.is_alive()) or not self.daily_commit_due(now):
594
+ return
595
+ self._daily_done = now.date()
596
+ thread = threading.Thread(
597
+ target=self._daily_guarded,
598
+ args=(now,),
599
+ name="gitgatekeeper-daily-commit",
600
+ daemon=True,
601
+ )
602
+ self._daily_thread = thread
603
+ thread.start()
604
+
605
+ def _daily_guarded(self, now: datetime) -> None:
606
+ try:
607
+ self.run_daily_commit(now)
608
+ except Exception:
609
+ logger.exception("the end-of-day commit crashed")
610
+
611
+ def run_daily_commit(self, now: datetime) -> list[str]:
612
+ """Commit the projects worked on today that got no commit today.
613
+
614
+ Goes through the normal cycle, so protected branches, the file limit,
615
+ the secret scan and ``auto_push`` apply exactly as always. Returns the
616
+ names of the projects it ran a cycle for.
617
+ """
618
+ day_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
619
+ ran: list[str] = []
620
+ for name, project in self._projects.items():
621
+ if self._stop.is_set():
622
+ break
623
+ try:
624
+ if not self._daily_candidate(name, project, day_start):
625
+ continue
626
+ logger.info("end-of-day commit: running the cycle for %s", name)
627
+ self.process(name)
628
+ ran.append(name)
629
+ except Exception:
630
+ logger.exception("end-of-day commit for %s failed", name)
631
+ return ran
632
+
633
+ def _daily_candidate(
634
+ self, name: str, project: ProjectConfig, day_start: datetime
635
+ ) -> bool:
636
+ if not self._config.effective_daily_commit(project):
637
+ return False
638
+ if self._store.has_commit_since(name, day_start):
639
+ return False # already has a commit today
640
+ try:
641
+ snapshot = analyze_repository(project.path)
642
+ except GitError as exc:
643
+ logger.error("end-of-day scan of %s failed: %s", name, exc)
644
+ return False
645
+ if not snapshot.files:
646
+ return False
647
+ if self._is_protected(project.path, snapshot.branch.name):
648
+ logger.info("end-of-day: %s is on a protected branch; skipped", name)
649
+ return False
650
+ return self._touched.get(name) == day_start.date() or _modified_since(
651
+ project.path, snapshot.files, day_start
652
+ )
653
+
654
+ # -- status file (read by `gitgatekeeper status`) ---
655
+ def _write_status(self) -> None:
656
+ detector, monitor = self._detector, self._monitor
657
+ if detector is None or monitor is None or self._started_at is None:
658
+ return
659
+ snapshots = {s.project: s for s in detector.snapshot()}
660
+ errors = monitor.errors
661
+ watched = set(monitor.watched_projects)
662
+ projects = []
663
+ for name, project in self._projects.items():
664
+ snap = snapshots.get(name)
665
+ projects.append(
666
+ {
667
+ "name": name,
668
+ "watching": name in watched,
669
+ "error": errors.get(name),
670
+ "state": snap.state.value if snap else "idle",
671
+ "idle_seconds": snap.idle_seconds if snap else None,
672
+ "remaining_seconds": snap.remaining_seconds if snap else None,
673
+ "threshold_seconds": snap.threshold_seconds if snap else None,
674
+ "auto_push": self._config.effective_auto_push(project),
675
+ }
676
+ )
677
+ payload = {
678
+ "reload_supported": True,
679
+ "reload": self._last_reload,
680
+ "pid": os.getpid(),
681
+ "started_at": self._started_at.isoformat(timespec="seconds"),
682
+ "updated_at": time.time(),
683
+ "interval": self._status_interval,
684
+ "projects": projects,
685
+ }
686
+ path = status_path(self._state_dir)
687
+ tmp = path.with_suffix(".tmp")
688
+ try:
689
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
690
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
691
+ json.dump(payload, handle)
692
+ os.replace(tmp, path)
693
+ except OSError:
694
+ logger.exception("could not write the status file")
695
+
696
+
697
+ def read_status(state_dir: Path) -> dict[str, object] | None:
698
+ """The running service's last status snapshot, or ``None`` if unreadable."""
699
+ try:
700
+ data = json.loads(status_path(state_dir).read_text(encoding="utf-8"))
701
+ except (OSError, ValueError):
702
+ return None
703
+ return data if isinstance(data, dict) else None