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,441 @@
1
+ """Push Engine: sends the current branch to its configured upstream, safely.
2
+
3
+ What it guarantees:
4
+
5
+ * **No forced updates, ever.** The refspec is built here as ``<commit>:<ref>``
6
+ with no ``+``, so a configured ``remote.*.push = +refs/...`` cannot turn it
7
+ into a force push, and the remote simply refuses anything that is not a
8
+ fast-forward. There is no ``--force`` or ``--force-with-lease`` anywhere.
9
+ * **Your remote setup is respected, never changed.** It pushes to the upstream
10
+ the branch already has. It does not set one (``push -u``), add remotes or
11
+ touch credentials or any other configuration.
12
+ * **No prompts.** The process has no terminal and no stdin, and askpass helpers
13
+ are disabled, so a missing credential is a failed push, not a hung service.
14
+ Credential helpers you already configured still work.
15
+ * **Local work is never touched.** A failed push leaves every local commit and
16
+ file exactly as it was; the next cycle simply tries again.
17
+ * **Secrets stay out of logs.** Credentials embedded in remote URLs are masked
18
+ in every message.
19
+
20
+ Which commits may be pushed is the caller's policy: ``owns_commit`` lets the
21
+ orchestrator refuse to publish commits GitGatekeeper did not create.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import logging
27
+ import re
28
+ from collections.abc import Callable
29
+ from dataclasses import dataclass
30
+ from enum import StrEnum
31
+ from pathlib import Path
32
+
33
+ from gitgatekeeper.core.locking import LockHeldError, RepositoryLock
34
+ from gitgatekeeper.git.analyzer import analyze_repository
35
+ from gitgatekeeper.git.repository import GitError, find_repository_root, run_git
36
+
37
+ logger = logging.getLogger(__name__)
38
+
39
+ PUSH_TIMEOUT_SECONDS = 120.0
40
+ GIT_QUERY_TIMEOUT_SECONDS = 15.0
41
+ MAX_COMMITS_LISTED = 500
42
+ _DETAIL_LIMIT = 500
43
+
44
+ # Disable every non-terminal way a credential prompt could appear.
45
+ _NO_PROMPT_ENV = {
46
+ "GIT_ASKPASS": "",
47
+ "SSH_ASKPASS": "",
48
+ "SSH_ASKPASS_REQUIRE": "never",
49
+ "GCM_INTERACTIVE": "never",
50
+ }
51
+
52
+ NO_PROMPT_ENV = (
53
+ _NO_PROMPT_ENV # public alias for read-only probes (gitgatekeeper check)
54
+ )
55
+
56
+ _URL_CREDENTIALS = re.compile(r"(?i)\b([a-z][a-z0-9+.-]*://)[^/\s@'\"]+@")
57
+
58
+
59
+ class PushOutcome(StrEnum):
60
+ PUSHED = "pushed"
61
+ NOTHING_TO_PUSH = "nothing-to-push"
62
+ SKIPPED = "skipped"
63
+ FAILED = "failed"
64
+
65
+
66
+ class PushReason(StrEnum):
67
+ NO_UPSTREAM = "no-upstream"
68
+ BEHIND = "behind-upstream"
69
+ BLOCKED = "blocked"
70
+ LOCKED = "locked"
71
+ FOREIGN_COMMITS = "foreign-commits"
72
+ PROTECTED_BRANCH = "protected-branch"
73
+ UNPUBLISHED_SUBMODULE = "unpublished-submodule"
74
+ REJECTED = "rejected"
75
+ AUTH_FAILED = "auth-failed"
76
+ NETWORK = "network"
77
+ TIMEOUT = "timeout"
78
+ GIT_FAILED = "git-failed"
79
+
80
+
81
+ @dataclass(frozen=True, slots=True)
82
+ class PushResult:
83
+ outcome: PushOutcome
84
+ repo: Path
85
+ reason: PushReason | None = None
86
+ detail: str = ""
87
+ branch: str | None = None
88
+ remote: str | None = None
89
+ remote_ref: str | None = None # e.g. "refs/heads/main"
90
+ head: str | None = None # the commit that was (or would have been) pushed
91
+ commits: tuple[str, ...] = () # commits sent, newest first
92
+ warnings: tuple[str, ...] = ()
93
+
94
+ @property
95
+ def pushed(self) -> bool:
96
+ return self.outcome is PushOutcome.PUSHED
97
+
98
+
99
+ def mask_url_credentials(text: str) -> str:
100
+ """Replace ``user:token@`` in any URL inside ``text`` with ``***@``."""
101
+ return _URL_CREDENTIALS.sub(r"\1***@", text)
102
+
103
+
104
+ def redact(text: str) -> str:
105
+ """Mask URL credentials and shorten the text for results and logs."""
106
+ text = mask_url_credentials(text.strip())
107
+ return text if len(text) <= _DETAIL_LIMIT else "..." + text[-_DETAIL_LIMIT:]
108
+
109
+
110
+ _AUTH_HINTS = (
111
+ "permission denied",
112
+ "authentication failed",
113
+ "could not read username",
114
+ "could not read password",
115
+ "terminal prompts disabled",
116
+ "host key verification failed",
117
+ "invalid credentials",
118
+ "access denied",
119
+ "returned error: 401",
120
+ "returned error: 403",
121
+ "repository not found",
122
+ )
123
+ _NETWORK_HINTS = (
124
+ "could not resolve host",
125
+ "connection refused",
126
+ "connection timed out",
127
+ "connection reset",
128
+ "network is unreachable",
129
+ "operation timed out",
130
+ "failed to connect",
131
+ "unable to access",
132
+ "early eof",
133
+ "the remote end hung up",
134
+ "temporary failure in name resolution",
135
+ )
136
+ _REJECTED_HINTS = (
137
+ "rejected",
138
+ "non-fast-forward",
139
+ "fetch first",
140
+ "declined",
141
+ "protected branch",
142
+ "failed to push some refs",
143
+ )
144
+
145
+
146
+ def classify_failure(output: str) -> PushReason:
147
+ """Map Git's error text to a reason (auth, network, rejection or other)."""
148
+ text = output.lower()
149
+ if "submodule paths contain changes" in text: # also says "hung up": check first
150
+ return PushReason.UNPUBLISHED_SUBMODULE
151
+ if any(hint in text for hint in _AUTH_HINTS):
152
+ return PushReason.AUTH_FAILED
153
+ if any(hint in text for hint in _NETWORK_HINTS):
154
+ return PushReason.NETWORK
155
+ if any(hint in text for hint in _REJECTED_HINTS):
156
+ return PushReason.REJECTED
157
+ return PushReason.GIT_FAILED
158
+
159
+
160
+ class PushEngine:
161
+ def __init__(
162
+ self,
163
+ *,
164
+ lock_dir: Path,
165
+ owns_commit: Callable[[str], bool] | None = None,
166
+ is_protected: Callable[[Path, str], bool] | None = None,
167
+ timeout: float = PUSH_TIMEOUT_SECONDS,
168
+ ) -> None:
169
+ """
170
+ ``owns_commit(oid)`` tells whether GitGatekeeper created a commit. When given,
171
+ a push is refused if any commit about to be published is not owned, so
172
+ the user's own unpublished work is never sent as a side effect. When
173
+ ``None`` every commit ahead of the upstream is pushed.
174
+ """
175
+ if timeout <= 0:
176
+ raise ValueError("timeout must be positive")
177
+ self._lock_dir = lock_dir
178
+ self._owns_commit = owns_commit
179
+ self._is_protected = is_protected
180
+ self._timeout = timeout
181
+
182
+ def run(self, repo: Path) -> PushResult:
183
+ """Run one push cycle for ``repo``. Never raises for Git problems."""
184
+ try:
185
+ root = find_repository_root(repo)
186
+ if root is None:
187
+ return PushResult(
188
+ PushOutcome.FAILED,
189
+ repo,
190
+ PushReason.GIT_FAILED,
191
+ f"not a Git repository: {repo}",
192
+ )
193
+ try:
194
+ with RepositoryLock(self._lock_dir, root, purpose="push"):
195
+ return self._cycle(root)
196
+ except LockHeldError as exc:
197
+ return PushResult(
198
+ PushOutcome.SKIPPED, root, PushReason.LOCKED, str(exc)
199
+ )
200
+ except (GitError, OSError) as exc:
201
+ logger.error("push cycle failed for %s: %s", repo, redact(str(exc)))
202
+ return PushResult(
203
+ PushOutcome.FAILED, repo, PushReason.GIT_FAILED, redact(str(exc))
204
+ )
205
+
206
+ # -- the cycle -------------------------------------------------------------
207
+ def _cycle(self, root: Path) -> PushResult:
208
+ snapshot = analyze_repository(root)
209
+ branch = snapshot.branch
210
+
211
+ # Operations in progress and a detached HEAD mean the history is in flux.
212
+ # A stuck index.lock is irrelevant here: pushing never touches the index.
213
+ blockers = [f"{op.value} in progress" for op in snapshot.operations]
214
+ if branch.detached:
215
+ blockers.append("HEAD is detached")
216
+ if blockers:
217
+ return self._skip(root, PushReason.BLOCKED, "; ".join(blockers))
218
+
219
+ if branch.unborn or branch.oid is None or branch.name is None:
220
+ return PushResult(
221
+ PushOutcome.NOTHING_TO_PUSH, root, detail="no commits yet"
222
+ )
223
+
224
+ target = self._upstream_target(root, branch.name)
225
+ if isinstance(target, str):
226
+ return self._skip(root, PushReason.NO_UPSTREAM, target, branch.name)
227
+ remote, remote_ref = target
228
+
229
+ if self._is_protected is not None:
230
+ published = remote_ref.removeprefix("refs/heads/")
231
+ for name in (branch.name, published):
232
+ if self._is_protected(root, name):
233
+ return self._skip(
234
+ root,
235
+ PushReason.PROTECTED_BRANCH,
236
+ f"branch {name!r} is protected; "
237
+ "GitGatekeeper never pushes to it",
238
+ branch.name,
239
+ remote,
240
+ remote_ref,
241
+ )
242
+
243
+ if branch.ahead is None:
244
+ return self._skip(
245
+ root,
246
+ PushReason.NO_UPSTREAM,
247
+ "the upstream branch does not exist locally (never fetched or gone)",
248
+ branch.name,
249
+ remote,
250
+ remote_ref,
251
+ )
252
+ if branch.ahead == 0:
253
+ return PushResult(
254
+ PushOutcome.NOTHING_TO_PUSH,
255
+ root,
256
+ branch=branch.name,
257
+ remote=remote,
258
+ remote_ref=remote_ref,
259
+ head=branch.oid,
260
+ )
261
+
262
+ if branch.behind:
263
+ return self._skip(
264
+ root,
265
+ PushReason.BEHIND,
266
+ f"local branch is {branch.behind} commit(s) behind {branch.upstream} "
267
+ "(as of the last fetch); integrate them before pushing",
268
+ branch.name,
269
+ remote,
270
+ remote_ref,
271
+ )
272
+ commits = self._commits_ahead(root, branch.oid)
273
+ if self._owns_commit is not None:
274
+ foreign = [c for c in commits if not self._owns_commit(c)]
275
+ if foreign:
276
+ return self._skip(
277
+ root,
278
+ PushReason.FOREIGN_COMMITS,
279
+ f"{len(foreign)} unpushed commit(s) were not created by "
280
+ "GitGatekeeper "
281
+ f"(first: {foreign[0][:12]}); push them yourself",
282
+ branch.name,
283
+ remote,
284
+ remote_ref,
285
+ )
286
+ return self._push(root, branch.name, branch.oid, remote, remote_ref, commits)
287
+
288
+ def _push(
289
+ self,
290
+ root: Path,
291
+ branch: str,
292
+ oid: str,
293
+ remote: str,
294
+ remote_ref: str,
295
+ commits: tuple[str, ...],
296
+ ) -> PushResult:
297
+ def result(
298
+ outcome: PushOutcome,
299
+ reason: PushReason | None = None,
300
+ detail: str = "",
301
+ warnings: tuple[str, ...] = (),
302
+ ) -> PushResult:
303
+ return PushResult(
304
+ outcome,
305
+ root,
306
+ reason,
307
+ detail,
308
+ branch,
309
+ remote,
310
+ remote_ref,
311
+ oid,
312
+ commits if outcome is PushOutcome.PUSHED else (),
313
+ warnings,
314
+ )
315
+
316
+ # An exact commit and a refspec without "+": never a forced update, and
317
+ # the commit pushed is the one that was checked, even if HEAD moves.
318
+ # recurseSubmodules=check never publishes a submodule's own work (that is
319
+ # not GitGatekeeper's to send) and refuses a commit that points at one that
320
+ # was never published; a user-configured "on-demand" is overridden.
321
+ args = [
322
+ "-c",
323
+ "push.recurseSubmodules=check",
324
+ "push",
325
+ "--no-follow-tags",
326
+ remote,
327
+ f"{oid}:{remote_ref}",
328
+ ]
329
+ try:
330
+ done = run_git(
331
+ args,
332
+ cwd=root,
333
+ input_text="",
334
+ timeout=self._timeout,
335
+ new_session=True,
336
+ extra_env=_NO_PROMPT_ENV,
337
+ )
338
+ except GitError as exc:
339
+ detail = redact(str(exc))
340
+ logger.warning("push timed out or could not run in %s: %s", root, detail)
341
+ timed_out = "timed out" in detail
342
+ return result(
343
+ PushOutcome.FAILED,
344
+ PushReason.TIMEOUT if timed_out else PushReason.GIT_FAILED,
345
+ detail,
346
+ )
347
+
348
+ if done.returncode != 0:
349
+ output = redact(done.stderr or done.stdout)
350
+ reason = classify_failure(output)
351
+ logger.warning(
352
+ "push failed repo=%s remote=%s reason=%s: %s",
353
+ root,
354
+ remote,
355
+ reason.value,
356
+ output,
357
+ )
358
+ return result(PushOutcome.FAILED, reason, output)
359
+
360
+ warnings: list[str] = []
361
+ if self._tracking_oid(root, branch) != oid:
362
+ warnings.append(
363
+ "the remote-tracking branch does not point at the pushed commit"
364
+ )
365
+ logger.info(
366
+ "push done repo=%s remote=%s ref=%s commits=%d",
367
+ root,
368
+ remote,
369
+ remote_ref,
370
+ len(commits),
371
+ )
372
+ return result(PushOutcome.PUSHED, warnings=tuple(warnings))
373
+
374
+ # -- git helpers -----------------------------------------------------------
375
+ @staticmethod
376
+ def _skip(
377
+ root: Path,
378
+ reason: PushReason,
379
+ detail: str,
380
+ branch: str | None = None,
381
+ remote: str | None = None,
382
+ remote_ref: str | None = None,
383
+ ) -> PushResult:
384
+ logger.warning(
385
+ "push skipped repo=%s reason=%s detail=%s", root, reason.value, detail
386
+ )
387
+ return PushResult(
388
+ PushOutcome.SKIPPED,
389
+ root,
390
+ reason,
391
+ detail,
392
+ branch=branch,
393
+ remote=remote,
394
+ remote_ref=remote_ref,
395
+ )
396
+
397
+ @staticmethod
398
+ def _config(root: Path, key: str) -> str | None:
399
+ result = run_git(
400
+ ["config", "--get", key], cwd=root, timeout=GIT_QUERY_TIMEOUT_SECONDS
401
+ )
402
+ value = result.stdout.strip()
403
+ return value if result.returncode == 0 and value else None
404
+
405
+ def _upstream_target(self, root: Path, branch: str) -> tuple[str, str] | str:
406
+ """The configured ``(remote, ref)`` of ``branch``, or why there is none."""
407
+ remote = self._config(root, f"branch.{branch}.remote")
408
+ merge = self._config(root, f"branch.{branch}.merge")
409
+ if remote is None or merge is None:
410
+ return f"branch {branch!r} has no upstream configured"
411
+ if remote == ".":
412
+ return f"the upstream of {branch!r} is a local branch, not a remote"
413
+ if not merge.startswith("refs/heads/"):
414
+ return f"unsupported upstream ref {merge!r}"
415
+ return remote, merge
416
+
417
+ @staticmethod
418
+ def _commits_ahead(root: Path, oid: str) -> tuple[str, ...]:
419
+ result = run_git(
420
+ [
421
+ "rev-list",
422
+ f"--max-count={MAX_COMMITS_LISTED}",
423
+ oid,
424
+ "--not",
425
+ "@{upstream}",
426
+ ],
427
+ cwd=root,
428
+ timeout=GIT_QUERY_TIMEOUT_SECONDS,
429
+ )
430
+ if result.returncode != 0:
431
+ raise GitError(f"git rev-list failed: {redact(result.stderr)}")
432
+ return tuple(result.stdout.split())
433
+
434
+ @staticmethod
435
+ def _tracking_oid(root: Path, branch: str) -> str | None:
436
+ result = run_git(
437
+ ["rev-parse", "--verify", "--quiet", f"{branch}@{{upstream}}"],
438
+ cwd=root,
439
+ timeout=GIT_QUERY_TIMEOUT_SECONDS,
440
+ )
441
+ return result.stdout.strip() or None if result.returncode == 0 else None