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,134 @@
1
+ """Copy settings and history from the old name (GitPilot) to GitGatekeeper.
2
+
3
+ The program used to be called ``gitpilot``. Its files lived under that name, so
4
+ a new install would start empty. Everything here only *copies*: the old files
5
+ are never changed or deleted, and nothing already present under the new name is
6
+ overwritten.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import shutil
13
+ import sqlite3
14
+ from dataclasses import dataclass
15
+ from pathlib import Path
16
+
17
+ LEGACY_NAME = "gitpilot"
18
+ LEGACY_DB = "gitpilot.db"
19
+ LEGACY_PID = "gitpilot.pid"
20
+ NEW_DB = "gitgatekeeper.db"
21
+
22
+
23
+ class MigrationError(Exception):
24
+ """Raised when the old installation cannot be copied safely."""
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class LegacyPaths:
29
+ config: Path
30
+ state_dir: Path
31
+ unit: Path
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class Step:
36
+ done: bool
37
+ message: str
38
+
39
+
40
+ def legacy_paths(
41
+ env: dict[str, str] | None = None, home: Path | None = None
42
+ ) -> LegacyPaths:
43
+ """Where the old installation kept its files."""
44
+ environ = os.environ if env is None else env
45
+ base = home if home is not None else Path.home()
46
+ override = environ.get("GITPILOT_STATE_DIR")
47
+ if override:
48
+ state = Path(override).expanduser()
49
+ else:
50
+ xdg = environ.get("XDG_STATE_HOME")
51
+ state = (Path(xdg) if xdg else base / ".local" / "state") / LEGACY_NAME
52
+ config_root = environ.get("XDG_CONFIG_HOME")
53
+ unit_root = Path(config_root) if config_root else base / ".config"
54
+ return LegacyPaths(
55
+ config=base / ".config" / LEGACY_NAME / "projects.yaml",
56
+ state_dir=state,
57
+ unit=unit_root / "systemd" / "user" / f"{LEGACY_NAME}.service",
58
+ )
59
+
60
+
61
+ def _old_instance_running(state_dir: Path) -> int | None:
62
+ pid_file = state_dir / LEGACY_PID
63
+ try:
64
+ pid = int(pid_file.read_text(encoding="utf-8").split()[0])
65
+ except (OSError, ValueError, IndexError):
66
+ return None
67
+ try:
68
+ os.kill(pid, 0)
69
+ except ProcessLookupError:
70
+ return None
71
+ except PermissionError:
72
+ return pid
73
+ return pid
74
+
75
+
76
+ def migrate(legacy: LegacyPaths, new_config: Path, new_state_dir: Path) -> list[Step]:
77
+ """Copy config and history. Returns what was done and what was skipped."""
78
+ pid = _old_instance_running(legacy.state_dir)
79
+ if pid is not None:
80
+ raise MigrationError(
81
+ f"the old GitPilot is still running (pid {pid}); stop it first with "
82
+ "`gitpilot stop`, or `systemctl --user disable --now gitpilot` if it "
83
+ "runs as a service"
84
+ )
85
+ steps: list[Step] = []
86
+ steps.append(_copy_config(legacy.config, new_config))
87
+ steps.append(_copy_history(legacy.state_dir / LEGACY_DB, new_state_dir / NEW_DB))
88
+ if legacy.unit.exists():
89
+ steps.append(
90
+ Step(
91
+ False,
92
+ f"old systemd unit found at {legacy.unit}; remove it with "
93
+ "`systemctl --user disable --now gitpilot && rm "
94
+ f"{legacy.unit} && systemctl --user daemon-reload`, then run "
95
+ "`gitgatekeeper service install`",
96
+ )
97
+ )
98
+ return steps
99
+
100
+
101
+ def _copy_config(source: Path, target: Path) -> Step:
102
+ if not source.is_file():
103
+ return Step(False, f"no old configuration at {source}")
104
+ if target.exists():
105
+ return Step(False, f"configuration already exists at {target}; left alone")
106
+ try:
107
+ target.parent.mkdir(parents=True, exist_ok=True)
108
+ shutil.copy2(source, target)
109
+ except OSError as exc:
110
+ raise MigrationError(f"cannot copy {source} to {target}: {exc}") from exc
111
+ return Step(True, f"configuration copied to {target}")
112
+
113
+
114
+ def _copy_history(source: Path, target: Path) -> Step:
115
+ if not source.is_file():
116
+ return Step(False, f"no old history at {source}")
117
+ if target.exists():
118
+ return Step(False, f"history already exists at {target}; left alone")
119
+ try:
120
+ target.parent.mkdir(parents=True, exist_ok=True)
121
+ # The backup API copies a consistent snapshot even with a -wal file.
122
+ src = sqlite3.connect(f"file:{source}?mode=ro", uri=True)
123
+ try:
124
+ dst = sqlite3.connect(target)
125
+ try:
126
+ src.backup(dst)
127
+ finally:
128
+ dst.close()
129
+ finally:
130
+ src.close()
131
+ except (OSError, sqlite3.Error) as exc:
132
+ target.unlink(missing_ok=True)
133
+ raise MigrationError(f"cannot copy history {source}: {exc}") from exc
134
+ return Step(True, f"history copied to {target}")
@@ -0,0 +1,408 @@
1
+ """Multi-repository file monitor built on Watchdog.
2
+
3
+ Design notes
4
+ ------------
5
+ * Each repository gets one non-recursive watch on its root plus one recursive
6
+ watch per *top-level* directory. Directories such as ``node_modules`` or
7
+ ``.venv`` (and top-level directories ignored by ``.gitignore``) are never
8
+ watched, which keeps inotify usage low.
9
+ * Raw events pass through cheap in-process filters, then are coalesced per
10
+ project by a :class:`ChangeBuffer` (debounce). ``.gitignore`` is applied once
11
+ per delivered batch via ``git check-ignore``, not once per event.
12
+ * Only the root watch decides when top-level directories appear or vanish:
13
+ it sees them in order, from a single kernel queue. The recursive watches
14
+ also emit a "deleted" event for their own directory, which can arrive after
15
+ the directory was recreated and would wrongly drop the new watch.
16
+ * Dropping a watch discards the events still queued for it, so when a
17
+ top-level directory disappears its removal is reported as one ``DELETED``
18
+ change of the directory itself. That signal comes from the root watch and
19
+ never depends on file events that may have been lost.
20
+ * Observer threads only enqueue; a single worker thread attaches new
21
+ directories and delivers batches, so a slow callback cannot stall event
22
+ collection and one project can never block another.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import logging
28
+ import os
29
+ import threading
30
+ from collections.abc import Callable, Sequence
31
+ from dataclasses import dataclass, field
32
+ from datetime import UTC, datetime
33
+ from pathlib import Path
34
+ from typing import Literal
35
+
36
+ from watchdog.events import (
37
+ DirCreatedEvent,
38
+ DirDeletedEvent,
39
+ DirMovedEvent,
40
+ FileCreatedEvent,
41
+ FileDeletedEvent,
42
+ FileModifiedEvent,
43
+ FileMovedEvent,
44
+ FileSystemEvent,
45
+ FileSystemEventHandler,
46
+ )
47
+ from watchdog.observers import Observer
48
+ from watchdog.observers.api import BaseObserver, ObservedWatch
49
+
50
+ from gitgatekeeper.core.buffer import ChangeBuffer, PendingBatch
51
+ from gitgatekeeper.core.events import (
52
+ ChangeKind,
53
+ FileChange,
54
+ ProjectActivity,
55
+ drop_ignored,
56
+ translate_file_event,
57
+ )
58
+ from gitgatekeeper.core.filters import is_ignored_dir_name
59
+ from gitgatekeeper.git import GitError, find_ignored
60
+
61
+ logger = logging.getLogger(__name__)
62
+
63
+ ActivityCallback = Callable[[ProjectActivity], None]
64
+
65
+ DEFAULT_DEBOUNCE_SECONDS = 2.0
66
+ DEFAULT_MAX_WAIT_SECONDS = 10.0
67
+ STOP_JOIN_TIMEOUT_SECONDS = 5.0
68
+
69
+ _WATCHED_EVENTS = [
70
+ FileCreatedEvent,
71
+ FileModifiedEvent,
72
+ FileDeletedEvent,
73
+ FileMovedEvent,
74
+ DirCreatedEvent,
75
+ DirDeletedEvent,
76
+ DirMovedEvent,
77
+ ]
78
+ _KINDS = {
79
+ "created": ChangeKind.CREATED,
80
+ "modified": ChangeKind.MODIFIED,
81
+ "deleted": ChangeKind.DELETED,
82
+ "moved": ChangeKind.MOVED,
83
+ }
84
+
85
+ _Action = Literal["attach", "detach"]
86
+
87
+
88
+ @dataclass(frozen=True, slots=True)
89
+ class MonitoredProject:
90
+ name: str
91
+ repo: Path # absolute repository root
92
+
93
+
94
+ class _Handler(FileSystemEventHandler):
95
+ def __init__(self, callback: Callable[[FileSystemEvent], None]) -> None:
96
+ super().__init__()
97
+ self._callback = callback
98
+
99
+ def on_any_event(self, event: FileSystemEvent) -> None:
100
+ self._callback(event)
101
+
102
+
103
+ @dataclass(slots=True)
104
+ class _ProjectState:
105
+ project: MonitoredProject
106
+ handler: _Handler
107
+ root_watch: ObservedWatch | None = None
108
+ dir_watches: dict[str, ObservedWatch] = field(default_factory=dict)
109
+
110
+
111
+ class RepositoryMonitor:
112
+ """Watches several repositories and reports debounced, filtered activity.
113
+
114
+ ``on_activity`` runs on the monitor's worker thread. An exception raised by
115
+ it is logged with its traceback and does not stop the monitor.
116
+ """
117
+
118
+ def __init__(
119
+ self,
120
+ projects: Sequence[MonitoredProject],
121
+ on_activity: ActivityCallback,
122
+ *,
123
+ debounce: float = DEFAULT_DEBOUNCE_SECONDS,
124
+ max_wait: float = DEFAULT_MAX_WAIT_SECONDS,
125
+ ) -> None:
126
+ names = [p.name for p in projects]
127
+ if len(set(names)) != len(names):
128
+ raise ValueError("project names must be unique")
129
+ self._projects = {p.name: p for p in projects}
130
+ self._on_activity = on_activity
131
+ self._debounce = debounce
132
+ self._max_wait = max_wait
133
+
134
+ self._lifecycle_lock = threading.Lock()
135
+ self._cond = threading.Condition()
136
+ self._buffer = ChangeBuffer(debounce, max_wait) # validates the arguments
137
+ self._requests: list[tuple[_Action, str, Path]] = []
138
+ self._stopping = False
139
+ self._observer: BaseObserver | None = None
140
+ self._worker: threading.Thread | None = None
141
+ self._states: dict[str, _ProjectState] = {}
142
+ self._errors: dict[str, str] = {}
143
+
144
+ # -- public API ------------------------------------------------------
145
+ @property
146
+ def is_running(self) -> bool:
147
+ return self._observer is not None
148
+
149
+ @property
150
+ def watched_projects(self) -> list[str]:
151
+ """Names of projects that are actually being watched."""
152
+ return [name for name in self._projects if name in self._states]
153
+
154
+ @property
155
+ def errors(self) -> dict[str, str]:
156
+ """Projects that could not be watched, with the reason."""
157
+ return dict(self._errors)
158
+
159
+ def start(self) -> None:
160
+ """Begin watching. May be called again after :meth:`stop`."""
161
+ with self._lifecycle_lock:
162
+ if self._observer is not None:
163
+ raise RuntimeError("monitor is already running")
164
+ self._buffer = ChangeBuffer(self._debounce, self._max_wait)
165
+ self._requests = []
166
+ self._stopping = False
167
+ self._states = {}
168
+ self._errors = {}
169
+
170
+ observer = Observer()
171
+ for project in self._projects.values():
172
+ self._start_project(observer, project)
173
+ observer.start()
174
+ worker = threading.Thread(
175
+ target=self._run, name="gitgatekeeper-monitor", daemon=True
176
+ )
177
+ worker.start()
178
+ self._observer = observer
179
+ self._worker = worker
180
+
181
+ def stop(self) -> None:
182
+ """Stop watching and deliver any still-pending activity. Idempotent."""
183
+ with self._lifecycle_lock:
184
+ observer, worker = self._observer, self._worker
185
+ if observer is None or worker is None:
186
+ return
187
+ observer.stop()
188
+ observer.join(timeout=STOP_JOIN_TIMEOUT_SECONDS)
189
+ with self._cond:
190
+ self._stopping = True
191
+ self._cond.notify_all()
192
+ worker.join(timeout=STOP_JOIN_TIMEOUT_SECONDS)
193
+ self._observer = None
194
+ self._worker = None
195
+
196
+ def __enter__(self) -> RepositoryMonitor:
197
+ self.start()
198
+ return self
199
+
200
+ def __exit__(self, *exc_info: object) -> None:
201
+ self.stop()
202
+
203
+ # -- watch setup -----------------------------------------------------
204
+ def _start_project(self, observer: BaseObserver, project: MonitoredProject) -> None:
205
+ handler = _Handler(
206
+ lambda event, p=project: self._handle_event(p, event, from_root=False)
207
+ )
208
+ root_handler = _Handler(
209
+ lambda event, p=project: self._handle_event(p, event, from_root=True)
210
+ )
211
+ state = _ProjectState(project, handler)
212
+ try:
213
+ if not project.repo.is_dir():
214
+ raise FileNotFoundError(f"directory not found: {project.repo}")
215
+ state.root_watch = observer.schedule(
216
+ root_handler,
217
+ str(project.repo),
218
+ recursive=False,
219
+ event_filter=_WATCHED_EVENTS,
220
+ )
221
+ names = sorted(
222
+ entry.name
223
+ for entry in os.scandir(project.repo)
224
+ if entry.is_dir(follow_symlinks=False)
225
+ and not is_ignored_dir_name(entry.name)
226
+ )
227
+ ignored = self._ignored(project.repo, [f"{n}/" for n in names])
228
+ for name in names:
229
+ if f"{name}/" in ignored:
230
+ continue
231
+ state.dir_watches[name] = observer.schedule(
232
+ handler,
233
+ str(project.repo / name),
234
+ recursive=True,
235
+ event_filter=_WATCHED_EVENTS,
236
+ )
237
+ except OSError as exc:
238
+ for watch in (state.root_watch, *state.dir_watches.values()):
239
+ if watch is not None:
240
+ observer.unschedule(watch)
241
+ self._errors[project.name] = str(exc)
242
+ logger.error("cannot watch %s: %s", project.name, exc)
243
+ return
244
+ self._states[project.name] = state
245
+
246
+ @staticmethod
247
+ def _ignored(repo: Path, paths: list[str]) -> set[str]:
248
+ try:
249
+ return find_ignored(repo, paths)
250
+ except GitError as exc:
251
+ # Fail open: watching a little too much is safe, missing work is not.
252
+ logger.warning("cannot evaluate .gitignore in %s: %s", repo, exc)
253
+ return set()
254
+
255
+ # -- observer thread -------------------------------------------------
256
+ def _handle_event(
257
+ self, project: MonitoredProject, event: FileSystemEvent, *, from_root: bool
258
+ ) -> None:
259
+ kind = _KINDS.get(event.event_type)
260
+ if kind is None:
261
+ return
262
+ src = self._relative(project, event.src_path)
263
+ dest = None
264
+ if kind is ChangeKind.MOVED:
265
+ dest = self._relative(project, getattr(event, "dest_path", ""))
266
+
267
+ if event.is_directory:
268
+ if from_root:
269
+ self._handle_directory(project, kind, src, dest)
270
+ return
271
+ if src is None and dest is None:
272
+ return
273
+ if kind is ChangeKind.MOVED:
274
+ if src is None and dest is not None: # moved in from outside
275
+ change = translate_file_event(ChangeKind.CREATED, dest)
276
+ elif dest is None and src is not None: # moved out of the repo
277
+ change = translate_file_event(ChangeKind.DELETED, src)
278
+ elif src is not None and dest is not None:
279
+ change = translate_file_event(ChangeKind.MOVED, src, dest)
280
+ else:
281
+ return
282
+ elif src is not None:
283
+ change = translate_file_event(kind, src)
284
+ else:
285
+ return
286
+ if change is not None:
287
+ with self._cond:
288
+ self._buffer.add(project.name, change)
289
+ self._cond.notify()
290
+
291
+ def _handle_directory(
292
+ self,
293
+ project: MonitoredProject,
294
+ kind: ChangeKind,
295
+ src: Path | None,
296
+ dest: Path | None,
297
+ ) -> None:
298
+ requests: list[tuple[_Action, str, Path]] = []
299
+ if kind is ChangeKind.CREATED and src and len(src.parts) == 1:
300
+ requests.append(("attach", project.name, src))
301
+ elif kind is ChangeKind.DELETED and src and len(src.parts) == 1:
302
+ requests.append(("detach", project.name, src))
303
+ elif kind is ChangeKind.MOVED:
304
+ if src and len(src.parts) == 1:
305
+ requests.append(("detach", project.name, src))
306
+ if dest and len(dest.parts) == 1:
307
+ requests.append(("attach", project.name, dest))
308
+ if requests:
309
+ with self._cond:
310
+ self._requests.extend(requests)
311
+ self._cond.notify()
312
+
313
+ @staticmethod
314
+ def _relative(project: MonitoredProject, raw: str | bytes) -> Path | None:
315
+ if not raw:
316
+ return None
317
+ try:
318
+ relative = Path(os.fsdecode(raw)).relative_to(project.repo)
319
+ except ValueError:
320
+ return None
321
+ return relative if relative.parts else None
322
+
323
+ # -- worker thread ---------------------------------------------------
324
+ def _run(self) -> None:
325
+ while True:
326
+ with self._cond:
327
+ while not self._stopping and not self._requests:
328
+ due = self._buffer.next_due_in()
329
+ if due is not None and due <= 0:
330
+ break
331
+ self._cond.wait(timeout=due)
332
+ stopping = self._stopping
333
+ requests, self._requests = self._requests, []
334
+ batches = self._buffer.pop_all() if stopping else self._buffer.pop_due()
335
+ if not stopping:
336
+ for request in requests:
337
+ self._apply_request(*request)
338
+ for batch in batches:
339
+ self._deliver(batch)
340
+ if stopping:
341
+ return
342
+
343
+ def _apply_request(self, action: _Action, name: str, relative: Path) -> None:
344
+ state = self._states.get(name)
345
+ observer = self._observer
346
+ if state is None or observer is None:
347
+ return
348
+ top = relative.parts[0]
349
+ if action == "detach":
350
+ watch = state.dir_watches.pop(top, None)
351
+ if watch is not None:
352
+ observer.unschedule(watch)
353
+ # Unscheduling drops queued file events: report the directory.
354
+ with self._cond:
355
+ self._buffer.add(name, FileChange(ChangeKind.DELETED, Path(top)))
356
+ return
357
+ self._attach(observer, state, top)
358
+
359
+ def _attach(self, observer: BaseObserver, state: _ProjectState, top: str) -> None:
360
+ repo = state.project.repo
361
+ path = repo / top
362
+ if top in state.dir_watches or is_ignored_dir_name(top):
363
+ return
364
+ if path.is_symlink() or not path.is_dir():
365
+ return
366
+ if f"{top}/" in self._ignored(repo, [f"{top}/"]):
367
+ return
368
+ try:
369
+ state.dir_watches[top] = observer.schedule(
370
+ state.handler,
371
+ str(path),
372
+ recursive=True,
373
+ event_filter=_WATCHED_EVENTS,
374
+ )
375
+ except OSError as exc:
376
+ logger.warning("cannot watch new directory %s: %s", path, exc)
377
+ return
378
+ # Files may have been created before the watch existed: report them.
379
+ for current, dirs, files in os.walk(path):
380
+ dirs[:] = [d for d in dirs if not is_ignored_dir_name(d)]
381
+ for filename in files:
382
+ relative = (Path(current) / filename).relative_to(repo)
383
+ change = translate_file_event(ChangeKind.CREATED, relative)
384
+ if change is not None:
385
+ with self._cond:
386
+ self._buffer.add(state.project.name, change)
387
+
388
+ def _deliver(self, batch: PendingBatch) -> None:
389
+ project = self._projects[batch.project]
390
+ paths: set[str] = set()
391
+ for change in batch.changes:
392
+ paths.add(change.path.as_posix())
393
+ if change.dest_path is not None:
394
+ paths.add(change.dest_path.as_posix())
395
+ changes = drop_ignored(batch.changes, self._ignored(project.repo, list(paths)))
396
+ if not changes:
397
+ return
398
+ activity = ProjectActivity(
399
+ project=project.name,
400
+ repo=project.repo,
401
+ changes=changes,
402
+ occurred_at=datetime.fromtimestamp(batch.last_event_wall, UTC),
403
+ )
404
+ try:
405
+ self._on_activity(activity)
406
+ except Exception:
407
+ # The callback is foreign code; never let it kill the monitor.
408
+ logger.exception("activity callback failed for %s", project.name)
@@ -0,0 +1,141 @@
1
+ """Registration and lifecycle management of monitored projects."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+
8
+ from gitgatekeeper.config import (
9
+ AppConfig,
10
+ ConfigError,
11
+ ProjectConfig,
12
+ load_config,
13
+ save_config,
14
+ )
15
+ from gitgatekeeper.git.repository import find_repository_root
16
+
17
+
18
+ class ProjectError(ConfigError):
19
+ """Raised when a project operation is invalid (bad path, duplicate, ...)."""
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class ProjectStatus:
24
+ """Point-in-time health of a registered project."""
25
+
26
+ project: ProjectConfig
27
+ path_exists: bool
28
+ is_repository: bool
29
+ inactivity_minutes: int
30
+ auto_push: bool
31
+
32
+ @property
33
+ def healthy(self) -> bool:
34
+ return self.path_exists and self.is_repository
35
+
36
+ @property
37
+ def state(self) -> str:
38
+ if not self.path_exists:
39
+ return "missing"
40
+ if not self.is_repository:
41
+ return "not a git repository"
42
+ return "enabled" if self.project.enabled else "disabled"
43
+
44
+
45
+ class ProjectManager:
46
+ """CRUD operations over the projects stored in the YAML config."""
47
+
48
+ def __init__(self, config_path: Path) -> None:
49
+ self.config_path = config_path
50
+
51
+ # -- queries ---------------------------------------------------------
52
+ def load(self) -> AppConfig:
53
+ return load_config(self.config_path)
54
+
55
+ def list_projects(self) -> list[ProjectConfig]:
56
+ return list(self.load().projects)
57
+
58
+ def get(self, name: str) -> ProjectConfig:
59
+ return self._find(self.load(), name)
60
+
61
+ def statuses(self) -> list[ProjectStatus]:
62
+ """Inspect every registered project (path and repository validity)."""
63
+ config = self.load()
64
+ return [self._inspect(config, p) for p in config.projects]
65
+
66
+ def status(self, name: str) -> ProjectStatus:
67
+ config = self.load()
68
+ return self._inspect(config, self._find(config, name))
69
+
70
+ # -- mutations -------------------------------------------------------
71
+ def add(self, path: Path, name: str | None = None) -> ProjectConfig:
72
+ """Register the repository containing ``path``.
73
+
74
+ The stored path is always the repository root, resolved and absolute.
75
+ """
76
+ resolved = path.expanduser().resolve()
77
+ if not resolved.exists():
78
+ raise ProjectError(f"path does not exist: {resolved}")
79
+ if not resolved.is_dir():
80
+ raise ProjectError(f"path is not a directory: {resolved}")
81
+
82
+ root = find_repository_root(resolved)
83
+ if root is None:
84
+ raise ProjectError(f"not a Git repository: {resolved}")
85
+
86
+ config = self.load()
87
+ for existing in config.projects:
88
+ if existing.path == root:
89
+ raise ProjectError(
90
+ f"repository already registered as {existing.name!r}: {root}"
91
+ )
92
+
93
+ project_name = (name or root.name).strip()
94
+ if not project_name:
95
+ raise ProjectError("project name must not be blank")
96
+ if any(p.name.casefold() == project_name.casefold() for p in config.projects):
97
+ raise ProjectError(
98
+ f"a project named {project_name!r} already exists; "
99
+ "choose another with --name"
100
+ )
101
+
102
+ project = ProjectConfig(name=project_name, path=root)
103
+ config.projects.append(project)
104
+ save_config(config, self.config_path)
105
+ return project
106
+
107
+ def remove(self, name: str) -> ProjectConfig:
108
+ """Unregister a project. Never touches the repository itself."""
109
+ config = self.load()
110
+ project = self._find(config, name)
111
+ config.projects = [p for p in config.projects if p is not project]
112
+ save_config(config, self.config_path)
113
+ return project
114
+
115
+ def set_enabled(self, name: str, enabled: bool) -> ProjectConfig:
116
+ config = self.load()
117
+ project = self._find(config, name)
118
+ project.enabled = enabled
119
+ save_config(config, self.config_path)
120
+ return project
121
+
122
+ # -- internals -------------------------------------------------------
123
+ @staticmethod
124
+ def _find(config: AppConfig, name: str) -> ProjectConfig:
125
+ wanted = name.strip().casefold()
126
+ for project in config.projects:
127
+ if project.name.casefold() == wanted:
128
+ return project
129
+ raise ProjectError(f"unknown project: {name!r}")
130
+
131
+ @staticmethod
132
+ def _inspect(config: AppConfig, project: ProjectConfig) -> ProjectStatus:
133
+ exists = project.path.is_dir()
134
+ is_repo = exists and find_repository_root(project.path) is not None
135
+ return ProjectStatus(
136
+ project=project,
137
+ path_exists=exists,
138
+ is_repository=is_repo,
139
+ inactivity_minutes=config.effective_inactivity_minutes(project),
140
+ auto_push=config.effective_auto_push(project),
141
+ )