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,79 @@
|
|
|
1
|
+
"""Cheap, in-process filters for paths that never matter to GitGatekeeper.
|
|
2
|
+
|
|
3
|
+
These run on every raw file-system event, so they must not touch the disk or
|
|
4
|
+
spawn processes. ``.gitignore`` rules are applied later, in batches, by
|
|
5
|
+
:func:`gitgatekeeper.git.find_ignored`.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from fnmatch import fnmatchcase
|
|
11
|
+
from pathlib import PurePath
|
|
12
|
+
|
|
13
|
+
IGNORED_DIR_NAMES = frozenset(
|
|
14
|
+
{
|
|
15
|
+
".git",
|
|
16
|
+
".hg",
|
|
17
|
+
".svn",
|
|
18
|
+
".venv",
|
|
19
|
+
"venv",
|
|
20
|
+
"node_modules",
|
|
21
|
+
"__pycache__",
|
|
22
|
+
"dist",
|
|
23
|
+
"build",
|
|
24
|
+
".pytest_cache",
|
|
25
|
+
".mypy_cache",
|
|
26
|
+
".ruff_cache",
|
|
27
|
+
".tox",
|
|
28
|
+
".nox",
|
|
29
|
+
".cache",
|
|
30
|
+
".idea",
|
|
31
|
+
".vscode",
|
|
32
|
+
"htmlcov",
|
|
33
|
+
}
|
|
34
|
+
)
|
|
35
|
+
IGNORED_DIR_SUFFIXES = (".egg-info",)
|
|
36
|
+
|
|
37
|
+
TEMP_FILE_PATTERNS = (
|
|
38
|
+
"*.swp",
|
|
39
|
+
"*.swo",
|
|
40
|
+
"*.swx",
|
|
41
|
+
"*~",
|
|
42
|
+
".#*",
|
|
43
|
+
"#*#",
|
|
44
|
+
"*.tmp",
|
|
45
|
+
"*.temp",
|
|
46
|
+
"*.part",
|
|
47
|
+
"*.crdownload",
|
|
48
|
+
".goutputstream-*",
|
|
49
|
+
"4913", # vim's write-permission probe file
|
|
50
|
+
"*.pyc",
|
|
51
|
+
"*.pyo",
|
|
52
|
+
".DS_Store",
|
|
53
|
+
"Thumbs.db",
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def is_ignored_dir_name(name: str) -> bool:
|
|
58
|
+
"""True for directories that are never worth watching (``.git``, ...)."""
|
|
59
|
+
return name in IGNORED_DIR_NAMES or name.endswith(IGNORED_DIR_SUFFIXES)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def is_temporary_file(name: str) -> bool:
|
|
63
|
+
"""True for editor swap/backup files and other transient artifacts."""
|
|
64
|
+
return any(fnmatchcase(name, pattern) for pattern in TEMP_FILE_PATTERNS)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def is_ignored_file(relative: PurePath) -> bool:
|
|
68
|
+
"""True if the *file* at ``relative`` (to the repo root) is irrelevant.
|
|
69
|
+
|
|
70
|
+
A file is irrelevant when it lives under an ignored directory or is a
|
|
71
|
+
temporary file. The final component is only matched as a file name, so a
|
|
72
|
+
legitimate file called ``build`` or ``dist`` is still reported.
|
|
73
|
+
"""
|
|
74
|
+
parts = relative.parts
|
|
75
|
+
if not parts:
|
|
76
|
+
return True
|
|
77
|
+
if any(is_ignored_dir_name(part) for part in parts[:-1]):
|
|
78
|
+
return True
|
|
79
|
+
return is_temporary_file(parts[-1])
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""Split one set of changed files into coherent groups, one commit per group.
|
|
2
|
+
|
|
3
|
+
Pure and local: it only looks at paths. A module's code and its tests travel
|
|
4
|
+
together (a feature and its tests are one logical change); documentation and
|
|
5
|
+
build/configuration files each get their own commit.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
from collections.abc import Callable, Sequence
|
|
12
|
+
from fnmatch import fnmatch
|
|
13
|
+
from pathlib import PurePosixPath
|
|
14
|
+
|
|
15
|
+
from gitgatekeeper.intelligence.analysis import FileCategory, categorize
|
|
16
|
+
|
|
17
|
+
MAX_GROUPS = 6
|
|
18
|
+
|
|
19
|
+
_DOC_SUFFIXES = {".md", ".rst", ".adoc", ".txt"}
|
|
20
|
+
_DOC_DIRS = {"docs", "doc"}
|
|
21
|
+
_DOC_NAMES = {"readme", "changelog", "license", "contributing", "authors"}
|
|
22
|
+
_CONFIG_SUFFIXES = {".yaml", ".yml", ".toml", ".ini", ".cfg", ".lock", ".conf"}
|
|
23
|
+
_CONFIG_NAMES = {
|
|
24
|
+
"dockerfile",
|
|
25
|
+
"makefile",
|
|
26
|
+
"package.json",
|
|
27
|
+
"composer.json",
|
|
28
|
+
"requirements.txt",
|
|
29
|
+
".gitignore",
|
|
30
|
+
".editorconfig",
|
|
31
|
+
".gitattributes",
|
|
32
|
+
}
|
|
33
|
+
_CONFIG_PATTERNS = (
|
|
34
|
+
"requirements*.txt",
|
|
35
|
+
"docker-compose*",
|
|
36
|
+
".env.example",
|
|
37
|
+
"*.config.js",
|
|
38
|
+
"*.config.cjs",
|
|
39
|
+
"*.config.mjs",
|
|
40
|
+
"*.config.ts",
|
|
41
|
+
"tsconfig*.json",
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
ModuleOf = Callable[[str], str | None]
|
|
45
|
+
|
|
46
|
+
PLACEHOLDERS = frozenset({".gitkeep", ".keep"})
|
|
47
|
+
|
|
48
|
+
_TEST_DIRS = {"tests", "test", "spec", "specs", "__tests__"}
|
|
49
|
+
_TEST_NAME = re.compile(r"(?:^test[_.-]|[a-z0-9]Test$|[_.-]tests?$|\.spec$)")
|
|
50
|
+
_DATABASE_DIRS = {"database", "migrations", "db"}
|
|
51
|
+
# Order of the coarse commits: schema first, then code, tests, docs, config.
|
|
52
|
+
_COARSE_ORDER = ("database", "code", "tests", "docs", "config")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def coarse_kind(path: str) -> str:
|
|
56
|
+
"""A broad area: ``database``, ``code``, ``tests``, ``docs`` or ``config``."""
|
|
57
|
+
kind = kind_of(path)
|
|
58
|
+
if kind != "code":
|
|
59
|
+
return kind
|
|
60
|
+
pure = PurePosixPath(path)
|
|
61
|
+
parts = {p.lower() for p in pure.parts[:-1]}
|
|
62
|
+
if parts & _TEST_DIRS or _TEST_NAME.search(pure.stem):
|
|
63
|
+
return "tests"
|
|
64
|
+
if parts & _DATABASE_DIRS or pure.suffix.lower() == ".sql":
|
|
65
|
+
return "database"
|
|
66
|
+
return "code"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def kind_of(path: str) -> str:
|
|
70
|
+
"""``docs``, ``config`` or ``code`` (tests count as code of their module)."""
|
|
71
|
+
pure = PurePosixPath(path)
|
|
72
|
+
name = pure.name.lower()
|
|
73
|
+
parts = {p.lower() for p in pure.parts[:-1]}
|
|
74
|
+
if parts & {".github", ".circleci", ".gitlab"}:
|
|
75
|
+
return "config"
|
|
76
|
+
if name in _CONFIG_NAMES or any(fnmatch(name, p) for p in _CONFIG_PATTERNS):
|
|
77
|
+
return "config"
|
|
78
|
+
if pure.suffix.lower() in _DOC_SUFFIXES and (
|
|
79
|
+
parts & _DOC_DIRS or pure.stem.lower() in _DOC_NAMES or pure.suffix != ".txt"
|
|
80
|
+
):
|
|
81
|
+
return "docs"
|
|
82
|
+
if pure.suffix.lower() in _CONFIG_SUFFIXES:
|
|
83
|
+
return "config"
|
|
84
|
+
# The analyzer knows more (lock files, CI, build files, anything under docs/).
|
|
85
|
+
category = categorize(path)
|
|
86
|
+
if category in (FileCategory.CI, FileCategory.BUILD, FileCategory.CONFIG):
|
|
87
|
+
return "config"
|
|
88
|
+
if category is FileCategory.DOCS and pure.suffix.lower() != ".txt":
|
|
89
|
+
return "docs"
|
|
90
|
+
return "code"
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def group_paths(
|
|
94
|
+
paths: Sequence[str], module_of: ModuleOf, *, max_groups: int = MAX_GROUPS
|
|
95
|
+
) -> list[tuple[str, ...]]:
|
|
96
|
+
"""Group ``paths``; returns a single group when splitting is not worthwhile.
|
|
97
|
+
|
|
98
|
+
Placeholder files (``.gitkeep``) never form a commit of their own: they join
|
|
99
|
+
the biggest group, since they only exist to support the other changes.
|
|
100
|
+
"""
|
|
101
|
+
ordered = sorted(paths)
|
|
102
|
+
placeholders = [p for p in ordered if PurePosixPath(p).name in PLACEHOLDERS]
|
|
103
|
+
real = [p for p in ordered if p not in placeholders]
|
|
104
|
+
groups = _group_real(real, module_of, max_groups)
|
|
105
|
+
if not placeholders:
|
|
106
|
+
return groups
|
|
107
|
+
if not groups:
|
|
108
|
+
return [tuple(ordered)]
|
|
109
|
+
biggest = max(range(len(groups)), key=lambda i: (len(groups[i]), -i))
|
|
110
|
+
groups[biggest] = tuple(sorted((*groups[biggest], *placeholders)))
|
|
111
|
+
return groups
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _group_real(
|
|
115
|
+
ordered: list[str], module_of: ModuleOf, max_groups: int
|
|
116
|
+
) -> list[tuple[str, ...]]:
|
|
117
|
+
code: dict[str, list[str]] = {}
|
|
118
|
+
docs: list[str] = []
|
|
119
|
+
config: list[str] = []
|
|
120
|
+
for path in ordered:
|
|
121
|
+
kind = kind_of(path)
|
|
122
|
+
if kind == "docs":
|
|
123
|
+
docs.append(path)
|
|
124
|
+
elif kind == "config":
|
|
125
|
+
config.append(path)
|
|
126
|
+
else:
|
|
127
|
+
code.setdefault(module_of(path) or "", []).append(path)
|
|
128
|
+
groups = [tuple(code[key]) for key in sorted(code)]
|
|
129
|
+
groups += [tuple(g) for g in (docs, config) if g]
|
|
130
|
+
if len(groups) > max_groups:
|
|
131
|
+
# Too fine-grained (e.g. layered folders where every model is a "module"):
|
|
132
|
+
# fall back to broad areas instead of one catch-all commit.
|
|
133
|
+
coarse: dict[str, list[str]] = {}
|
|
134
|
+
for path in ordered:
|
|
135
|
+
coarse.setdefault(coarse_kind(path), []).append(path)
|
|
136
|
+
groups = [tuple(coarse[k]) for k in _COARSE_ORDER if k in coarse]
|
|
137
|
+
if len(groups) <= 1:
|
|
138
|
+
return [tuple(ordered)] if ordered else []
|
|
139
|
+
return groups
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""Per-project inactivity tracking.
|
|
2
|
+
|
|
3
|
+
A pure state machine with an injectable clock, so every timing rule can be
|
|
4
|
+
tested without sleeping. It is **not** thread-safe: :class:`InactivityDetector`
|
|
5
|
+
guards it with a lock.
|
|
6
|
+
|
|
7
|
+
Each project is in one of three states::
|
|
8
|
+
|
|
9
|
+
IDLE ──activity──▶ PENDING ──quiet for N seconds──▶ RUNNING ──finish──▶ IDLE
|
|
10
|
+
▲ └─activity restarts the countdown │
|
|
11
|
+
└──────── activity arrived while RUNNING ───┘
|
|
12
|
+
|
|
13
|
+
``RUNNING`` is what prevents two analyses from overlapping in one repository:
|
|
14
|
+
a running project is never handed out again until :meth:`finish` is called.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import time
|
|
20
|
+
from collections.abc import Callable, Mapping
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from enum import StrEnum
|
|
23
|
+
|
|
24
|
+
from gitgatekeeper.config import AppConfig
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ProjectState(StrEnum):
|
|
28
|
+
IDLE = "idle" # nothing pending
|
|
29
|
+
PENDING = "pending" # changes seen, waiting for the quiet period
|
|
30
|
+
RUNNING = "running" # eligible work is in progress
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True, slots=True)
|
|
34
|
+
class InactivitySnapshot:
|
|
35
|
+
"""Read-only view of one project, for status displays."""
|
|
36
|
+
|
|
37
|
+
project: str
|
|
38
|
+
state: ProjectState
|
|
39
|
+
threshold_seconds: float
|
|
40
|
+
idle_seconds: float | None # since the last relevant change; None when IDLE
|
|
41
|
+
remaining_seconds: float | None # until eligible; only while PENDING
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(slots=True)
|
|
45
|
+
class _Entry:
|
|
46
|
+
threshold: float
|
|
47
|
+
state: ProjectState = ProjectState.IDLE
|
|
48
|
+
last_activity: float = 0.0
|
|
49
|
+
activity_during_run: bool = False
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def due_at(self) -> float:
|
|
53
|
+
return self.last_activity + self.threshold
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def thresholds_from_config(config: AppConfig) -> dict[str, float]:
|
|
57
|
+
"""Inactivity window in seconds for every *enabled* project.
|
|
58
|
+
|
|
59
|
+
Per-project overrides win over the global value.
|
|
60
|
+
"""
|
|
61
|
+
return {
|
|
62
|
+
project.name: config.effective_inactivity_minutes(project) * 60.0
|
|
63
|
+
for project in config.projects
|
|
64
|
+
if project.enabled
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class InactivityTracker:
|
|
69
|
+
def __init__(
|
|
70
|
+
self,
|
|
71
|
+
thresholds: Mapping[str, float],
|
|
72
|
+
clock: Callable[[], float] = time.monotonic,
|
|
73
|
+
) -> None:
|
|
74
|
+
for name, seconds in thresholds.items():
|
|
75
|
+
if seconds <= 0:
|
|
76
|
+
raise ValueError(f"threshold for {name!r} must be positive")
|
|
77
|
+
self._clock = clock
|
|
78
|
+
self._entries = {name: _Entry(seconds) for name, seconds in thresholds.items()}
|
|
79
|
+
|
|
80
|
+
def record_activity(self, project: str, age: float = 0.0) -> None:
|
|
81
|
+
"""Register a relevant change in ``project``.
|
|
82
|
+
|
|
83
|
+
``age`` is how many seconds ago the change really happened (events are
|
|
84
|
+
delivered after a debounce delay); the clock never moves backwards.
|
|
85
|
+
"""
|
|
86
|
+
entry = self._entry(project)
|
|
87
|
+
at = self._clock() - max(age, 0.0)
|
|
88
|
+
if entry.state is ProjectState.IDLE:
|
|
89
|
+
entry.state = ProjectState.PENDING
|
|
90
|
+
entry.last_activity = at
|
|
91
|
+
return
|
|
92
|
+
entry.last_activity = max(entry.last_activity, at)
|
|
93
|
+
if entry.state is ProjectState.RUNNING:
|
|
94
|
+
entry.activity_during_run = True
|
|
95
|
+
|
|
96
|
+
def take_eligible(self) -> list[str]:
|
|
97
|
+
"""Move every project whose quiet period elapsed to RUNNING and return it."""
|
|
98
|
+
now = self._clock()
|
|
99
|
+
eligible = [
|
|
100
|
+
name
|
|
101
|
+
for name, entry in self._entries.items()
|
|
102
|
+
if entry.state is ProjectState.PENDING and entry.due_at <= now
|
|
103
|
+
]
|
|
104
|
+
for name in eligible:
|
|
105
|
+
entry = self._entries[name]
|
|
106
|
+
entry.state = ProjectState.RUNNING
|
|
107
|
+
entry.activity_during_run = False
|
|
108
|
+
return eligible
|
|
109
|
+
|
|
110
|
+
def finish(self, project: str) -> None:
|
|
111
|
+
"""Mark the run of ``project`` as over.
|
|
112
|
+
|
|
113
|
+
If the project changed again meanwhile it goes back to PENDING (its
|
|
114
|
+
countdown keeps running from that newer change); otherwise to IDLE.
|
|
115
|
+
"""
|
|
116
|
+
entry = self._entry(project)
|
|
117
|
+
if entry.state is not ProjectState.RUNNING:
|
|
118
|
+
raise RuntimeError(f"project {project!r} is not running")
|
|
119
|
+
entry.state = (
|
|
120
|
+
ProjectState.PENDING if entry.activity_during_run else ProjectState.IDLE
|
|
121
|
+
)
|
|
122
|
+
entry.activity_during_run = False
|
|
123
|
+
|
|
124
|
+
def next_due_in(self) -> float | None:
|
|
125
|
+
"""Seconds until the earliest PENDING project is eligible (``<= 0`` if due)."""
|
|
126
|
+
due = [
|
|
127
|
+
entry.due_at
|
|
128
|
+
for entry in self._entries.values()
|
|
129
|
+
if entry.state is ProjectState.PENDING
|
|
130
|
+
]
|
|
131
|
+
return min(due) - self._clock() if due else None
|
|
132
|
+
|
|
133
|
+
def snapshot(self) -> list[InactivitySnapshot]:
|
|
134
|
+
now = self._clock()
|
|
135
|
+
result: list[InactivitySnapshot] = []
|
|
136
|
+
for name, entry in self._entries.items():
|
|
137
|
+
idle = (
|
|
138
|
+
None if entry.state is ProjectState.IDLE else now - entry.last_activity
|
|
139
|
+
)
|
|
140
|
+
remaining = (
|
|
141
|
+
max(entry.due_at - now, 0.0)
|
|
142
|
+
if entry.state is ProjectState.PENDING
|
|
143
|
+
else None
|
|
144
|
+
)
|
|
145
|
+
result.append(
|
|
146
|
+
InactivitySnapshot(name, entry.state, entry.threshold, idle, remaining)
|
|
147
|
+
)
|
|
148
|
+
return result
|
|
149
|
+
|
|
150
|
+
def _entry(self, project: str) -> _Entry:
|
|
151
|
+
try:
|
|
152
|
+
return self._entries[project]
|
|
153
|
+
except KeyError:
|
|
154
|
+
raise KeyError(f"unknown project: {project!r}") from None
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
"""Single running instance of GitGatekeeper, and a safe way to stop it.
|
|
2
|
+
|
|
3
|
+
The running service holds an exclusive ``flock`` on ``gitgatekeeper.pid`` inside the
|
|
4
|
+
state directory and writes its pid there. The kernel drops the lock when the
|
|
5
|
+
process dies, so a crash never leaves a stale "running" state, and a second
|
|
6
|
+
``start`` is refused while the first is alive.
|
|
7
|
+
|
|
8
|
+
``stop`` only signals a process that holds that lock *and* looks like GitGatekeeper,
|
|
9
|
+
and it sends SIGTERM only: GitGatekeeper never escalates to SIGKILL on its own.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import fcntl
|
|
15
|
+
import os
|
|
16
|
+
import signal
|
|
17
|
+
import time
|
|
18
|
+
from collections.abc import Callable
|
|
19
|
+
from enum import StrEnum
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from types import TracebackType
|
|
22
|
+
|
|
23
|
+
PID_FILE_NAME = "gitgatekeeper.pid"
|
|
24
|
+
DEFAULT_STOP_TIMEOUT_SECONDS = 30.0
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class AlreadyRunningError(Exception):
|
|
28
|
+
def __init__(self, pid: int) -> None:
|
|
29
|
+
super().__init__(
|
|
30
|
+
f"GitGatekeeper is already running (pid {pid})"
|
|
31
|
+
if pid
|
|
32
|
+
else "GitGatekeeper is already running"
|
|
33
|
+
)
|
|
34
|
+
self.pid = pid
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class InstanceLock:
|
|
38
|
+
"""Exclusive, crash-safe claim on "the" GitGatekeeper instance of a state dir."""
|
|
39
|
+
|
|
40
|
+
def __init__(self, state_dir: Path) -> None:
|
|
41
|
+
self._path = state_dir / PID_FILE_NAME
|
|
42
|
+
self._fd: int | None = None
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def path(self) -> Path:
|
|
46
|
+
return self._path
|
|
47
|
+
|
|
48
|
+
def acquire(self) -> None:
|
|
49
|
+
if self._fd is not None:
|
|
50
|
+
raise RuntimeError("instance lock already acquired")
|
|
51
|
+
self._path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
52
|
+
fd = os.open(self._path, os.O_RDWR | os.O_CREAT | os.O_CLOEXEC, 0o600)
|
|
53
|
+
try:
|
|
54
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
55
|
+
except BlockingIOError:
|
|
56
|
+
pid = _read_pid(fd)
|
|
57
|
+
os.close(fd)
|
|
58
|
+
raise AlreadyRunningError(pid) from None
|
|
59
|
+
except BaseException:
|
|
60
|
+
os.close(fd)
|
|
61
|
+
raise
|
|
62
|
+
os.ftruncate(fd, 0)
|
|
63
|
+
os.write(fd, f"{os.getpid()}\n".encode())
|
|
64
|
+
self._fd = fd
|
|
65
|
+
|
|
66
|
+
def release(self) -> None:
|
|
67
|
+
if self._fd is None:
|
|
68
|
+
return
|
|
69
|
+
try:
|
|
70
|
+
os.ftruncate(self._fd, 0)
|
|
71
|
+
fcntl.flock(self._fd, fcntl.LOCK_UN)
|
|
72
|
+
finally:
|
|
73
|
+
os.close(self._fd)
|
|
74
|
+
self._fd = None
|
|
75
|
+
|
|
76
|
+
def __enter__(self) -> InstanceLock:
|
|
77
|
+
self.acquire()
|
|
78
|
+
return self
|
|
79
|
+
|
|
80
|
+
def __exit__(
|
|
81
|
+
self,
|
|
82
|
+
exc_type: type[BaseException] | None,
|
|
83
|
+
exc: BaseException | None,
|
|
84
|
+
traceback: TracebackType | None,
|
|
85
|
+
) -> None:
|
|
86
|
+
self.release()
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _read_pid(fd: int) -> int:
|
|
90
|
+
try:
|
|
91
|
+
text = os.pread(fd, 32, 0).decode("ascii", "replace").strip()
|
|
92
|
+
return int(text) if text.isdigit() else 0
|
|
93
|
+
except OSError:
|
|
94
|
+
return 0
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def running_pid(state_dir: Path) -> int | None:
|
|
98
|
+
"""Pid of the running instance (``0`` if unknown), or ``None`` if none runs."""
|
|
99
|
+
path = state_dir / PID_FILE_NAME
|
|
100
|
+
try:
|
|
101
|
+
fd = os.open(path, os.O_RDONLY | os.O_CLOEXEC)
|
|
102
|
+
except OSError:
|
|
103
|
+
return None
|
|
104
|
+
try:
|
|
105
|
+
try:
|
|
106
|
+
fcntl.flock(fd, fcntl.LOCK_SH | fcntl.LOCK_NB)
|
|
107
|
+
except BlockingIOError:
|
|
108
|
+
return _read_pid(fd)
|
|
109
|
+
fcntl.flock(fd, fcntl.LOCK_UN)
|
|
110
|
+
return None
|
|
111
|
+
finally:
|
|
112
|
+
os.close(fd)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def looks_like_gitgatekeeper(pid: int) -> bool:
|
|
116
|
+
"""True if process ``pid`` was started as GitGatekeeper (script, module or code)."""
|
|
117
|
+
try:
|
|
118
|
+
raw = Path(f"/proc/{pid}/cmdline").read_bytes()
|
|
119
|
+
except OSError:
|
|
120
|
+
return False
|
|
121
|
+
args = [a.decode("utf-8", "replace") for a in raw.split(b"\0") if a]
|
|
122
|
+
if not args:
|
|
123
|
+
return False
|
|
124
|
+
if Path(args[0]).name.lower() == "gitgatekeeper":
|
|
125
|
+
return True
|
|
126
|
+
# A mere mention is not enough: a folder called "GitGatekeeper" (a venv, a
|
|
127
|
+
# checkout) appears in the paths of unrelated programs such as pytest.
|
|
128
|
+
# Only the entry point itself, ``-m gitgatekeeper...`` or ``-c`` code count.
|
|
129
|
+
for previous, arg in zip(args, args[1:], strict=False):
|
|
130
|
+
if previous in ("-m", "-c") and "gitgatekeeper" in arg.lower():
|
|
131
|
+
return True
|
|
132
|
+
if Path(arg).name.lower() in ("gitgatekeeper", "gitgatekeeper.py"):
|
|
133
|
+
return True
|
|
134
|
+
return False
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class StopOutcome(StrEnum):
|
|
138
|
+
NOT_RUNNING = "not-running"
|
|
139
|
+
STOPPED = "stopped"
|
|
140
|
+
TIMEOUT = "timeout"
|
|
141
|
+
REFUSED = "refused" # the pid in the file is not a GitGatekeeper process
|
|
142
|
+
NO_PERMISSION = "no-permission"
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class SignalOutcome(StrEnum):
|
|
146
|
+
NOT_RUNNING = "not-running"
|
|
147
|
+
SENT = "sent"
|
|
148
|
+
REFUSED = "refused" # the pid in the file is not a GitGatekeeper process
|
|
149
|
+
NO_PERMISSION = "no-permission"
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def signal_running(
|
|
153
|
+
state_dir: Path,
|
|
154
|
+
signum: int,
|
|
155
|
+
*,
|
|
156
|
+
signaller: Callable[[int, int], None] = os.kill,
|
|
157
|
+
) -> tuple[SignalOutcome, int | None]:
|
|
158
|
+
"""Send ``signum`` to the running instance, after the same checks as a stop."""
|
|
159
|
+
pid = running_pid(state_dir)
|
|
160
|
+
if pid is None:
|
|
161
|
+
return SignalOutcome.NOT_RUNNING, None
|
|
162
|
+
if pid <= 1 or not looks_like_gitgatekeeper(pid):
|
|
163
|
+
return SignalOutcome.REFUSED, pid
|
|
164
|
+
try:
|
|
165
|
+
signaller(pid, signum)
|
|
166
|
+
except ProcessLookupError:
|
|
167
|
+
return SignalOutcome.NOT_RUNNING, pid
|
|
168
|
+
except PermissionError:
|
|
169
|
+
return SignalOutcome.NO_PERMISSION, pid
|
|
170
|
+
return SignalOutcome.SENT, pid
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def stop_running(
|
|
174
|
+
state_dir: Path,
|
|
175
|
+
*,
|
|
176
|
+
timeout: float = DEFAULT_STOP_TIMEOUT_SECONDS,
|
|
177
|
+
poll_interval: float = 0.1,
|
|
178
|
+
signaller: Callable[[int, int], None] = os.kill,
|
|
179
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
180
|
+
clock: Callable[[], float] = time.monotonic,
|
|
181
|
+
) -> tuple[StopOutcome, int | None]:
|
|
182
|
+
"""Ask the running instance to stop (SIGTERM) and wait for it to finish."""
|
|
183
|
+
pid = running_pid(state_dir)
|
|
184
|
+
if pid is None:
|
|
185
|
+
return StopOutcome.NOT_RUNNING, None
|
|
186
|
+
if pid <= 1 or not looks_like_gitgatekeeper(pid):
|
|
187
|
+
return StopOutcome.REFUSED, pid
|
|
188
|
+
try:
|
|
189
|
+
signaller(pid, signal.SIGTERM)
|
|
190
|
+
except ProcessLookupError:
|
|
191
|
+
return StopOutcome.STOPPED, pid
|
|
192
|
+
except PermissionError:
|
|
193
|
+
return StopOutcome.NO_PERMISSION, pid
|
|
194
|
+
deadline = clock() + timeout
|
|
195
|
+
while clock() < deadline:
|
|
196
|
+
if running_pid(state_dir) is None:
|
|
197
|
+
return StopOutcome.STOPPED, pid
|
|
198
|
+
sleep(poll_interval)
|
|
199
|
+
return (
|
|
200
|
+
StopOutcome.STOPPED if running_pid(state_dir) is None else StopOutcome.TIMEOUT,
|
|
201
|
+
pid,
|
|
202
|
+
)
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Per-repository exclusive lock shared by threads and processes.
|
|
2
|
+
|
|
3
|
+
Backed by ``flock`` on a file kept in GitGatekeeper's own state directory, never
|
|
4
|
+
inside the repository. The kernel drops the lock when its holder exits or
|
|
5
|
+
crashes, so a restart cannot be blocked by a stale lock.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import fcntl
|
|
11
|
+
import hashlib
|
|
12
|
+
import os
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from types import TracebackType
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class LockHeldError(Exception):
|
|
18
|
+
"""Another thread or process is already working on this repository."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def default_state_dir() -> Path:
|
|
22
|
+
"""Where GitGatekeeper keeps runtime state (lock files, later the history).
|
|
23
|
+
|
|
24
|
+
``$GITGATEKEEPER_STATE_DIR``, else ``$XDG_STATE_HOME/gitgatekeeper``, else
|
|
25
|
+
``~/.local/state/gitgatekeeper``.
|
|
26
|
+
"""
|
|
27
|
+
override = os.environ.get("GITGATEKEEPER_STATE_DIR")
|
|
28
|
+
if override:
|
|
29
|
+
return Path(override).expanduser()
|
|
30
|
+
base = os.environ.get("XDG_STATE_HOME")
|
|
31
|
+
root = Path(base) if base else Path.home() / ".local" / "state"
|
|
32
|
+
return root / "gitgatekeeper"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class RepositoryLock:
|
|
36
|
+
"""Context manager taking a non-blocking exclusive lock for one repository."""
|
|
37
|
+
|
|
38
|
+
def __init__(self, lock_dir: Path, repo: Path, purpose: str = "commit") -> None:
|
|
39
|
+
"""``purpose`` separates independent activities on one repository, so a
|
|
40
|
+
slow push does not stop the next commit (and vice versa)."""
|
|
41
|
+
resolved = repo.resolve()
|
|
42
|
+
digest = hashlib.sha256(str(resolved).encode("utf-8", "surrogateescape"))
|
|
43
|
+
stem = f"{resolved.name or 'repo'}-{digest.hexdigest()[:16]}"
|
|
44
|
+
suffix = "" if purpose == "commit" else f".{purpose}"
|
|
45
|
+
self._path = lock_dir / f"{stem}{suffix}.lock"
|
|
46
|
+
self._fd: int | None = None
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def path(self) -> Path:
|
|
50
|
+
return self._path
|
|
51
|
+
|
|
52
|
+
def acquire(self) -> None:
|
|
53
|
+
if self._fd is not None:
|
|
54
|
+
raise RuntimeError("lock already acquired")
|
|
55
|
+
self._path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
56
|
+
fd = os.open(self._path, os.O_RDWR | os.O_CREAT | os.O_CLOEXEC, 0o600)
|
|
57
|
+
try:
|
|
58
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
59
|
+
except BlockingIOError:
|
|
60
|
+
os.close(fd)
|
|
61
|
+
raise LockHeldError(f"repository is locked: {self._path}") from None
|
|
62
|
+
except BaseException:
|
|
63
|
+
os.close(fd)
|
|
64
|
+
raise
|
|
65
|
+
self._fd = fd
|
|
66
|
+
|
|
67
|
+
def release(self) -> None:
|
|
68
|
+
if self._fd is not None:
|
|
69
|
+
try:
|
|
70
|
+
fcntl.flock(self._fd, fcntl.LOCK_UN)
|
|
71
|
+
finally:
|
|
72
|
+
os.close(self._fd)
|
|
73
|
+
self._fd = None
|
|
74
|
+
|
|
75
|
+
def __enter__(self) -> RepositoryLock:
|
|
76
|
+
self.acquire()
|
|
77
|
+
return self
|
|
78
|
+
|
|
79
|
+
def __exit__(
|
|
80
|
+
self,
|
|
81
|
+
exc_type: type[BaseException] | None,
|
|
82
|
+
exc: BaseException | None,
|
|
83
|
+
traceback: TracebackType | None,
|
|
84
|
+
) -> None:
|
|
85
|
+
self.release()
|