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,154 @@
1
+ """Threaded inactivity detector.
2
+
3
+ Wraps :class:`InactivityTracker` with a worker thread that sleeps until the
4
+ next project becomes eligible, then runs ``on_eligible(project)`` on a small
5
+ thread pool. Different projects run in parallel; the same project never runs
6
+ twice at once (the tracker keeps it ``RUNNING`` until the callback returns).
7
+
8
+ The detector's :meth:`handle_activity` can be passed straight to
9
+ :class:`RepositoryMonitor` as its ``on_activity`` callback.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+ import threading
16
+ import time
17
+ from collections.abc import Callable, Mapping
18
+ from concurrent.futures import ThreadPoolExecutor
19
+ from datetime import datetime
20
+
21
+ from gitgatekeeper.core.events import ProjectActivity
22
+ from gitgatekeeper.core.inactivity import InactivitySnapshot, InactivityTracker
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+ EligibleCallback = Callable[[str], None]
27
+
28
+ DEFAULT_MAX_WORKERS = 4
29
+ STOP_JOIN_TIMEOUT_SECONDS = 5.0
30
+
31
+
32
+ class InactivityDetector:
33
+ """Calls ``on_eligible(project)`` once a project has been quiet long enough.
34
+
35
+ An exception raised by the callback is logged with its traceback and does
36
+ not stop the detector; the project simply returns to idle.
37
+ """
38
+
39
+ def __init__(
40
+ self,
41
+ thresholds: Mapping[str, float],
42
+ on_eligible: EligibleCallback,
43
+ *,
44
+ max_workers: int = DEFAULT_MAX_WORKERS,
45
+ clock: Callable[[], float] = time.monotonic,
46
+ wall_clock: Callable[[], float] = time.time,
47
+ ) -> None:
48
+ if max_workers < 1:
49
+ raise ValueError("max_workers must be at least 1")
50
+ self._thresholds = dict(thresholds)
51
+ self._on_eligible = on_eligible
52
+ self._max_workers = max_workers
53
+ self._clock = clock
54
+ self._wall_clock = wall_clock
55
+
56
+ self._lifecycle_lock = threading.Lock()
57
+ self._cond = threading.Condition()
58
+ self._tracker = InactivityTracker(self._thresholds, clock)
59
+ self._stopping = False
60
+ self._worker: threading.Thread | None = None
61
+ self._executor: ThreadPoolExecutor | None = None
62
+
63
+ # -- public API ------------------------------------------------------
64
+ @property
65
+ def is_running(self) -> bool:
66
+ return self._worker is not None
67
+
68
+ def handle_activity(self, activity: ProjectActivity) -> None:
69
+ """Register a monitor batch. Raises ``KeyError`` for unknown projects."""
70
+ age = self._age_seconds(activity.occurred_at)
71
+ with self._cond:
72
+ self._tracker.record_activity(activity.project, age=age)
73
+ self._cond.notify()
74
+
75
+ def record_activity(self, project: str) -> None:
76
+ """Register activity that happened just now (e.g. a startup scan)."""
77
+ with self._cond:
78
+ self._tracker.record_activity(project)
79
+ self._cond.notify()
80
+
81
+ def snapshot(self) -> list[InactivitySnapshot]:
82
+ with self._cond:
83
+ return self._tracker.snapshot()
84
+
85
+ def start(self) -> None:
86
+ """Start the detector. May be called again after :meth:`stop`."""
87
+ with self._lifecycle_lock:
88
+ if self._worker is not None:
89
+ raise RuntimeError("detector is already running")
90
+ with self._cond:
91
+ self._tracker = InactivityTracker(self._thresholds, self._clock)
92
+ self._stopping = False
93
+ self._executor = ThreadPoolExecutor(
94
+ max_workers=self._max_workers, thread_name_prefix="gitgatekeeper-run"
95
+ )
96
+ self._worker = threading.Thread(
97
+ target=self._run, name="gitgatekeeper-inactivity", daemon=True
98
+ )
99
+ self._worker.start()
100
+
101
+ def stop(self) -> None:
102
+ """Stop the detector, letting any callback that is running finish.
103
+
104
+ Projects still waiting out their quiet period are dropped. Idempotent.
105
+ """
106
+ with self._lifecycle_lock:
107
+ worker, executor = self._worker, self._executor
108
+ if worker is None or executor is None:
109
+ return
110
+ with self._cond:
111
+ self._stopping = True
112
+ self._cond.notify_all()
113
+ worker.join(timeout=STOP_JOIN_TIMEOUT_SECONDS)
114
+ executor.shutdown(wait=True) # never abandon a run half-way
115
+ self._worker = None
116
+ self._executor = None
117
+
118
+ def __enter__(self) -> InactivityDetector:
119
+ self.start()
120
+ return self
121
+
122
+ def __exit__(self, *exc_info: object) -> None:
123
+ self.stop()
124
+
125
+ # -- internals -------------------------------------------------------
126
+ def _age_seconds(self, occurred_at: datetime) -> float:
127
+ return max(self._wall_clock() - occurred_at.timestamp(), 0.0)
128
+
129
+ def _run(self) -> None:
130
+ executor = self._executor
131
+ assert executor is not None
132
+ while True:
133
+ with self._cond:
134
+ while not self._stopping:
135
+ due = self._tracker.next_due_in()
136
+ if due is not None and due <= 0:
137
+ break
138
+ self._cond.wait(timeout=due)
139
+ if self._stopping:
140
+ return
141
+ eligible = self._tracker.take_eligible()
142
+ for project in eligible:
143
+ executor.submit(self._execute, project)
144
+
145
+ def _execute(self, project: str) -> None:
146
+ try:
147
+ self._on_eligible(project)
148
+ except Exception:
149
+ # The callback is foreign code; never let it kill the detector.
150
+ logger.exception("analysis failed for %s", project)
151
+ finally:
152
+ with self._cond:
153
+ self._tracker.finish(project)
154
+ self._cond.notify()
@@ -0,0 +1,172 @@
1
+ """Find Git repositories under a few folders, read-only.
2
+
3
+ Used by ``gitgatekeeper init``. Nothing here writes to a repository, follows
4
+ symbolic links or looks outside the folders it is given.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ from collections.abc import Iterable
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+
14
+ from gitgatekeeper.git.repository import GitError, run_git
15
+
16
+ # Folders where people usually keep code, tried in this order under $HOME.
17
+ COMMON_ROOTS = (
18
+ "Projetos",
19
+ "Projects",
20
+ "projects",
21
+ "projetos",
22
+ "dev",
23
+ "code",
24
+ "src",
25
+ "repos",
26
+ "workspace",
27
+ "Agents",
28
+ )
29
+
30
+ # Never worth descending into: dependencies, caches and build output.
31
+ _SKIP_DIRS = frozenset(
32
+ {
33
+ "node_modules",
34
+ "venv",
35
+ "env",
36
+ "__pycache__",
37
+ "site-packages",
38
+ "target",
39
+ "dist",
40
+ "build",
41
+ "vendor",
42
+ "snap",
43
+ }
44
+ )
45
+
46
+ DEFAULT_DEPTH = 3
47
+ MAX_REPOSITORIES = 500
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class Discovered:
52
+ """A repository found on disk."""
53
+
54
+ path: Path
55
+ branch: str | None
56
+ remote: str | None
57
+
58
+ @property
59
+ def name(self) -> str:
60
+ return self.path.name
61
+
62
+
63
+ def default_roots(home: Path | None = None) -> list[Path]:
64
+ """The usual code folders that exist under ``home``."""
65
+ base = home if home is not None else Path.home()
66
+ return [base / name for name in COMMON_ROOTS if (base / name).is_dir()]
67
+
68
+
69
+ def discover(
70
+ roots: Iterable[Path],
71
+ *,
72
+ depth: int = DEFAULT_DEPTH,
73
+ limit: int = MAX_REPOSITORIES,
74
+ ) -> list[Discovered]:
75
+ """Return the repositories found under ``roots``, sorted by path.
76
+
77
+ A folder holding ``.git`` is a repository; its inside is not searched, so
78
+ nested repositories and submodules are not listed separately. Hidden
79
+ folders, dependency folders and symbolic links are skipped. The search
80
+ stops at ``limit`` repositories.
81
+ """
82
+ found: dict[Path, Discovered] = {}
83
+ for root in roots:
84
+ top = root.expanduser().resolve()
85
+ if not top.is_dir():
86
+ continue
87
+ for repo in _walk(top, depth):
88
+ if repo in found:
89
+ continue
90
+ found[repo] = _describe(repo)
91
+ if len(found) >= limit:
92
+ return sorted(found.values(), key=lambda item: str(item.path))
93
+ return sorted(found.values(), key=lambda item: str(item.path))
94
+
95
+
96
+ def _walk(top: Path, depth: int) -> Iterable[Path]:
97
+ pending = [(top, 0)]
98
+ while pending:
99
+ current, level = pending.pop()
100
+ if (current / ".git").exists():
101
+ yield current
102
+ continue
103
+ if level >= depth:
104
+ continue
105
+ try:
106
+ entries = sorted(os.scandir(current), key=lambda entry: entry.name)
107
+ except OSError:
108
+ continue
109
+ for entry in reversed(entries):
110
+ name = entry.name
111
+ if name.startswith(".") or name in _SKIP_DIRS:
112
+ continue
113
+ try:
114
+ if entry.is_dir(follow_symlinks=False):
115
+ pending.append((Path(entry.path), level + 1))
116
+ except OSError:
117
+ continue
118
+
119
+
120
+ def _describe(repo: Path) -> Discovered:
121
+ branch = _git_line(repo, ["branch", "--show-current"])
122
+ remote = _git_line(repo, ["config", "--get", "remote.origin.url"])
123
+ return Discovered(path=repo, branch=branch, remote=_strip_credentials(remote))
124
+
125
+
126
+ def _git_line(repo: Path, args: list[str]) -> str | None:
127
+ try:
128
+ result = run_git(args, cwd=repo, timeout=10)
129
+ except GitError:
130
+ return None
131
+ if result.returncode != 0:
132
+ return None
133
+ return result.stdout.strip() or None
134
+
135
+
136
+ def _strip_credentials(url: str | None) -> str | None:
137
+ """Remove ``user:password@`` from an https remote before it is displayed."""
138
+ if not url or "://" not in url:
139
+ return url
140
+ scheme, rest = url.split("://", 1)
141
+ authority, sep, tail = rest.partition("/")
142
+ if "@" in authority:
143
+ authority = authority.rsplit("@", 1)[1]
144
+ return f"{scheme}://{authority}{sep}{tail}"
145
+
146
+
147
+ def parse_selection(text: str, count: int) -> list[int]:
148
+ """Turn ``"1,3,5-7"``, ``"all"`` or ``"none"`` into 0-based indexes.
149
+
150
+ An empty answer means all. Raises ``ValueError`` on anything else.
151
+ """
152
+ answer = text.strip().lower()
153
+ if answer in ("", "a", "all", "todos", "t"):
154
+ return list(range(count))
155
+ if answer in ("n", "none", "nenhum", "0"):
156
+ return []
157
+ chosen: set[int] = set()
158
+ for part in answer.replace(" ", "").split(","):
159
+ if not part:
160
+ continue
161
+ low, dash, high = part.partition("-")
162
+ try:
163
+ first = int(low)
164
+ last = int(high) if dash else first
165
+ except ValueError:
166
+ raise ValueError(f"not a number or range: {part!r}") from None
167
+ if first > last:
168
+ raise ValueError(f"empty range: {part!r}")
169
+ if first < 1 or last > count:
170
+ raise ValueError(f"out of range 1-{count}: {part!r}")
171
+ chosen.update(range(first - 1, last))
172
+ return sorted(chosen)
@@ -0,0 +1,220 @@
1
+ """Read-only readiness check of a project (``gitgatekeeper check``).
2
+
3
+ Looks only at the local repository and its configuration; it never contacts a
4
+ remote, so it is safe and instant. It answers "will GitGatekeeper be able to commit
5
+ and publish here, and if not, what do I run?".
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+ from enum import StrEnum
12
+ from fnmatch import fnmatchcase
13
+
14
+ from gitgatekeeper.config import AppConfig, ProjectConfig
15
+ from gitgatekeeper.core.push_engine import (
16
+ NO_PROMPT_ENV,
17
+ PushReason,
18
+ classify_failure,
19
+ redact,
20
+ )
21
+ from gitgatekeeper.git.analyzer import analyze_repository
22
+ from gitgatekeeper.git.repository import GitError, find_repository_root, run_git
23
+
24
+ PROBE_TIMEOUT_SECONDS = 20.0
25
+
26
+
27
+ class Level(StrEnum):
28
+ OK = "ok"
29
+ WARN = "warn"
30
+ FAIL = "fail"
31
+
32
+
33
+ @dataclass(frozen=True, slots=True)
34
+ class Check:
35
+ level: Level
36
+ text: str
37
+ fix: str = ""
38
+
39
+
40
+ def _config_value(root, key: str) -> str | None: # type: ignore[no-untyped-def]
41
+ result = run_git(["config", "--get", key], root)
42
+ value = result.stdout.strip()
43
+ return value if result.returncode == 0 and value else None
44
+
45
+
46
+ def _upstream_fix(root, branch: str) -> str: # type: ignore[no-untyped-def]
47
+ """The command that gives ``branch`` an upstream, naming the right remote."""
48
+ remotes = run_git(["remote"], root).stdout.split()
49
+ if not remotes:
50
+ return (
51
+ "create the repository on your Git host, then run: "
52
+ f"git remote add origin <url> && git push -u origin {branch}"
53
+ )
54
+ name = "origin" if "origin" in remotes else remotes[0]
55
+ return f"git push -u {name} {branch}"
56
+
57
+
58
+ def explain_remote_failure(output: str, remote: str) -> Check:
59
+ """Turn Git's error text from a remote probe into a finding with a fix."""
60
+ text = output.lower()
61
+ reason = classify_failure(output)
62
+ if "host key verification failed" in text:
63
+ return Check(
64
+ Level.FAIL,
65
+ f"the SSH host key of {remote!r} is not trusted yet",
66
+ "run `git ls-remote --heads "
67
+ f"{remote}` once in a terminal and accept the host key only if its "
68
+ "fingerprint matches the one the provider publishes",
69
+ )
70
+ if "permission denied (publickey" in text:
71
+ return Check(
72
+ Level.FAIL,
73
+ f"{remote!r} rejected your SSH key",
74
+ "add the content of ~/.ssh/id_ed25519.pub (the .pub file only) to "
75
+ "your account's SSH keys on that host",
76
+ )
77
+ if reason is PushReason.AUTH_FAILED:
78
+ return Check(
79
+ Level.FAIL,
80
+ f"cannot authenticate to {remote!r} without a prompt "
81
+ "(or the repository was not found)",
82
+ "check the remote URL and your access; GitGatekeeper cannot type "
83
+ "passwords, so use an SSH key or a credential helper",
84
+ )
85
+ if reason is PushReason.NETWORK:
86
+ return Check(
87
+ Level.WARN,
88
+ f"cannot reach {remote!r} right now ({redact(output)[-120:]})",
89
+ "this is only a problem if it persists; failed pushes are retried",
90
+ )
91
+ return Check(Level.WARN, f"could not probe {remote!r}: {redact(output)[-160:]}")
92
+
93
+
94
+ def _probe_remote(root, remote: str, ref: str) -> Check: # type: ignore[no-untyped-def]
95
+ try:
96
+ result = run_git(
97
+ ["ls-remote", "--heads", remote, ref],
98
+ root,
99
+ timeout=PROBE_TIMEOUT_SECONDS,
100
+ new_session=True,
101
+ extra_env=NO_PROMPT_ENV,
102
+ )
103
+ except GitError as exc:
104
+ return Check(Level.WARN, f"remote {remote!r} did not answer: {exc}")
105
+ if result.returncode == 0:
106
+ return Check(Level.OK, f"remote {remote!r} is reachable and accepts you")
107
+ return explain_remote_failure(result.stderr or result.stdout, remote)
108
+
109
+
110
+ def check_project(
111
+ config: AppConfig, project: ProjectConfig, *, probe_remote: bool = False
112
+ ) -> list[Check]:
113
+ """Return the findings for ``project``; never raises for Git problems.
114
+
115
+ With ``probe_remote`` it also runs one read-only ``git ls-remote`` against
116
+ the upstream's remote (never prompting) to catch access problems early.
117
+ """
118
+ checks: list[Check] = []
119
+ try:
120
+ root = find_repository_root(project.path)
121
+ if root is None:
122
+ return [Check(Level.FAIL, f"{project.path} is not a Git repository")]
123
+ snapshot = analyze_repository(root)
124
+ except (GitError, OSError) as exc:
125
+ return [Check(Level.FAIL, f"cannot inspect the repository: {exc}")]
126
+
127
+ for key, label in (("user.name", "name"), ("user.email", "email")):
128
+ if _config_value(root, key) is None:
129
+ checks.append(
130
+ Check(
131
+ Level.FAIL,
132
+ f"Git {label} is not configured; commits would fail",
133
+ f"git config --global {key} 'value'",
134
+ )
135
+ )
136
+
137
+ branch = snapshot.branch
138
+ for blocker in snapshot.blockers:
139
+ checks.append(Check(Level.WARN, f"blocked right now: {blocker}"))
140
+ if branch.detached or branch.name is None:
141
+ checks.append(
142
+ Check(Level.FAIL, "HEAD is detached; GitGatekeeper will not commit")
143
+ )
144
+ return checks
145
+ protected = config.effective_protected_branches(project)
146
+ if any(fnmatchcase(branch.name, p) for p in protected):
147
+ checks.append(
148
+ Check(
149
+ Level.WARN,
150
+ f"branch {branch.name!r} is protected; GitGatekeeper will not commit "
151
+ "or push here",
152
+ "work on another branch, or set `protected_branches: []` for "
153
+ "this project",
154
+ )
155
+ )
156
+ else:
157
+ checks.append(Check(Level.OK, f"branch {branch.name!r} is not protected"))
158
+
159
+ limit = config.effective_max_files(project)
160
+ pending = len(snapshot.files)
161
+ if pending > limit:
162
+ checks.append(
163
+ Check(
164
+ Level.WARN,
165
+ f"{pending} changed files exceed the limit of {limit} per cycle; "
166
+ "GitGatekeeper will commit nothing here",
167
+ "commit in batches yourself, or raise `max_files_per_commit` "
168
+ "for this project in the config",
169
+ )
170
+ )
171
+
172
+ if not config.effective_auto_push(project):
173
+ checks.append(
174
+ Check(
175
+ Level.WARN,
176
+ "auto_push is off; commits stay local",
177
+ "set `auto_push: true` for this project in the config",
178
+ )
179
+ )
180
+ return checks
181
+
182
+ remote = _config_value(root, f"branch.{branch.name}.remote")
183
+ merge = _config_value(root, f"branch.{branch.name}.merge")
184
+ if remote is None or merge is None or remote == ".":
185
+ checks.append(
186
+ Check(
187
+ Level.FAIL,
188
+ f"branch {branch.name!r} has no remote upstream; nothing can be pushed",
189
+ _upstream_fix(root, branch.name),
190
+ )
191
+ )
192
+ return checks
193
+ target = merge.removeprefix("refs/heads/")
194
+ if any(fnmatchcase(target, p) for p in protected):
195
+ checks.append(
196
+ Check(
197
+ Level.WARN,
198
+ f"the upstream branch {target!r} is protected; pushes are refused",
199
+ )
200
+ )
201
+ else:
202
+ checks.append(Check(Level.OK, f"pushes go to {remote}/{target}"))
203
+ if probe_remote:
204
+ checks.append(_probe_remote(root, remote, merge))
205
+ if branch.ahead is None:
206
+ checks.append(Check(Level.WARN, "the upstream was never fetched", "git fetch"))
207
+ else:
208
+ if branch.behind:
209
+ checks.append(
210
+ Check(
211
+ Level.WARN,
212
+ f"{branch.behind} commit(s) behind upstream; pushes are refused",
213
+ "git pull --rebase",
214
+ )
215
+ )
216
+ if branch.ahead:
217
+ checks.append(
218
+ Check(Level.OK, f"{branch.ahead} commit(s) waiting to be pushed")
219
+ )
220
+ return checks
@@ -0,0 +1,89 @@
1
+ """Event types emitted by the repository monitor."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from datetime import datetime
7
+ from enum import StrEnum
8
+ from pathlib import Path
9
+
10
+ from gitgatekeeper.core.filters import is_ignored_file
11
+
12
+
13
+ class ChangeKind(StrEnum):
14
+ CREATED = "created"
15
+ MODIFIED = "modified"
16
+ DELETED = "deleted"
17
+ MOVED = "moved"
18
+
19
+
20
+ @dataclass(frozen=True, slots=True)
21
+ class FileChange:
22
+ """A single file change. Paths are relative to the repository root."""
23
+
24
+ kind: ChangeKind
25
+ path: Path
26
+ dest_path: Path | None = None # only for MOVED
27
+
28
+
29
+ @dataclass(frozen=True, slots=True)
30
+ class ProjectActivity:
31
+ """A debounced batch of relevant changes in one project."""
32
+
33
+ project: str
34
+ repo: Path
35
+ changes: tuple[FileChange, ...]
36
+ occurred_at: datetime # timezone-aware UTC time of the last raw event
37
+
38
+
39
+ def drop_ignored(
40
+ changes: tuple[FileChange, ...], ignored: set[str]
41
+ ) -> tuple[FileChange, ...]:
42
+ """Apply a set of ``.gitignore``-ignored POSIX paths to ``changes``.
43
+
44
+ Mirrors the move rules of :func:`translate_file_event`: a move out of an
45
+ ignored path is a creation, a move into one is a deletion.
46
+ """
47
+ kept: list[FileChange] = []
48
+ for change in changes:
49
+ src_ignored = change.path.as_posix() in ignored
50
+ if change.kind is not ChangeKind.MOVED:
51
+ if not src_ignored:
52
+ kept.append(change)
53
+ continue
54
+ assert change.dest_path is not None
55
+ dest_ignored = change.dest_path.as_posix() in ignored
56
+ if src_ignored and dest_ignored:
57
+ continue
58
+ if src_ignored:
59
+ kept.append(FileChange(ChangeKind.MODIFIED, change.dest_path))
60
+ elif dest_ignored:
61
+ kept.append(FileChange(ChangeKind.DELETED, change.path))
62
+ else:
63
+ kept.append(change)
64
+ return tuple(kept)
65
+
66
+
67
+ def translate_file_event(
68
+ kind: ChangeKind, src: Path, dest: Path | None = None
69
+ ) -> FileChange | None:
70
+ """Build a :class:`FileChange`, or ``None`` if the event is irrelevant.
71
+
72
+ Moves are normalised against the static filters: renaming a temporary file
73
+ onto a real one (an editor's atomic save) is a modification of the real
74
+ file, and renaming a real file to a temporary name is a deletion.
75
+ """
76
+ if kind is not ChangeKind.MOVED:
77
+ return None if is_ignored_file(src) else FileChange(kind, src)
78
+
79
+ if dest is None:
80
+ raise ValueError("a MOVED change requires a destination")
81
+ src_ignored = is_ignored_file(src)
82
+ dest_ignored = is_ignored_file(dest)
83
+ if src_ignored and dest_ignored:
84
+ return None
85
+ if src_ignored:
86
+ return FileChange(ChangeKind.MODIFIED, dest)
87
+ if dest_ignored:
88
+ return FileChange(ChangeKind.DELETED, src)
89
+ return FileChange(ChangeKind.MOVED, src, dest)