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.
- gitgatekeeper/__init__.py +10 -0
- gitgatekeeper/cli/main.py +1074 -0
- gitgatekeeper/config/__init__.py +18 -0
- gitgatekeeper/config/loader.py +100 -0
- gitgatekeeper/config/models.py +205 -0
- gitgatekeeper/core/__init__.py +46 -0
- gitgatekeeper/core/buffer.py +125 -0
- gitgatekeeper/core/commit_engine.py +900 -0
- gitgatekeeper/core/detector.py +154 -0
- gitgatekeeper/core/discovery.py +172 -0
- gitgatekeeper/core/doctor.py +220 -0
- gitgatekeeper/core/events.py +89 -0
- gitgatekeeper/core/filters.py +79 -0
- gitgatekeeper/core/grouping.py +139 -0
- gitgatekeeper/core/inactivity.py +154 -0
- gitgatekeeper/core/instance.py +202 -0
- gitgatekeeper/core/locking.py +85 -0
- gitgatekeeper/core/migrate.py +134 -0
- gitgatekeeper/core/monitor.py +408 -0
- gitgatekeeper/core/project_manager.py +141 -0
- gitgatekeeper/core/push_engine.py +441 -0
- gitgatekeeper/core/service.py +703 -0
- gitgatekeeper/core/systemd.py +223 -0
- gitgatekeeper/core/undo.py +104 -0
- gitgatekeeper/git/__init__.py +43 -0
- gitgatekeeper/git/analyzer.py +96 -0
- gitgatekeeper/git/diff.py +252 -0
- gitgatekeeper/git/ignore.py +36 -0
- gitgatekeeper/git/models.py +118 -0
- gitgatekeeper/git/repository.py +123 -0
- gitgatekeeper/git/secrets.py +150 -0
- gitgatekeeper/git/sensitive.py +114 -0
- gitgatekeeper/git/status_parser.py +134 -0
- gitgatekeeper/intelligence/__init__.py +23 -0
- gitgatekeeper/intelligence/analysis.py +358 -0
- gitgatekeeper/intelligence/context.py +57 -0
- gitgatekeeper/intelligence/message.py +117 -0
- gitgatekeeper/intelligence/profile.py +213 -0
- gitgatekeeper/intelligence/provider.py +65 -0
- gitgatekeeper/intelligence/rules.py +561 -0
- gitgatekeeper/logging_setup.py +122 -0
- gitgatekeeper/storage/__init__.py +16 -0
- gitgatekeeper/storage/database.py +235 -0
- gitgatekeeper/storage/history.py +440 -0
- gitgatekeeper/storage/models.py +78 -0
- gitgatekeeper/storage/recorder.py +178 -0
- gitgatekeeper-0.1.1.dist-info/METADATA +671 -0
- gitgatekeeper-0.1.1.dist-info/RECORD +52 -0
- gitgatekeeper-0.1.1.dist-info/WHEEL +5 -0
- gitgatekeeper-0.1.1.dist-info/entry_points.txt +2 -0
- gitgatekeeper-0.1.1.dist-info/licenses/LICENSE +21 -0
- gitgatekeeper-0.1.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Configuration models and loading."""
|
|
2
|
+
|
|
3
|
+
from gitgatekeeper.config.loader import (
|
|
4
|
+
ConfigError,
|
|
5
|
+
default_config_path,
|
|
6
|
+
load_config,
|
|
7
|
+
save_config,
|
|
8
|
+
)
|
|
9
|
+
from gitgatekeeper.config.models import AppConfig, ProjectConfig
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"AppConfig",
|
|
13
|
+
"ConfigError",
|
|
14
|
+
"ProjectConfig",
|
|
15
|
+
"default_config_path",
|
|
16
|
+
"load_config",
|
|
17
|
+
"save_config",
|
|
18
|
+
]
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Loading, saving and locating the GitGatekeeper YAML configuration."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import tempfile
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import yaml
|
|
10
|
+
from pydantic import ValidationError
|
|
11
|
+
|
|
12
|
+
from gitgatekeeper.config.models import AppConfig
|
|
13
|
+
|
|
14
|
+
CONFIG_ENV_VAR = "GITGATEKEEPER_CONFIG"
|
|
15
|
+
LOCAL_CONFIG = Path("config") / "projects.yaml"
|
|
16
|
+
USER_CONFIG = Path("~/.config/gitgatekeeper/projects.yaml")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ConfigError(Exception):
|
|
20
|
+
"""Raised when the configuration cannot be read, parsed or validated."""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def default_config_path() -> Path:
|
|
24
|
+
"""Resolve the config file location.
|
|
25
|
+
|
|
26
|
+
Order: ``$GITGATEKEEPER_CONFIG``, ``./config/projects.yaml``, then
|
|
27
|
+
``~/.config/gitgatekeeper/projects.yaml``. A ``./config/projects.yaml`` that
|
|
28
|
+
watches nothing (the template of a checkout, say) never hides a real user
|
|
29
|
+
config: it is skipped while the user config exists. A local file that
|
|
30
|
+
cannot be parsed is still chosen, so its error is shown instead of hidden.
|
|
31
|
+
"""
|
|
32
|
+
env_value = os.environ.get(CONFIG_ENV_VAR)
|
|
33
|
+
if env_value:
|
|
34
|
+
return Path(env_value).expanduser().resolve()
|
|
35
|
+
user = USER_CONFIG.expanduser()
|
|
36
|
+
local = (Path.cwd() / LOCAL_CONFIG).resolve()
|
|
37
|
+
if local.is_file():
|
|
38
|
+
if user.is_file() and not _watches_something(local):
|
|
39
|
+
return user
|
|
40
|
+
return local
|
|
41
|
+
return user
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _watches_something(path: Path) -> bool:
|
|
45
|
+
try:
|
|
46
|
+
config = load_config(path)
|
|
47
|
+
except ConfigError:
|
|
48
|
+
return True
|
|
49
|
+
return any(project.enabled for project in config.projects)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def load_config(path: Path) -> AppConfig:
|
|
53
|
+
"""Load and validate the config at ``path``.
|
|
54
|
+
|
|
55
|
+
A missing file yields an empty default configuration; an unreadable,
|
|
56
|
+
malformed or invalid file raises :class:`ConfigError`.
|
|
57
|
+
"""
|
|
58
|
+
if not path.exists():
|
|
59
|
+
return AppConfig()
|
|
60
|
+
try:
|
|
61
|
+
raw = yaml.safe_load(path.read_text(encoding="utf-8"))
|
|
62
|
+
except OSError as exc:
|
|
63
|
+
raise ConfigError(f"cannot read {path}: {exc}") from exc
|
|
64
|
+
except yaml.YAMLError as exc:
|
|
65
|
+
raise ConfigError(f"invalid YAML in {path}: {exc}") from exc
|
|
66
|
+
|
|
67
|
+
if raw is None:
|
|
68
|
+
return AppConfig()
|
|
69
|
+
if not isinstance(raw, dict):
|
|
70
|
+
raise ConfigError(f"{path}: top-level value must be a mapping")
|
|
71
|
+
|
|
72
|
+
try:
|
|
73
|
+
return AppConfig.model_validate(raw)
|
|
74
|
+
except ValidationError as exc:
|
|
75
|
+
raise ConfigError(f"invalid configuration in {path}:\n{exc}") from exc
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def save_config(config: AppConfig, path: Path) -> None:
|
|
79
|
+
"""Atomically write ``config`` to ``path`` (temp file + rename)."""
|
|
80
|
+
data = config.model_dump(mode="json", exclude_none=True)
|
|
81
|
+
for project in data.get("projects", []):
|
|
82
|
+
if not project.get("modules"):
|
|
83
|
+
project.pop("modules", None) # keep the file free of empty blocks
|
|
84
|
+
if not project.get("secret_scan_allow"):
|
|
85
|
+
project.pop("secret_scan_allow", None)
|
|
86
|
+
text = yaml.safe_dump(data, sort_keys=False, allow_unicode=True)
|
|
87
|
+
try:
|
|
88
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
89
|
+
fd, tmp_name = tempfile.mkstemp(
|
|
90
|
+
dir=path.parent, prefix=f".{path.name}.", suffix=".tmp"
|
|
91
|
+
)
|
|
92
|
+
try:
|
|
93
|
+
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
94
|
+
handle.write(text)
|
|
95
|
+
os.replace(tmp_name, path)
|
|
96
|
+
except BaseException:
|
|
97
|
+
Path(tmp_name).unlink(missing_ok=True)
|
|
98
|
+
raise
|
|
99
|
+
except OSError as exc:
|
|
100
|
+
raise ConfigError(f"cannot write {path}: {exc}") from exc
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""Pydantic models describing the GitGatekeeper configuration file."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
|
9
|
+
|
|
10
|
+
DEFAULT_INACTIVITY_MINUTES = 10
|
|
11
|
+
MODULE_NAME = re.compile(r"^[a-z0-9][a-z0-9._-]*$")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
DEFAULT_PROTECTED_BRANCHES = ("main", "master")
|
|
15
|
+
# Shortly before midnight, so the commit still lands on the day it is for.
|
|
16
|
+
DEFAULT_DAILY_COMMIT_TIME = "23:55"
|
|
17
|
+
_CLOCK_TIME = re.compile(r"^([01]\d|2[0-3]):([0-5]\d)$")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _clean_branch_patterns(value: list[str]) -> list[str]:
|
|
21
|
+
cleaned = [item.strip() for item in value]
|
|
22
|
+
if any(not item for item in cleaned):
|
|
23
|
+
raise ValueError("protected branch names must not be blank")
|
|
24
|
+
return cleaned
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ProjectConfig(BaseModel):
|
|
28
|
+
"""A single monitored Git project."""
|
|
29
|
+
|
|
30
|
+
model_config = ConfigDict(extra="forbid")
|
|
31
|
+
|
|
32
|
+
name: str = Field(min_length=1)
|
|
33
|
+
path: Path
|
|
34
|
+
enabled: bool = True
|
|
35
|
+
# ``None`` means "use the global value".
|
|
36
|
+
inactivity_minutes: int | None = Field(default=None, ge=1)
|
|
37
|
+
auto_push: bool | None = None
|
|
38
|
+
# ``None`` means "use the global value".
|
|
39
|
+
protected_branches: list[str] | None = None
|
|
40
|
+
split_commits: bool | None = None
|
|
41
|
+
max_files_per_commit: int | None = Field(default=None, ge=1, le=2000)
|
|
42
|
+
daily_commit: bool | None = None
|
|
43
|
+
require_approval: bool | None = None
|
|
44
|
+
# Optional hand-made map of the project's modules: name -> paths (a folder
|
|
45
|
+
# prefix like "src/billing" or a glob like "app/**/*Invoice*.php"). It
|
|
46
|
+
# refines what GitGatekeeper detects on its own; leave it out to rely on that.
|
|
47
|
+
modules: dict[str, list[str]] = Field(default_factory=dict)
|
|
48
|
+
# Paths (globs, or "dir/") where `password = "..."`-style lines are known to
|
|
49
|
+
# be examples or test values. Only that one heuristic is relaxed there.
|
|
50
|
+
secret_scan_allow: list[str] = Field(default_factory=list)
|
|
51
|
+
|
|
52
|
+
@field_validator("modules")
|
|
53
|
+
@classmethod
|
|
54
|
+
def _check_modules(cls, value: dict[str, list[str]]) -> dict[str, list[str]]:
|
|
55
|
+
cleaned: dict[str, list[str]] = {}
|
|
56
|
+
for name, patterns in value.items():
|
|
57
|
+
if not MODULE_NAME.match(name):
|
|
58
|
+
raise ValueError(
|
|
59
|
+
f"invalid module name {name!r}: use lowercase letters, "
|
|
60
|
+
"digits, '.', '_' or '-'"
|
|
61
|
+
)
|
|
62
|
+
if not patterns:
|
|
63
|
+
raise ValueError(f"module {name!r} needs at least one path")
|
|
64
|
+
checked: list[str] = []
|
|
65
|
+
for pattern in patterns:
|
|
66
|
+
pattern = pattern.strip()
|
|
67
|
+
parts = pattern.split("/")
|
|
68
|
+
if not pattern or pattern.startswith("/") or ".." in parts:
|
|
69
|
+
raise ValueError(
|
|
70
|
+
f"module {name!r}: paths must be relative to the "
|
|
71
|
+
f"repository and must not contain '..': {pattern!r}"
|
|
72
|
+
)
|
|
73
|
+
checked.append(pattern)
|
|
74
|
+
cleaned[name] = checked
|
|
75
|
+
return cleaned
|
|
76
|
+
|
|
77
|
+
@field_validator("secret_scan_allow")
|
|
78
|
+
@classmethod
|
|
79
|
+
def _check_allow(cls, value: list[str]) -> list[str]:
|
|
80
|
+
cleaned: list[str] = []
|
|
81
|
+
for pattern in value:
|
|
82
|
+
pattern = pattern.strip()
|
|
83
|
+
parts = pattern.split("/")
|
|
84
|
+
if not pattern or pattern.startswith("/") or ".." in parts:
|
|
85
|
+
raise ValueError(
|
|
86
|
+
"secret_scan_allow paths must be relative to the repository "
|
|
87
|
+
f"and must not contain '..': {pattern!r}"
|
|
88
|
+
)
|
|
89
|
+
cleaned.append(pattern)
|
|
90
|
+
return cleaned
|
|
91
|
+
|
|
92
|
+
@field_validator("protected_branches")
|
|
93
|
+
@classmethod
|
|
94
|
+
def _check_protected(cls, value: list[str] | None) -> list[str] | None:
|
|
95
|
+
return _clean_branch_patterns(value) if value is not None else None
|
|
96
|
+
|
|
97
|
+
@field_validator("name")
|
|
98
|
+
@classmethod
|
|
99
|
+
def _strip_name(cls, value: str) -> str:
|
|
100
|
+
value = value.strip()
|
|
101
|
+
if not value:
|
|
102
|
+
raise ValueError("project name must not be blank")
|
|
103
|
+
return value
|
|
104
|
+
|
|
105
|
+
@field_validator("path")
|
|
106
|
+
@classmethod
|
|
107
|
+
def _require_absolute_path(cls, value: Path) -> Path:
|
|
108
|
+
value = value.expanduser()
|
|
109
|
+
if not value.is_absolute():
|
|
110
|
+
raise ValueError(f"project path must be absolute: {value}")
|
|
111
|
+
return value
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class AppConfig(BaseModel):
|
|
115
|
+
"""Root configuration: global defaults plus the project list."""
|
|
116
|
+
|
|
117
|
+
model_config = ConfigDict(extra="forbid")
|
|
118
|
+
|
|
119
|
+
inactivity_minutes: int = Field(default=DEFAULT_INACTIVITY_MINUTES, ge=1)
|
|
120
|
+
auto_push: bool = False
|
|
121
|
+
# Branches (names or globs such as "release/*") GitGatekeeper never commits to
|
|
122
|
+
# or pushes to. Set to [] to switch the protection off.
|
|
123
|
+
protected_branches: list[str] = Field(
|
|
124
|
+
default_factory=lambda: list(DEFAULT_PROTECTED_BRANCHES)
|
|
125
|
+
)
|
|
126
|
+
# One commit per module/docs/config group instead of a single commit.
|
|
127
|
+
split_commits: bool = True
|
|
128
|
+
# Safety valve: a cycle with more changed files than this commits nothing.
|
|
129
|
+
max_files_per_commit: int = Field(default=50, ge=1, le=2000)
|
|
130
|
+
# Once a day, at ``daily_commit_time`` (local time), commit the projects
|
|
131
|
+
# you worked on today that have pending changes but no commit yet today.
|
|
132
|
+
daily_commit: bool = True
|
|
133
|
+
daily_commit_time: str = DEFAULT_DAILY_COMMIT_TIME
|
|
134
|
+
# Prepare commits but wait for ``gitgatekeeper approve`` instead of committing.
|
|
135
|
+
require_approval: bool = False
|
|
136
|
+
projects: list[ProjectConfig] = Field(default_factory=list)
|
|
137
|
+
|
|
138
|
+
@field_validator("protected_branches")
|
|
139
|
+
@classmethod
|
|
140
|
+
def _check_protected(cls, value: list[str]) -> list[str]:
|
|
141
|
+
return _clean_branch_patterns(value)
|
|
142
|
+
|
|
143
|
+
@field_validator("daily_commit_time")
|
|
144
|
+
@classmethod
|
|
145
|
+
def _check_daily_time(cls, value: str) -> str:
|
|
146
|
+
value = value.strip()
|
|
147
|
+
if not _CLOCK_TIME.match(value):
|
|
148
|
+
raise ValueError("daily_commit_time must look like HH:MM (24-hour)")
|
|
149
|
+
return value
|
|
150
|
+
|
|
151
|
+
@model_validator(mode="after")
|
|
152
|
+
def _reject_duplicates(self) -> AppConfig:
|
|
153
|
+
names: set[str] = set()
|
|
154
|
+
paths: set[Path] = set()
|
|
155
|
+
for project in self.projects:
|
|
156
|
+
key = project.name.casefold()
|
|
157
|
+
if key in names:
|
|
158
|
+
raise ValueError(f"duplicate project name: {project.name!r}")
|
|
159
|
+
if project.path in paths:
|
|
160
|
+
raise ValueError(f"duplicate project path: {project.path}")
|
|
161
|
+
names.add(key)
|
|
162
|
+
paths.add(project.path)
|
|
163
|
+
return self
|
|
164
|
+
|
|
165
|
+
def effective_inactivity_minutes(self, project: ProjectConfig) -> int:
|
|
166
|
+
"""Return the inactivity window for ``project`` (override or global)."""
|
|
167
|
+
if project.inactivity_minutes is not None:
|
|
168
|
+
return project.inactivity_minutes
|
|
169
|
+
return self.inactivity_minutes
|
|
170
|
+
|
|
171
|
+
def effective_auto_push(self, project: ProjectConfig) -> bool:
|
|
172
|
+
"""Return the auto-push flag for ``project`` (override or global)."""
|
|
173
|
+
if project.auto_push is not None:
|
|
174
|
+
return project.auto_push
|
|
175
|
+
return self.auto_push
|
|
176
|
+
|
|
177
|
+
def effective_protected_branches(self, project: ProjectConfig) -> list[str]:
|
|
178
|
+
"""Return the protected branch patterns for ``project``."""
|
|
179
|
+
if project.protected_branches is not None:
|
|
180
|
+
return project.protected_branches
|
|
181
|
+
return self.protected_branches
|
|
182
|
+
|
|
183
|
+
def effective_split_commits(self, project: ProjectConfig) -> bool:
|
|
184
|
+
"""Return whether commits are split by area for ``project``."""
|
|
185
|
+
if project.split_commits is not None:
|
|
186
|
+
return project.split_commits
|
|
187
|
+
return self.split_commits
|
|
188
|
+
|
|
189
|
+
def effective_max_files(self, project: ProjectConfig) -> int:
|
|
190
|
+
"""Return the file limit per cycle for ``project``."""
|
|
191
|
+
if project.max_files_per_commit is not None:
|
|
192
|
+
return project.max_files_per_commit
|
|
193
|
+
return self.max_files_per_commit
|
|
194
|
+
|
|
195
|
+
def effective_daily_commit(self, project: ProjectConfig) -> bool:
|
|
196
|
+
"""Return whether the end-of-day commit is on for ``project``."""
|
|
197
|
+
if project.daily_commit is not None:
|
|
198
|
+
return project.daily_commit
|
|
199
|
+
return self.daily_commit
|
|
200
|
+
|
|
201
|
+
def effective_require_approval(self, project: ProjectConfig) -> bool:
|
|
202
|
+
"""Return whether commits wait for approval for ``project``."""
|
|
203
|
+
if project.require_approval is not None:
|
|
204
|
+
return project.require_approval
|
|
205
|
+
return self.require_approval
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Core domain logic.
|
|
2
|
+
|
|
3
|
+
``gitgatekeeper.core.service`` is deliberately not re-exported here: it depends on
|
|
4
|
+
``gitgatekeeper.storage``, which itself imports this package.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from gitgatekeeper.core.commit_engine import (
|
|
8
|
+
CommitEngine,
|
|
9
|
+
CommitResult,
|
|
10
|
+
Outcome,
|
|
11
|
+
Reason,
|
|
12
|
+
select_files,
|
|
13
|
+
)
|
|
14
|
+
from gitgatekeeper.core.instance import AlreadyRunningError, InstanceLock
|
|
15
|
+
from gitgatekeeper.core.locking import LockHeldError, RepositoryLock, default_state_dir
|
|
16
|
+
from gitgatekeeper.core.project_manager import (
|
|
17
|
+
ProjectError,
|
|
18
|
+
ProjectManager,
|
|
19
|
+
ProjectStatus,
|
|
20
|
+
)
|
|
21
|
+
from gitgatekeeper.core.push_engine import (
|
|
22
|
+
PushEngine,
|
|
23
|
+
PushOutcome,
|
|
24
|
+
PushReason,
|
|
25
|
+
PushResult,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"AlreadyRunningError",
|
|
30
|
+
"InstanceLock",
|
|
31
|
+
"CommitEngine",
|
|
32
|
+
"CommitResult",
|
|
33
|
+
"LockHeldError",
|
|
34
|
+
"Outcome",
|
|
35
|
+
"ProjectError",
|
|
36
|
+
"ProjectManager",
|
|
37
|
+
"ProjectStatus",
|
|
38
|
+
"PushEngine",
|
|
39
|
+
"PushOutcome",
|
|
40
|
+
"PushReason",
|
|
41
|
+
"PushResult",
|
|
42
|
+
"Reason",
|
|
43
|
+
"RepositoryLock",
|
|
44
|
+
"default_state_dir",
|
|
45
|
+
"select_files",
|
|
46
|
+
]
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""Per-project debouncing and coalescing of file changes.
|
|
2
|
+
|
|
3
|
+
The buffer is a pure data structure with injectable clocks so it can be tested
|
|
4
|
+
without sleeping. It is **not** thread-safe: the monitor guards it with a lock.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import time
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from gitgatekeeper.core.events import ChangeKind, FileChange
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def merge_changes(old: FileChange, new: FileChange) -> FileChange | None:
|
|
18
|
+
"""Combine two successive changes to the same path.
|
|
19
|
+
|
|
20
|
+
Returns ``None`` when they cancel out (a file created and deleted inside
|
|
21
|
+
one debounce window never existed as far as Git is concerned).
|
|
22
|
+
"""
|
|
23
|
+
pair = (old.kind, new.kind)
|
|
24
|
+
if pair == (ChangeKind.CREATED, ChangeKind.DELETED):
|
|
25
|
+
return None
|
|
26
|
+
if old.kind is ChangeKind.CREATED and new.kind is ChangeKind.MODIFIED:
|
|
27
|
+
return old
|
|
28
|
+
if pair == (ChangeKind.DELETED, ChangeKind.CREATED):
|
|
29
|
+
return FileChange(ChangeKind.MODIFIED, new.path)
|
|
30
|
+
if pair == (ChangeKind.MODIFIED, ChangeKind.CREATED):
|
|
31
|
+
return old
|
|
32
|
+
return new
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True, slots=True)
|
|
36
|
+
class PendingBatch:
|
|
37
|
+
project: str
|
|
38
|
+
changes: tuple[FileChange, ...]
|
|
39
|
+
last_event_wall: float # epoch seconds of the most recent raw event
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(slots=True)
|
|
43
|
+
class _Pending:
|
|
44
|
+
changes: dict[Path, FileChange]
|
|
45
|
+
first_seen: float
|
|
46
|
+
last_seen: float
|
|
47
|
+
last_wall: float
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class ChangeBuffer:
|
|
51
|
+
"""Collects changes per project and releases them once things go quiet.
|
|
52
|
+
|
|
53
|
+
A project's batch is due ``debounce`` seconds after its last event, but no
|
|
54
|
+
later than ``max_wait`` seconds after its first, so a continuous stream of
|
|
55
|
+
events cannot postpone delivery forever.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
def __init__(
|
|
59
|
+
self,
|
|
60
|
+
debounce: float,
|
|
61
|
+
max_wait: float,
|
|
62
|
+
clock: Callable[[], float] = time.monotonic,
|
|
63
|
+
wall_clock: Callable[[], float] = time.time,
|
|
64
|
+
) -> None:
|
|
65
|
+
if debounce <= 0 or max_wait < debounce:
|
|
66
|
+
raise ValueError("require 0 < debounce <= max_wait")
|
|
67
|
+
self._debounce = debounce
|
|
68
|
+
self._max_wait = max_wait
|
|
69
|
+
self._clock = clock
|
|
70
|
+
self._wall_clock = wall_clock
|
|
71
|
+
self._pending: dict[str, _Pending] = {}
|
|
72
|
+
|
|
73
|
+
def __len__(self) -> int:
|
|
74
|
+
return len(self._pending)
|
|
75
|
+
|
|
76
|
+
def add(self, project: str, change: FileChange) -> None:
|
|
77
|
+
now = self._clock()
|
|
78
|
+
wall = self._wall_clock()
|
|
79
|
+
entry = self._pending.get(project)
|
|
80
|
+
if entry is None:
|
|
81
|
+
entry = _Pending({}, first_seen=now, last_seen=now, last_wall=wall)
|
|
82
|
+
self._pending[project] = entry
|
|
83
|
+
else:
|
|
84
|
+
entry.last_seen = now
|
|
85
|
+
entry.last_wall = wall
|
|
86
|
+
|
|
87
|
+
existing = entry.changes.get(change.path)
|
|
88
|
+
merged = change if existing is None else merge_changes(existing, change)
|
|
89
|
+
if merged is None:
|
|
90
|
+
del entry.changes[change.path]
|
|
91
|
+
if not entry.changes:
|
|
92
|
+
del self._pending[project]
|
|
93
|
+
else:
|
|
94
|
+
entry.changes[change.path] = merged
|
|
95
|
+
|
|
96
|
+
def discard(self, project: str) -> None:
|
|
97
|
+
self._pending.pop(project, None)
|
|
98
|
+
|
|
99
|
+
def next_due_in(self) -> float | None:
|
|
100
|
+
"""Seconds until the earliest batch is due (``<= 0`` if overdue)."""
|
|
101
|
+
if not self._pending:
|
|
102
|
+
return None
|
|
103
|
+
now = self._clock()
|
|
104
|
+
return min(self._due_at(entry) for entry in self._pending.values()) - now
|
|
105
|
+
|
|
106
|
+
def pop_due(self) -> list[PendingBatch]:
|
|
107
|
+
now = self._clock()
|
|
108
|
+
due = [
|
|
109
|
+
name for name, entry in self._pending.items() if self._due_at(entry) <= now
|
|
110
|
+
]
|
|
111
|
+
return [self._pop(name) for name in due]
|
|
112
|
+
|
|
113
|
+
def pop_all(self) -> list[PendingBatch]:
|
|
114
|
+
return [self._pop(name) for name in list(self._pending)]
|
|
115
|
+
|
|
116
|
+
def _due_at(self, entry: _Pending) -> float:
|
|
117
|
+
return min(entry.last_seen + self._debounce, entry.first_seen + self._max_wait)
|
|
118
|
+
|
|
119
|
+
def _pop(self, project: str) -> PendingBatch:
|
|
120
|
+
entry = self._pending.pop(project)
|
|
121
|
+
return PendingBatch(
|
|
122
|
+
project=project,
|
|
123
|
+
changes=tuple(entry.changes.values()),
|
|
124
|
+
last_event_wall=entry.last_wall,
|
|
125
|
+
)
|