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,223 @@
1
+ """Install GitGatekeeper as a systemd *user* service.
2
+
3
+ Only files under the user's own config directory are written, and only the
4
+ user's own ``systemctl --user`` is called. Nothing system-wide is touched, and
5
+ ``loginctl enable-linger`` is never run.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import shutil
12
+ import subprocess
13
+ import sys
14
+ from collections.abc import Callable, Sequence
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+
18
+ UNIT_NAME = "gitgatekeeper.service"
19
+ Runner = Callable[[Sequence[str]], "subprocess.CompletedProcess[str]"]
20
+
21
+ # Sockets of the SSH agents desktops use, relative to $XDG_RUNTIME_DIR.
22
+ _SSH_SOCKETS = ("gcr/ssh", "keyring/ssh", "ssh-agent.socket")
23
+
24
+
25
+ class SystemdError(Exception):
26
+ """Raised when the service cannot be installed, removed or queried."""
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class UnitStatus:
31
+ installed: bool
32
+ enabled: str
33
+ active: str
34
+ path: Path
35
+
36
+
37
+ def unit_dir(env: dict[str, str] | None = None) -> Path:
38
+ environ = os.environ if env is None else env
39
+ base = environ.get("XDG_CONFIG_HOME")
40
+ root = Path(base).expanduser() if base else Path.home() / ".config"
41
+ return root / "systemd" / "user"
42
+
43
+
44
+ def unit_path(env: dict[str, str] | None = None) -> Path:
45
+ return unit_dir(env) / UNIT_NAME
46
+
47
+
48
+ def find_executable() -> Path:
49
+ """Absolute path of the ``gitgatekeeper`` command that is running now."""
50
+ candidates = [Path(sys.argv[0]), Path(sys.executable).parent / "gitgatekeeper"]
51
+ found = shutil.which("gitgatekeeper")
52
+ if found:
53
+ candidates.append(Path(found))
54
+ for candidate in candidates:
55
+ if candidate.name == "gitgatekeeper" and candidate.is_file():
56
+ return candidate.absolute()
57
+ raise SystemdError(
58
+ "cannot find the gitgatekeeper executable; run this from the environment "
59
+ "where GitGatekeeper is installed"
60
+ )
61
+
62
+
63
+ def quote(value: str) -> str:
64
+ """Quote one ExecStart argument following systemd.syntax rules."""
65
+ escaped = (
66
+ value.replace("\\", "\\\\")
67
+ .replace('"', '\\"')
68
+ .replace("%", "%%")
69
+ .replace("$", "$$")
70
+ )
71
+ return f'"{escaped}"'
72
+
73
+
74
+ def ssh_socket(runtime_dir: Path | None = None) -> Path | None:
75
+ """The desktop's SSH agent socket, if one is there."""
76
+ if runtime_dir is None:
77
+ value = os.environ.get("XDG_RUNTIME_DIR")
78
+ if not value:
79
+ return None
80
+ runtime_dir = Path(value)
81
+ for relative in _SSH_SOCKETS:
82
+ candidate = runtime_dir / relative
83
+ if candidate.is_socket():
84
+ return candidate
85
+ return None
86
+
87
+
88
+ def render_unit(
89
+ executable: Path,
90
+ config: Path,
91
+ *,
92
+ state_dir: Path | None = None,
93
+ ssh_auth_sock: Path | None = None,
94
+ ) -> str:
95
+ """Text of the unit file. All paths must be absolute."""
96
+ for path in (executable, config, *([state_dir] if state_dir else [])):
97
+ if not path.is_absolute():
98
+ raise SystemdError(f"path must be absolute: {path}")
99
+ args = [str(executable), "start", "--config", str(config)]
100
+ if state_dir is not None:
101
+ args += ["--state-dir", str(state_dir)]
102
+ exec_start = " ".join(quote(arg) for arg in args)
103
+ lines = [
104
+ "# Written by `gitgatekeeper service install`. Remove it with",
105
+ "# `gitgatekeeper service uninstall`.",
106
+ "[Unit]",
107
+ "Description=GitGatekeeper - Git automation agent",
108
+ "Documentation=https://github.com/robertofilho0/GitGatekeeper",
109
+ "After=default.target",
110
+ "",
111
+ "[Service]",
112
+ "Type=simple",
113
+ f"ExecStart={exec_start}",
114
+ "Restart=on-failure",
115
+ "RestartSec=10",
116
+ "# GitGatekeeper finishes the cycle in progress on SIGTERM.",
117
+ "TimeoutStopSec=60",
118
+ "Environment=PYTHONUNBUFFERED=1",
119
+ ]
120
+ if ssh_auth_sock is not None:
121
+ lines.append(f"Environment={quote(f'SSH_AUTH_SOCK={ssh_auth_sock}')}")
122
+ lines += [
123
+ "NoNewPrivileges=true",
124
+ "RestrictSUIDSGID=true",
125
+ "LockPersonality=true",
126
+ "",
127
+ "[Install]",
128
+ "WantedBy=default.target",
129
+ "",
130
+ ]
131
+ return "\n".join(lines)
132
+
133
+
134
+ def _run(command: Sequence[str]) -> subprocess.CompletedProcess[str]:
135
+ try:
136
+ return subprocess.run(
137
+ list(command),
138
+ capture_output=True,
139
+ text=True,
140
+ timeout=30,
141
+ check=False,
142
+ )
143
+ except FileNotFoundError as exc:
144
+ raise SystemdError("systemctl not found: systemd is not available") from exc
145
+ except subprocess.TimeoutExpired as exc:
146
+ raise SystemdError(f"{' '.join(command)} timed out") from exc
147
+
148
+
149
+ def _systemctl(run: Runner, *args: str) -> subprocess.CompletedProcess[str]:
150
+ return run(["systemctl", "--user", *args])
151
+
152
+
153
+ def _require_user_manager(run: Runner) -> None:
154
+ result = _systemctl(run, "show-environment")
155
+ if result.returncode != 0:
156
+ detail = (result.stderr or result.stdout).strip()
157
+ raise SystemdError(
158
+ "systemd user manager is not reachable"
159
+ + (f": {detail}" if detail else "")
160
+ + ". Log in through a normal desktop or SSH session and try again."
161
+ )
162
+
163
+
164
+ def install(
165
+ unit_text: str,
166
+ *,
167
+ path: Path | None = None,
168
+ start: bool = True,
169
+ force: bool = False,
170
+ run: Runner | None = None,
171
+ ) -> Path:
172
+ """Write the unit, then enable it (and start it unless ``start`` is false)."""
173
+ target = path or unit_path()
174
+ run = run or _run
175
+ _require_user_manager(run)
176
+ if target.exists() and not force:
177
+ if target.read_text(encoding="utf-8", errors="replace") != unit_text:
178
+ raise SystemdError(
179
+ f"{target} already exists and differs; use --force to replace it"
180
+ )
181
+ try:
182
+ target.parent.mkdir(parents=True, exist_ok=True)
183
+ target.write_text(unit_text, encoding="utf-8")
184
+ except OSError as exc:
185
+ raise SystemdError(f"cannot write {target}: {exc}") from exc
186
+ _check(_systemctl(run, "daemon-reload"), "daemon-reload")
187
+ verb = ("enable", "--now") if start else ("enable",)
188
+ _check(_systemctl(run, *verb, UNIT_NAME), f"enable {UNIT_NAME}")
189
+ return target
190
+
191
+
192
+ def uninstall(*, path: Path | None = None, run: Runner | None = None) -> bool:
193
+ """Stop, disable and delete the unit. Returns False if it was not installed."""
194
+ target = path or unit_path()
195
+ if not target.exists():
196
+ return False
197
+ run = run or _run
198
+ _require_user_manager(run)
199
+ # A unit that is already stopped or disabled is not an error here.
200
+ _systemctl(run, "disable", "--now", UNIT_NAME)
201
+ try:
202
+ target.unlink()
203
+ except OSError as exc:
204
+ raise SystemdError(f"cannot remove {target}: {exc}") from exc
205
+ _check(_systemctl(run, "daemon-reload"), "daemon-reload")
206
+ return True
207
+
208
+
209
+ def unit_status(*, path: Path | None = None, run: Runner | None = None) -> UnitStatus:
210
+ target = path or unit_path()
211
+ if not target.exists():
212
+ return UnitStatus(False, "-", "-", target)
213
+ run = run or _run
214
+ _require_user_manager(run)
215
+ enabled = _systemctl(run, "is-enabled", UNIT_NAME).stdout.strip() or "unknown"
216
+ active = _systemctl(run, "is-active", UNIT_NAME).stdout.strip() or "unknown"
217
+ return UnitStatus(True, enabled, active, target)
218
+
219
+
220
+ def _check(result: subprocess.CompletedProcess[str], what: str) -> None:
221
+ if result.returncode != 0:
222
+ detail = (result.stderr or result.stdout).strip()
223
+ raise SystemdError(f"systemctl --user {what} failed: {detail}")
@@ -0,0 +1,104 @@
1
+ """Take back the last commit GitGatekeeper made, without losing any work.
2
+
3
+ ``undo`` runs ``git reset --mixed <parent>``: the commit leaves the branch, the
4
+ index goes back to the parent and **no file in the working tree is touched**.
5
+ It never rewrites anything a remote has seen and never uses ``--hard``.
6
+
7
+ It refuses, with the reason, whenever the reset could surprise the user: the
8
+ commit is not the tip of the branch, it was already pushed, something the user
9
+ staged would be dropped, or a merge, rebase or similar operation is under way.
10
+ The undone commit stays in the reflog, so ``git reset <oid>`` puts it back.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+
18
+ from gitgatekeeper.core.locking import LockHeldError, RepositoryLock
19
+ from gitgatekeeper.git import GitError, detect_operations, find_repository_root, run_git
20
+
21
+
22
+ class UndoError(Exception):
23
+ """The commit cannot be undone safely; the message says why."""
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class UndoResult:
28
+ oid: str
29
+ parent: str
30
+
31
+
32
+ def undo_commit(repo: Path, oid: str, *, lock_dir: Path) -> UndoResult:
33
+ """Undo commit ``oid``, which must be the tip of the checked-out branch."""
34
+ try:
35
+ root = find_repository_root(repo) if repo.is_dir() else None
36
+ except GitError as exc:
37
+ raise UndoError(str(exc)) from exc
38
+ if root is None:
39
+ raise UndoError(f"{repo} is not a Git repository (or no longer exists)")
40
+ try:
41
+ with RepositoryLock(lock_dir, root):
42
+ return _undo(root, oid)
43
+ except LockHeldError:
44
+ raise UndoError(
45
+ "a commit cycle is running for this repository; try again in a moment"
46
+ ) from None
47
+ except GitError as exc:
48
+ raise UndoError(str(exc)) from exc
49
+
50
+
51
+ def _git(root: Path, *args: str) -> str:
52
+ result = run_git(list(args), cwd=root)
53
+ if result.returncode != 0:
54
+ raise UndoError(f"git {' '.join(args)} failed: {result.stderr.strip()}")
55
+ return result.stdout.strip()
56
+
57
+
58
+ def _undo(root: Path, oid: str) -> UndoResult:
59
+ git_dir = Path(_git(root, "rev-parse", "--absolute-git-dir"))
60
+ operations = detect_operations(git_dir)
61
+ if operations:
62
+ names = ", ".join(op.value for op in operations)
63
+ raise UndoError(f"a {names} is in progress; finish or abort it first")
64
+ if (git_dir / "index.lock").exists():
65
+ raise UndoError("another Git command is running here (index.lock exists)")
66
+
67
+ head = run_git(["rev-parse", "--verify", "--quiet", "HEAD"], cwd=root)
68
+ if head.returncode != 0 or head.stdout.strip() != oid:
69
+ raise UndoError(
70
+ f"{oid[:8]} is no longer the latest commit of the current branch; "
71
+ "newer commits sit on top of it, so undo them first with Git"
72
+ )
73
+ if (
74
+ run_git(["rev-parse", "--verify", "--quiet", f"{oid}^2"], cwd=root).returncode
75
+ == 0
76
+ ):
77
+ raise UndoError("that is a merge commit; undo it with Git yourself")
78
+ parent = run_git(["rev-parse", "--verify", "--quiet", f"{oid}^1"], cwd=root)
79
+ if parent.returncode != 0:
80
+ raise UndoError(
81
+ "that is the first commit of the repository; nothing to go back to"
82
+ )
83
+ parent_oid = parent.stdout.strip()
84
+
85
+ staged = run_git(["diff", "--cached", "--quiet"], cwd=root)
86
+ if staged.returncode == 1:
87
+ raise UndoError(
88
+ "you have staged changes; commit or unstage them first so undo cannot "
89
+ "drop them"
90
+ )
91
+ if staged.returncode != 0:
92
+ raise UndoError(f"cannot inspect the index: {staged.stderr.strip()}")
93
+
94
+ remote = run_git(["branch", "--remotes", "--contains", oid], cwd=root)
95
+ if remote.returncode != 0:
96
+ raise UndoError(f"cannot tell whether it was pushed: {remote.stderr.strip()}")
97
+ if remote.stdout.strip():
98
+ raise UndoError(
99
+ "that commit is already on a remote branch; GitGatekeeper never rewrites "
100
+ f"published history. To take it back use `git revert {oid[:8]}`"
101
+ )
102
+
103
+ _git(root, "reset", "--quiet", "--mixed", parent_oid)
104
+ return UndoResult(oid=oid, parent=parent_oid)
@@ -0,0 +1,43 @@
1
+ """Git CLI integration."""
2
+
3
+ from gitgatekeeper.git.analyzer import analyze_repository, detect_operations
4
+ from gitgatekeeper.git.diff import DiffSummary, FileDiff, read_staged_diff
5
+ from gitgatekeeper.git.ignore import find_ignored
6
+ from gitgatekeeper.git.models import (
7
+ BranchInfo,
8
+ ChangeType,
9
+ FileStatus,
10
+ Operation,
11
+ RepositorySnapshot,
12
+ )
13
+ from gitgatekeeper.git.repository import (
14
+ GitError,
15
+ find_repository_root,
16
+ is_git_repository,
17
+ run_git,
18
+ )
19
+ from gitgatekeeper.git.secrets import SecretFinding, scan_lines
20
+ from gitgatekeeper.git.sensitive import is_sensitive_path
21
+ from gitgatekeeper.git.status_parser import parse_status
22
+
23
+ __all__ = [
24
+ "BranchInfo",
25
+ "ChangeType",
26
+ "DiffSummary",
27
+ "FileDiff",
28
+ "FileStatus",
29
+ "GitError",
30
+ "Operation",
31
+ "RepositorySnapshot",
32
+ "SecretFinding",
33
+ "analyze_repository",
34
+ "detect_operations",
35
+ "find_ignored",
36
+ "find_repository_root",
37
+ "is_git_repository",
38
+ "is_sensitive_path",
39
+ "parse_status",
40
+ "read_staged_diff",
41
+ "run_git",
42
+ "scan_lines",
43
+ ]
@@ -0,0 +1,96 @@
1
+ """Read-only analysis of a repository's current state.
2
+
3
+ Nothing here writes to the repository: it only runs ``git status`` and
4
+ ``git rev-parse`` and looks for marker files in the Git directory.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from pathlib import Path
10
+
11
+ from gitgatekeeper.git.models import Operation, RepositorySnapshot
12
+ from gitgatekeeper.git.repository import GitError, find_repository_root, run_git
13
+ from gitgatekeeper.git.status_parser import parse_status
14
+
15
+ # Large repositories on a cold disk cache can take a while to stat.
16
+ STATUS_TIMEOUT_SECONDS = 30.0
17
+
18
+
19
+ def detect_operations(git_dir: Path) -> tuple[Operation, ...]:
20
+ """Detect multi-step operations in progress from marker files in ``git_dir``."""
21
+ found: set[Operation] = set()
22
+
23
+ if (git_dir / "MERGE_HEAD").exists():
24
+ found.add(Operation.MERGE)
25
+ if (git_dir / "rebase-merge").is_dir():
26
+ found.add(Operation.REBASE)
27
+ if (git_dir / "rebase-apply").is_dir():
28
+ if (git_dir / "rebase-apply" / "applying").exists():
29
+ found.add(Operation.APPLY_MAILBOX)
30
+ else:
31
+ found.add(Operation.REBASE)
32
+ if (git_dir / "CHERRY_PICK_HEAD").exists():
33
+ found.add(Operation.CHERRY_PICK)
34
+ if (git_dir / "REVERT_HEAD").exists():
35
+ found.add(Operation.REVERT)
36
+ if (git_dir / "BISECT_LOG").exists():
37
+ found.add(Operation.BISECT)
38
+ if (git_dir / "sequencer").is_dir():
39
+ # A multi-commit cherry-pick/revert between two steps leaves only this.
40
+ found.add(_sequencer_operation(git_dir / "sequencer" / "todo"))
41
+
42
+ return tuple(op for op in Operation if op in found)
43
+
44
+
45
+ def _sequencer_operation(todo: Path) -> Operation:
46
+ try:
47
+ text = todo.read_text(encoding="utf-8", errors="replace")
48
+ except OSError:
49
+ return Operation.CHERRY_PICK # unknown: either way, it blocks commits
50
+ for line in text.splitlines():
51
+ line = line.strip()
52
+ if line and not line.startswith("#"):
53
+ first = line.split()[0]
54
+ return (
55
+ Operation.REVERT if first in {"revert", "r"} else Operation.CHERRY_PICK
56
+ )
57
+ return Operation.CHERRY_PICK
58
+
59
+
60
+ def analyze_repository(repo: Path) -> RepositorySnapshot:
61
+ """Return a snapshot of the repository containing ``repo``.
62
+
63
+ Raises :class:`GitError` if ``repo`` is not a usable work tree or Git fails.
64
+ """
65
+ root = find_repository_root(repo)
66
+ if root is None:
67
+ raise GitError(f"not a Git repository: {repo}")
68
+
69
+ git_dir = _absolute_git_dir(root)
70
+ status = run_git(
71
+ ["status", "--porcelain=v2", "--branch", "-z", "--untracked-files=all"],
72
+ cwd=root,
73
+ timeout=STATUS_TIMEOUT_SECONDS,
74
+ )
75
+ if status.returncode != 0:
76
+ raise GitError(
77
+ f"git status failed in {root} (exit {status.returncode}): "
78
+ f"{status.stderr.strip()}"
79
+ )
80
+ branch, files = parse_status(status.stdout)
81
+ return RepositorySnapshot(
82
+ root=root,
83
+ branch=branch,
84
+ files=files,
85
+ operations=detect_operations(git_dir),
86
+ index_locked=(git_dir / "index.lock").exists(),
87
+ )
88
+
89
+
90
+ def _absolute_git_dir(root: Path) -> Path:
91
+ result = run_git(["rev-parse", "--absolute-git-dir"], cwd=root)
92
+ if result.returncode != 0:
93
+ raise GitError(
94
+ f"cannot locate the Git directory of {root}: {result.stderr.strip()}"
95
+ )
96
+ return Path(result.stdout.strip())