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,561 @@
|
|
|
1
|
+
"""Deterministic, explainable commit message generator.
|
|
2
|
+
|
|
3
|
+
The commit *type* is inferred from evidence in the diff and every decision is
|
|
4
|
+
recorded in ``CommitMessage.reasons`` together with a confidence level. The
|
|
5
|
+
*description* never asserts more than the diff shows: it names files and
|
|
6
|
+
identifiers that appear in it, and uses a neutral verb (add/update/remove).
|
|
7
|
+
Breaking changes (``!``) are never inferred.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
from dataclasses import dataclass, replace
|
|
14
|
+
from pathlib import PurePosixPath
|
|
15
|
+
|
|
16
|
+
from gitgatekeeper.git.diff import DiffSummary, FileDiff
|
|
17
|
+
from gitgatekeeper.git.models import ChangeType
|
|
18
|
+
from gitgatekeeper.intelligence.analysis import (
|
|
19
|
+
FIX_PATTERN,
|
|
20
|
+
PERF_PATTERN,
|
|
21
|
+
FileCategory,
|
|
22
|
+
categorize,
|
|
23
|
+
extract_css_names,
|
|
24
|
+
extract_definitions,
|
|
25
|
+
extract_headings,
|
|
26
|
+
has_signal,
|
|
27
|
+
is_comment_only,
|
|
28
|
+
is_formatting_only,
|
|
29
|
+
is_stylesheet,
|
|
30
|
+
)
|
|
31
|
+
from gitgatekeeper.intelligence.message import (
|
|
32
|
+
MAX_HEADER_LENGTH,
|
|
33
|
+
CommitMessage,
|
|
34
|
+
CommitType,
|
|
35
|
+
Confidence,
|
|
36
|
+
)
|
|
37
|
+
from gitgatekeeper.intelligence.profile import ProjectProfile
|
|
38
|
+
|
|
39
|
+
_CATEGORY_TYPES = {
|
|
40
|
+
FileCategory.DOCS: CommitType.DOCS,
|
|
41
|
+
FileCategory.TEST: CommitType.TEST,
|
|
42
|
+
FileCategory.CI: CommitType.CI,
|
|
43
|
+
FileCategory.BUILD: CommitType.BUILD,
|
|
44
|
+
FileCategory.CONFIG: CommitType.CHORE,
|
|
45
|
+
}
|
|
46
|
+
# Tie-break order when non-source categories weigh the same.
|
|
47
|
+
_CATEGORY_PRIORITY = (
|
|
48
|
+
FileCategory.BUILD,
|
|
49
|
+
FileCategory.CI,
|
|
50
|
+
FileCategory.TEST,
|
|
51
|
+
FileCategory.DOCS,
|
|
52
|
+
FileCategory.CONFIG,
|
|
53
|
+
)
|
|
54
|
+
_GENERIC_DIRS = frozenset({"src", "lib", "app", "tests", "test", "docs", "doc"})
|
|
55
|
+
_NEW = (ChangeType.ADDED, ChangeType.COPIED)
|
|
56
|
+
_DOMINANT_SHARE = 0.6 # a module must own this share of the change to be the scope
|
|
57
|
+
_MAX_DETAIL_NAMES = 5
|
|
58
|
+
_MAX_BODY_LINE = 100
|
|
59
|
+
_MARKDOWN = (".md", ".rst", ".adoc")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(frozen=True, slots=True)
|
|
63
|
+
class _Decision:
|
|
64
|
+
type: CommitType
|
|
65
|
+
confidence: Confidence
|
|
66
|
+
verb: str
|
|
67
|
+
targets: list[str]
|
|
68
|
+
reasons: list[str]
|
|
69
|
+
suffix: str = ""
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
_MIGRATION_DIRS = frozenset({"migrations", "migrate"})
|
|
73
|
+
_MIGRATION_SUFFIXES = frozenset({".php", ".py", ".rb", ".sql", ".js", ".ts", ".cs"})
|
|
74
|
+
_PLURAL_SUFFIXES = {" sections": " section", " migrations": " migration"}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _is_migration(path: str) -> bool:
|
|
78
|
+
pure = PurePosixPath(path)
|
|
79
|
+
return pure.suffix.lower() in _MIGRATION_SUFFIXES and any(
|
|
80
|
+
part.lower() in _MIGRATION_DIRS for part in pure.parent.parts
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _migration_name(path: str) -> str:
|
|
85
|
+
"""``2026_01_01_000000_create_orders_table.php`` -> ``orders table``."""
|
|
86
|
+
stem = PurePosixPath(path).stem
|
|
87
|
+
name = re.sub(r"^[\d_\-]+(?=[A-Za-z])", "", stem) or stem
|
|
88
|
+
name = name.replace("_", " ").replace("-", " ").strip()
|
|
89
|
+
for noise in ("create ", "add "): # the verb of the message already says it
|
|
90
|
+
if name.startswith(noise) and len(name) > len(noise):
|
|
91
|
+
name = name[len(noise) :]
|
|
92
|
+
break
|
|
93
|
+
return name
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _humanize(path: str, *, strip_test: bool = False) -> str:
|
|
97
|
+
pure = PurePosixPath(path)
|
|
98
|
+
stem = pure.stem or path
|
|
99
|
+
if stem.endswith(".d") and pure.suffix in (".ts", ".mts", ".cts"):
|
|
100
|
+
stem = stem[:-2] or stem # schema.d.ts is "schema"
|
|
101
|
+
if strip_test:
|
|
102
|
+
stem = stem.removeprefix("test_").removesuffix("_test") or stem
|
|
103
|
+
stem = stem.removesuffix("Test") or stem # PHP/Java/C#: InvoiceTest
|
|
104
|
+
return stem.replace("_", " ").replace("-", " ")
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def derive_scope(paths: list[str]) -> str | None:
|
|
108
|
+
"""Scope = first meaningful directory shared by every path, if any."""
|
|
109
|
+
directories = [PurePosixPath(p).parent.parts for p in paths]
|
|
110
|
+
if not directories:
|
|
111
|
+
return None
|
|
112
|
+
common: list[str] = []
|
|
113
|
+
for level in zip(*directories, strict=False):
|
|
114
|
+
if len(set(level)) != 1:
|
|
115
|
+
break
|
|
116
|
+
common.append(level[0])
|
|
117
|
+
if common and common[0].startswith("."):
|
|
118
|
+
return None # .github/, .circleci/ ...: tooling folders make poor scopes
|
|
119
|
+
if common and common[0] == "src":
|
|
120
|
+
common = common[2:] # src/<package>/...
|
|
121
|
+
meaningful = [
|
|
122
|
+
part
|
|
123
|
+
for part in common
|
|
124
|
+
if part.lower() not in _GENERIC_DIRS and not part.startswith(".")
|
|
125
|
+
]
|
|
126
|
+
if not meaningful:
|
|
127
|
+
return None
|
|
128
|
+
scope = "".join(c if c.isalnum() or c in "._-" else "-" for c in meaningful[0])
|
|
129
|
+
return scope.lower().strip("-._") or None
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _verb_for(files: list[FileDiff]) -> str:
|
|
133
|
+
statuses = {f.status for f in files}
|
|
134
|
+
if statuses <= set(_NEW):
|
|
135
|
+
return "add"
|
|
136
|
+
if statuses == {ChangeType.DELETED}:
|
|
137
|
+
return "remove"
|
|
138
|
+
if statuses == {ChangeType.RENAMED}:
|
|
139
|
+
return "rename"
|
|
140
|
+
return "update"
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _dedupe(names: list[str]) -> list[str]:
|
|
144
|
+
return list(dict.fromkeys(names))
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _css_base(name: str) -> str:
|
|
148
|
+
return name.split("__")[0].split("-")[0] or name
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _css_names(lines: tuple[str, ...]) -> list[str]:
|
|
152
|
+
"""Selector names for a message: exact when few, grouped by prefix when many."""
|
|
153
|
+
names = extract_css_names(lines)
|
|
154
|
+
if len(names) <= 2:
|
|
155
|
+
return names
|
|
156
|
+
return _dedupe([_css_base(n) for n in names])
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _css_target(f: FileDiff) -> str | None:
|
|
160
|
+
""" "heatmap and stats styles" from the selectors a stylesheet change touches."""
|
|
161
|
+
bases = _css_names(f.added_lines or f.removed_lines)
|
|
162
|
+
if not bases:
|
|
163
|
+
return None
|
|
164
|
+
shown = bases[:2]
|
|
165
|
+
more = len(bases) - len(shown)
|
|
166
|
+
phrase = " and ".join(shown)
|
|
167
|
+
return f"{phrase} and {more} more styles" if more > 0 else f"{phrase} styles"
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _new_definition_names(f: FileDiff) -> list[str]:
|
|
171
|
+
"""Public classes/types first, then functions, defined by an added file."""
|
|
172
|
+
definitions = [d for d in extract_definitions(f.added_lines) if d.is_public]
|
|
173
|
+
ordered = [d for d in definitions if d.kind != "function"] + [
|
|
174
|
+
d for d in definitions if d.kind == "function"
|
|
175
|
+
]
|
|
176
|
+
return _dedupe([d.name for d in ordered])
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _comments_target(files: list[FileDiff]) -> str:
|
|
180
|
+
names = _dedupe([PurePosixPath(f.path).name for f in files])
|
|
181
|
+
shown = " and ".join(names[:2])
|
|
182
|
+
more = len(names) - 2
|
|
183
|
+
return f"comments in {shown}" + (f" and {more} more" if more > 0 else "")
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
PLACEHOLDERS = frozenset({".gitkeep", ".keep"})
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _file_targets(f: FileDiff) -> list[str]:
|
|
190
|
+
"""The most specific names for what changed in one source file."""
|
|
191
|
+
if is_stylesheet(f.path):
|
|
192
|
+
target = _css_target(f)
|
|
193
|
+
if target:
|
|
194
|
+
return [target]
|
|
195
|
+
stem = _humanize(f.path)
|
|
196
|
+
return [stem if stem.endswith(("style", "styles")) else stem + " styles"]
|
|
197
|
+
if f.content_read and f.status in _NEW:
|
|
198
|
+
# A new file is best named by its classes/types. Loose function names
|
|
199
|
+
# ("run", "main") say less than the file name, so they stay in the body.
|
|
200
|
+
names = [
|
|
201
|
+
d.name
|
|
202
|
+
for d in extract_definitions(f.added_lines)
|
|
203
|
+
if d.is_public and d.kind != "function"
|
|
204
|
+
]
|
|
205
|
+
if names:
|
|
206
|
+
return _dedupe(names)[:3]
|
|
207
|
+
if f.touched:
|
|
208
|
+
return list(f.touched)
|
|
209
|
+
return [_humanize(f.path)]
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
class RuleBasedGenerator:
|
|
213
|
+
"""Builds Conventional Commit messages from a staged :class:`DiffSummary`."""
|
|
214
|
+
|
|
215
|
+
def __init__(
|
|
216
|
+
self,
|
|
217
|
+
*,
|
|
218
|
+
max_header_length: int = MAX_HEADER_LENGTH,
|
|
219
|
+
include_body: bool = True,
|
|
220
|
+
max_body_files: int = 10,
|
|
221
|
+
profile: ProjectProfile | None = None,
|
|
222
|
+
) -> None:
|
|
223
|
+
self._profile = profile
|
|
224
|
+
self._max_header = max_header_length
|
|
225
|
+
self._include_body = include_body
|
|
226
|
+
self._max_body_files = max_body_files
|
|
227
|
+
|
|
228
|
+
def generate(self, summary: DiffSummary) -> CommitMessage:
|
|
229
|
+
if not summary.files:
|
|
230
|
+
raise ValueError("cannot describe an empty diff")
|
|
231
|
+
|
|
232
|
+
categories = {f.path: categorize(f.path) for f in summary.files}
|
|
233
|
+
source = [f for f in summary.files if categories[f.path] is FileCategory.SOURCE]
|
|
234
|
+
# Placeholders (.gitkeep) say nothing about the change; name the rest.
|
|
235
|
+
meaningful = [
|
|
236
|
+
f for f in source if f.path.rsplit("/", 1)[-1] not in PLACEHOLDERS
|
|
237
|
+
]
|
|
238
|
+
placeholder_only = bool(source) and not meaningful
|
|
239
|
+
source = meaningful or source
|
|
240
|
+
if placeholder_only:
|
|
241
|
+
added = all(f.status in _NEW for f in source)
|
|
242
|
+
decision = _Decision(
|
|
243
|
+
CommitType.CHORE,
|
|
244
|
+
Confidence.HIGH,
|
|
245
|
+
"add" if added else "update",
|
|
246
|
+
_dedupe([PurePosixPath(f.path).name for f in source]),
|
|
247
|
+
["only placeholder files changed"],
|
|
248
|
+
)
|
|
249
|
+
primary = source
|
|
250
|
+
elif source:
|
|
251
|
+
decision = self._decide_source(source)
|
|
252
|
+
if all(_is_migration(f.path) for f in source):
|
|
253
|
+
names = _dedupe(
|
|
254
|
+
[
|
|
255
|
+
_migration_name(f.path)
|
|
256
|
+
for f in sorted(source, key=lambda f: f.path)
|
|
257
|
+
]
|
|
258
|
+
)
|
|
259
|
+
decision = replace(
|
|
260
|
+
decision,
|
|
261
|
+
targets=names,
|
|
262
|
+
suffix=" migrations", # _subject singularizes it when needed
|
|
263
|
+
)
|
|
264
|
+
primary = source
|
|
265
|
+
else:
|
|
266
|
+
decision, primary = self._decide_other(summary.files, categories)
|
|
267
|
+
|
|
268
|
+
scope = self._scope(primary, source_group=bool(source))
|
|
269
|
+
subject = self._subject(decision, scope)
|
|
270
|
+
return CommitMessage(
|
|
271
|
+
type=decision.type,
|
|
272
|
+
subject=subject,
|
|
273
|
+
scope=scope,
|
|
274
|
+
body=self._body(summary.files) if self._include_body else "",
|
|
275
|
+
confidence=decision.confidence,
|
|
276
|
+
reasons=tuple(decision.reasons),
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
# -- type decision -----------------------------------------------------
|
|
280
|
+
def _decide_source(self, files: list[FileDiff]) -> _Decision:
|
|
281
|
+
# The biggest changes name the commit; sorted() is stable, so equal
|
|
282
|
+
# sizes keep their original (alphabetical) order.
|
|
283
|
+
files = sorted(files, key=lambda f: -((f.added or 0) + (f.removed or 0)))
|
|
284
|
+
stems = _dedupe([_humanize(f.path) for f in files])
|
|
285
|
+
specific = _dedupe([t for f in files for t in _file_targets(f)])
|
|
286
|
+
new_files = [f for f in files if f.status in _NEW]
|
|
287
|
+
modified = [f for f in files if f.status not in (*_NEW, ChangeType.DELETED)]
|
|
288
|
+
readable = all(f.content_read or f.binary for f in modified)
|
|
289
|
+
|
|
290
|
+
if all(
|
|
291
|
+
f.status is ChangeType.RENAMED and not (f.added or f.removed) for f in files
|
|
292
|
+
):
|
|
293
|
+
moved = all(
|
|
294
|
+
PurePosixPath(f.old_path or f.path).name == PurePosixPath(f.path).name
|
|
295
|
+
for f in files
|
|
296
|
+
)
|
|
297
|
+
return _Decision(
|
|
298
|
+
CommitType.REFACTOR,
|
|
299
|
+
Confidence.HIGH,
|
|
300
|
+
"move" if moved else "rename",
|
|
301
|
+
_dedupe([self._rename_target(f, moved) for f in files]),
|
|
302
|
+
["source files were only renamed or moved"],
|
|
303
|
+
)
|
|
304
|
+
if all(f.status is ChangeType.DELETED for f in files):
|
|
305
|
+
return _Decision(
|
|
306
|
+
CommitType.REFACTOR,
|
|
307
|
+
Confidence.MEDIUM,
|
|
308
|
+
"remove",
|
|
309
|
+
stems,
|
|
310
|
+
["source files were deleted"],
|
|
311
|
+
)
|
|
312
|
+
if new_files:
|
|
313
|
+
return _Decision(
|
|
314
|
+
CommitType.FEAT,
|
|
315
|
+
Confidence.HIGH,
|
|
316
|
+
"add",
|
|
317
|
+
_dedupe([t for f in new_files for t in _file_targets(f)]),
|
|
318
|
+
["new source files were added"],
|
|
319
|
+
)
|
|
320
|
+
|
|
321
|
+
reasons: list[str] = []
|
|
322
|
+
if not readable:
|
|
323
|
+
reasons.append("diff content was not available for every file")
|
|
324
|
+
else:
|
|
325
|
+
if all(
|
|
326
|
+
is_formatting_only(f.added_lines, f.removed_lines) for f in modified
|
|
327
|
+
):
|
|
328
|
+
return _Decision(
|
|
329
|
+
CommitType.STYLE,
|
|
330
|
+
Confidence.HIGH,
|
|
331
|
+
"update",
|
|
332
|
+
stems,
|
|
333
|
+
["only whitespace changed"],
|
|
334
|
+
)
|
|
335
|
+
if all(
|
|
336
|
+
is_comment_only(f.path, f.added_lines, f.removed_lines)
|
|
337
|
+
for f in modified
|
|
338
|
+
):
|
|
339
|
+
return _Decision(
|
|
340
|
+
CommitType.DOCS,
|
|
341
|
+
Confidence.MEDIUM,
|
|
342
|
+
"update",
|
|
343
|
+
[_comments_target(modified)],
|
|
344
|
+
["only comments changed"],
|
|
345
|
+
)
|
|
346
|
+
added = [line for f in modified for line in f.added_lines]
|
|
347
|
+
if has_signal(added, FIX_PATTERN):
|
|
348
|
+
return _Decision(
|
|
349
|
+
CommitType.FIX,
|
|
350
|
+
Confidence.MEDIUM,
|
|
351
|
+
"update",
|
|
352
|
+
specific,
|
|
353
|
+
["added lines mention a fix (bug, crash, regression, ...)"],
|
|
354
|
+
)
|
|
355
|
+
if has_signal(added, PERF_PATTERN):
|
|
356
|
+
return _Decision(
|
|
357
|
+
CommitType.PERF,
|
|
358
|
+
Confidence.MEDIUM,
|
|
359
|
+
"update",
|
|
360
|
+
specific,
|
|
361
|
+
["added lines mention performance work"],
|
|
362
|
+
)
|
|
363
|
+
added_total = sum(f.added or 0 for f in modified)
|
|
364
|
+
removed_total = sum(f.removed or 0 for f in modified)
|
|
365
|
+
names = self._new_public_definitions(modified)
|
|
366
|
+
if removed_total >= 30 and removed_total >= 3 * added_total:
|
|
367
|
+
return _Decision(
|
|
368
|
+
CommitType.REFACTOR,
|
|
369
|
+
Confidence.MEDIUM,
|
|
370
|
+
"simplify",
|
|
371
|
+
names or specific,
|
|
372
|
+
["the change mostly removes code"],
|
|
373
|
+
)
|
|
374
|
+
if names:
|
|
375
|
+
return _Decision(
|
|
376
|
+
CommitType.FEAT,
|
|
377
|
+
Confidence.MEDIUM,
|
|
378
|
+
"add",
|
|
379
|
+
names,
|
|
380
|
+
["new public definitions were added to existing files"],
|
|
381
|
+
)
|
|
382
|
+
reasons.append("no structural or keyword evidence in the diff")
|
|
383
|
+
|
|
384
|
+
removed = any(f.removed for f in modified)
|
|
385
|
+
reasons.append("fell back to the shape of the change")
|
|
386
|
+
return _Decision(
|
|
387
|
+
CommitType.REFACTOR if removed else CommitType.FEAT,
|
|
388
|
+
Confidence.LOW,
|
|
389
|
+
"update",
|
|
390
|
+
specific,
|
|
391
|
+
reasons,
|
|
392
|
+
)
|
|
393
|
+
|
|
394
|
+
@staticmethod
|
|
395
|
+
def _new_public_definitions(files: list[FileDiff]) -> list[str]:
|
|
396
|
+
names: list[str] = []
|
|
397
|
+
for f in files:
|
|
398
|
+
removed = {d.name for d in extract_definitions(f.removed_lines)}
|
|
399
|
+
names += [
|
|
400
|
+
d.name
|
|
401
|
+
for d in extract_definitions(f.added_lines)
|
|
402
|
+
if d.is_public and d.name not in removed
|
|
403
|
+
]
|
|
404
|
+
return _dedupe(names)
|
|
405
|
+
|
|
406
|
+
@staticmethod
|
|
407
|
+
def _rename_target(f: FileDiff, moved: bool) -> str:
|
|
408
|
+
new = PurePosixPath(f.path).name
|
|
409
|
+
if moved:
|
|
410
|
+
return new
|
|
411
|
+
return f"{PurePosixPath(f.old_path or f.path).name} to {new}"
|
|
412
|
+
|
|
413
|
+
def _decide_other(
|
|
414
|
+
self, files: tuple[FileDiff, ...], categories: dict[str, FileCategory]
|
|
415
|
+
) -> tuple[_Decision, list[FileDiff]]:
|
|
416
|
+
weight: dict[FileCategory, int] = {}
|
|
417
|
+
for f in files:
|
|
418
|
+
weight[categories[f.path]] = weight.get(categories[f.path], 0) + max(
|
|
419
|
+
1, (f.added or 0) + (f.removed or 0)
|
|
420
|
+
)
|
|
421
|
+
winner = max(
|
|
422
|
+
weight,
|
|
423
|
+
key=lambda c: (weight[c], -_CATEGORY_PRIORITY.index(c)),
|
|
424
|
+
)
|
|
425
|
+
group = [f for f in files if categories[f.path] is winner]
|
|
426
|
+
verb = _verb_for(group)
|
|
427
|
+
if winner is FileCategory.TEST:
|
|
428
|
+
targets = _dedupe([_humanize(f.path, strip_test=True) for f in group])
|
|
429
|
+
suffix = " tests"
|
|
430
|
+
elif winner is FileCategory.DOCS and (
|
|
431
|
+
headings := _dedupe([h for f in group for h in self._headings(f)])
|
|
432
|
+
):
|
|
433
|
+
targets, verb = headings, "document"
|
|
434
|
+
suffix = " sections"
|
|
435
|
+
else:
|
|
436
|
+
targets = _dedupe([PurePosixPath(f.path).name for f in group])
|
|
437
|
+
suffix = ""
|
|
438
|
+
single = len(weight) == 1
|
|
439
|
+
reasons = [f"all changed files are {winner.value} files"]
|
|
440
|
+
if not single:
|
|
441
|
+
reasons = [f"mixed non-source changes; {winner.value} files weigh most"]
|
|
442
|
+
return (
|
|
443
|
+
_Decision(
|
|
444
|
+
_CATEGORY_TYPES[winner],
|
|
445
|
+
Confidence.HIGH if single else Confidence.MEDIUM,
|
|
446
|
+
verb,
|
|
447
|
+
targets,
|
|
448
|
+
reasons,
|
|
449
|
+
suffix,
|
|
450
|
+
),
|
|
451
|
+
group,
|
|
452
|
+
)
|
|
453
|
+
|
|
454
|
+
@staticmethod
|
|
455
|
+
def _headings(f: FileDiff) -> list[str]:
|
|
456
|
+
if not f.content_read or f.status is not ChangeType.MODIFIED:
|
|
457
|
+
return []
|
|
458
|
+
if not f.path.lower().endswith(_MARKDOWN):
|
|
459
|
+
return []
|
|
460
|
+
return extract_headings(f.added_lines)
|
|
461
|
+
|
|
462
|
+
# -- scope --------------------------------------------------------------
|
|
463
|
+
def _scope(self, primary: list[FileDiff], *, source_group: bool) -> str | None:
|
|
464
|
+
paths = [f.path for f in primary]
|
|
465
|
+
if self._profile is not None and source_group:
|
|
466
|
+
weight: dict[str, int] = {}
|
|
467
|
+
for f in primary:
|
|
468
|
+
module = self._profile.module_for(f.path)
|
|
469
|
+
if module:
|
|
470
|
+
weight[module] = weight.get(module, 0) + max(
|
|
471
|
+
1, (f.added or 0) + (f.removed or 0)
|
|
472
|
+
)
|
|
473
|
+
total = sum(max(1, (f.added or 0) + (f.removed or 0)) for f in primary)
|
|
474
|
+
if weight:
|
|
475
|
+
module, share = max(weight.items(), key=lambda kv: (kv[1], kv[0]))
|
|
476
|
+
if share / total >= _DOMINANT_SHARE:
|
|
477
|
+
return module
|
|
478
|
+
return derive_scope(paths)
|
|
479
|
+
|
|
480
|
+
# -- text ---------------------------------------------------------------
|
|
481
|
+
def _subject(self, decision: _Decision, scope: str | None) -> str:
|
|
482
|
+
prefix_length = len(decision.type.value) + (len(scope) + 2 if scope else 0) + 2
|
|
483
|
+
budget = self._max_header - prefix_length
|
|
484
|
+
targets = decision.targets
|
|
485
|
+
total = len(targets)
|
|
486
|
+
|
|
487
|
+
for shown in (min(total, 3), 2, 1):
|
|
488
|
+
names = targets[:shown]
|
|
489
|
+
rest = total - len(names)
|
|
490
|
+
phrase = (
|
|
491
|
+
names[0]
|
|
492
|
+
if len(names) == 1
|
|
493
|
+
else f"{', '.join(names[:-1])} and {names[-1]}"
|
|
494
|
+
)
|
|
495
|
+
if rest > 0:
|
|
496
|
+
phrase = (
|
|
497
|
+
f"{phrase} and {rest} more"
|
|
498
|
+
if len(names) == 1
|
|
499
|
+
else f"{', '.join(names)} and {rest} more"
|
|
500
|
+
)
|
|
501
|
+
suffix = decision.suffix
|
|
502
|
+
if suffix in _PLURAL_SUFFIXES:
|
|
503
|
+
# "A", "A and 1 more section", "A, B and 1 more section"
|
|
504
|
+
if rest == 1 or (rest == 0 and len(names) == 1):
|
|
505
|
+
suffix = _PLURAL_SUFFIXES[suffix]
|
|
506
|
+
candidate = f"{decision.verb} {phrase}{suffix}"
|
|
507
|
+
if len(candidate) <= budget:
|
|
508
|
+
return candidate
|
|
509
|
+
|
|
510
|
+
counted = f"{decision.verb} {total} file{'s' if total != 1 else ''}"
|
|
511
|
+
if len(counted) <= budget:
|
|
512
|
+
return counted
|
|
513
|
+
return counted[:budget].rstrip()
|
|
514
|
+
|
|
515
|
+
def _body(self, files: tuple[FileDiff, ...]) -> str:
|
|
516
|
+
if len(files) < 2:
|
|
517
|
+
only = files[0] if files else None
|
|
518
|
+
names = self._detail_names(only) if only else []
|
|
519
|
+
if len(names) <= 3:
|
|
520
|
+
return ""
|
|
521
|
+
lines = [f"- {self._describe(f)}" for f in files[: self._max_body_files]]
|
|
522
|
+
hidden = len(files) - self._max_body_files
|
|
523
|
+
if hidden > 0:
|
|
524
|
+
lines.append(f"- and {hidden} more files")
|
|
525
|
+
return "\n".join(lines)
|
|
526
|
+
|
|
527
|
+
def _detail_names(self, f: FileDiff) -> list[str]:
|
|
528
|
+
"""Identifiers (or headings, or selectors) that explain a file's change."""
|
|
529
|
+
if f.binary or f.sensitive or not f.content_read:
|
|
530
|
+
return []
|
|
531
|
+
if f.status is ChangeType.DELETED:
|
|
532
|
+
return [d.name for d in extract_definitions(f.removed_lines)]
|
|
533
|
+
if is_stylesheet(f.path):
|
|
534
|
+
return _css_names(f.added_lines)
|
|
535
|
+
if f.path.lower().endswith(_MARKDOWN):
|
|
536
|
+
return self._headings(f)
|
|
537
|
+
if categorize(f.path) is not FileCategory.SOURCE:
|
|
538
|
+
return []
|
|
539
|
+
if f.status in _NEW:
|
|
540
|
+
return _new_definition_names(f)
|
|
541
|
+
return list(f.touched)
|
|
542
|
+
|
|
543
|
+
def _describe(self, f: FileDiff) -> str:
|
|
544
|
+
if f.status is ChangeType.RENAMED and f.old_path:
|
|
545
|
+
return f"renamed {f.old_path} -> {f.path}"
|
|
546
|
+
word = {
|
|
547
|
+
ChangeType.ADDED: "added",
|
|
548
|
+
ChangeType.COPIED: "added",
|
|
549
|
+
ChangeType.DELETED: "deleted",
|
|
550
|
+
}.get(f.status, "modified")
|
|
551
|
+
if f.binary:
|
|
552
|
+
return f"{word} {f.path} (binary)"
|
|
553
|
+
line = f"{word} {f.path} (+{f.added or 0}/-{f.removed or 0})"
|
|
554
|
+
names = self._detail_names(f)
|
|
555
|
+
if names:
|
|
556
|
+
shown = ", ".join(names[:_MAX_DETAIL_NAMES])
|
|
557
|
+
more = len(names) - _MAX_DETAIL_NAMES
|
|
558
|
+
line += f": {shown}" + (f" and {more} more" if more > 0 else "")
|
|
559
|
+
if len(line) > _MAX_BODY_LINE:
|
|
560
|
+
line = line[: _MAX_BODY_LINE - 3].rstrip() + "..."
|
|
561
|
+
return line
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Structured (JSON lines) logging with credentials masked.
|
|
2
|
+
|
|
3
|
+
The service writes ``logs/gitgatekeeper.log`` in the state directory: one JSON object
|
|
4
|
+
per line, rotated by size, readable only by the user. Whatever is logged, any
|
|
5
|
+
``user:secret@`` inside a URL is masked before it reaches a handler.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import logging
|
|
12
|
+
import logging.handlers
|
|
13
|
+
import os
|
|
14
|
+
import sys
|
|
15
|
+
from datetime import UTC, datetime
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
from gitgatekeeper.core.push_engine import mask_url_credentials
|
|
19
|
+
|
|
20
|
+
LOG_DIR_NAME = "logs"
|
|
21
|
+
LOG_FILE_NAME = "gitgatekeeper.log"
|
|
22
|
+
MAX_LOG_BYTES = 5 * 1024 * 1024
|
|
23
|
+
LOG_BACKUPS = 3
|
|
24
|
+
_HANDLER_TAG = "_gitgatekeeper_handler"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class JsonFormatter(logging.Formatter):
|
|
28
|
+
def format(self, record: logging.LogRecord) -> str:
|
|
29
|
+
entry: dict[str, str] = {
|
|
30
|
+
"ts": datetime.fromtimestamp(record.created, UTC).isoformat(
|
|
31
|
+
timespec="milliseconds"
|
|
32
|
+
),
|
|
33
|
+
"level": record.levelname,
|
|
34
|
+
"logger": record.name,
|
|
35
|
+
"message": mask_url_credentials(record.getMessage()),
|
|
36
|
+
}
|
|
37
|
+
if record.exc_info:
|
|
38
|
+
entry["exception"] = mask_url_credentials(
|
|
39
|
+
self.formatException(record.exc_info)
|
|
40
|
+
)
|
|
41
|
+
return json.dumps(entry, ensure_ascii=False)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class MaskingFormatter(logging.Formatter):
|
|
45
|
+
def format(self, record: logging.LogRecord) -> str:
|
|
46
|
+
return mask_url_credentials(super().format(record))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def parse_level(name: str) -> int:
|
|
50
|
+
level = logging.getLevelName(name.strip().upper())
|
|
51
|
+
if not isinstance(level, int):
|
|
52
|
+
raise ValueError(f"unknown log level: {name!r}")
|
|
53
|
+
return level
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def log_file_path(state_dir: Path) -> Path:
|
|
57
|
+
return state_dir / LOG_DIR_NAME / LOG_FILE_NAME
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def configure_logging(
|
|
61
|
+
state_dir: Path, level: str | int = "INFO", *, console: bool = False
|
|
62
|
+
) -> Path:
|
|
63
|
+
"""Send GitGatekeeper's logs to the rotating JSON file (and optionally stderr).
|
|
64
|
+
|
|
65
|
+
Safe to call more than once: earlier GitGatekeeper handlers are replaced.
|
|
66
|
+
Returns the log file path.
|
|
67
|
+
"""
|
|
68
|
+
resolved = parse_level(level) if isinstance(level, str) else level
|
|
69
|
+
path = log_file_path(state_dir)
|
|
70
|
+
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
71
|
+
os.close(os.open(path, os.O_WRONLY | os.O_CREAT | os.O_CLOEXEC, 0o600))
|
|
72
|
+
|
|
73
|
+
reset_logging()
|
|
74
|
+
logger = logging.getLogger("gitgatekeeper")
|
|
75
|
+
logger.setLevel(resolved)
|
|
76
|
+
|
|
77
|
+
file_handler = logging.handlers.RotatingFileHandler(
|
|
78
|
+
path, maxBytes=MAX_LOG_BYTES, backupCount=LOG_BACKUPS, encoding="utf-8"
|
|
79
|
+
)
|
|
80
|
+
file_handler.setFormatter(JsonFormatter())
|
|
81
|
+
_tag(file_handler)
|
|
82
|
+
logger.addHandler(file_handler)
|
|
83
|
+
|
|
84
|
+
if console:
|
|
85
|
+
stream = logging.StreamHandler(sys.stderr)
|
|
86
|
+
stream.setFormatter(
|
|
87
|
+
MaskingFormatter("%(asctime)s %(levelname)-7s %(name)s: %(message)s")
|
|
88
|
+
)
|
|
89
|
+
_tag(stream)
|
|
90
|
+
logger.addHandler(stream)
|
|
91
|
+
return path
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def reset_logging() -> None:
|
|
95
|
+
"""Remove the handlers installed by :func:`configure_logging`."""
|
|
96
|
+
logger = logging.getLogger("gitgatekeeper")
|
|
97
|
+
for handler in list(logger.handlers):
|
|
98
|
+
if getattr(handler, _HANDLER_TAG, False):
|
|
99
|
+
logger.removeHandler(handler)
|
|
100
|
+
handler.close()
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _tag(handler: logging.Handler) -> None:
|
|
104
|
+
setattr(handler, _HANDLER_TAG, True)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def read_log_tail(path: Path, lines: int) -> list[str]:
|
|
108
|
+
"""The last ``lines`` lines of a log file ([] if it does not exist)."""
|
|
109
|
+
if lines < 1:
|
|
110
|
+
raise ValueError("lines must be at least 1")
|
|
111
|
+
try:
|
|
112
|
+
size = path.stat().st_size
|
|
113
|
+
with path.open("rb") as handle:
|
|
114
|
+
chunk = min(size, max(8192, lines * 400))
|
|
115
|
+
handle.seek(size - chunk)
|
|
116
|
+
data = handle.read()
|
|
117
|
+
except OSError:
|
|
118
|
+
return []
|
|
119
|
+
text = data.decode("utf-8", "replace").splitlines()
|
|
120
|
+
if chunk < size and text:
|
|
121
|
+
text = text[1:] # the first line may be cut in half
|
|
122
|
+
return text[-lines:]
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Persistent history (SQLite)."""
|
|
2
|
+
|
|
3
|
+
from gitgatekeeper.storage.database import Database, StorageError
|
|
4
|
+
from gitgatekeeper.storage.history import HistoryStore
|
|
5
|
+
from gitgatekeeper.storage.models import CommitRecord, EventRecord, PendingRecord
|
|
6
|
+
from gitgatekeeper.storage.recorder import HistoryRecorder
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"CommitRecord",
|
|
10
|
+
"Database",
|
|
11
|
+
"EventRecord",
|
|
12
|
+
"HistoryRecorder",
|
|
13
|
+
"HistoryStore",
|
|
14
|
+
"PendingRecord",
|
|
15
|
+
"StorageError",
|
|
16
|
+
]
|