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,252 @@
|
|
|
1
|
+
"""Read-only access to the staged diff.
|
|
2
|
+
|
|
3
|
+
Safety notes
|
|
4
|
+
------------
|
|
5
|
+
* ``--no-ext-diff`` and ``--no-textconv`` stop Git from running programs that a
|
|
6
|
+
repository's configuration or ``.gitattributes`` may define for diffing.
|
|
7
|
+
* ``--literal-pathspecs`` makes every path an exact name, never a pattern.
|
|
8
|
+
* Files whose names look like secrets are listed but their content is never
|
|
9
|
+
read, and line content is excluded from ``repr`` so it cannot leak into logs.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import re
|
|
15
|
+
from collections.abc import Sequence
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from gitgatekeeper.git.models import ChangeType
|
|
20
|
+
from gitgatekeeper.git.repository import GitError, run_git
|
|
21
|
+
from gitgatekeeper.git.sensitive import is_sensitive_path
|
|
22
|
+
|
|
23
|
+
MAX_CONTENT_FILES = 40
|
|
24
|
+
MAX_LINES_PER_FILE = 2000
|
|
25
|
+
MAX_BLOB_BYTES = 1_000_000
|
|
26
|
+
DIFF_TIMEOUT_SECONDS = 30.0
|
|
27
|
+
|
|
28
|
+
_STATUS_LETTERS = {
|
|
29
|
+
"A": ChangeType.ADDED,
|
|
30
|
+
"M": ChangeType.MODIFIED,
|
|
31
|
+
"D": ChangeType.DELETED,
|
|
32
|
+
"R": ChangeType.RENAMED,
|
|
33
|
+
"C": ChangeType.COPIED,
|
|
34
|
+
"T": ChangeType.TYPE_CHANGED,
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True, slots=True)
|
|
39
|
+
class FileDiff:
|
|
40
|
+
"""One file of a diff. ``added``/``removed`` are ``None`` for binary files."""
|
|
41
|
+
|
|
42
|
+
path: str
|
|
43
|
+
status: ChangeType
|
|
44
|
+
added: int | None
|
|
45
|
+
removed: int | None
|
|
46
|
+
old_path: str | None = None
|
|
47
|
+
binary: bool = False
|
|
48
|
+
sensitive: bool = False
|
|
49
|
+
content_read: bool = False
|
|
50
|
+
# Transient and possibly secret: never persist or log these.
|
|
51
|
+
added_lines: tuple[str, ...] = field(default=(), repr=False)
|
|
52
|
+
removed_lines: tuple[str, ...] = field(default=(), repr=False)
|
|
53
|
+
# Where the added lines sit in the new file (1-based), aligned with
|
|
54
|
+
# ``added_lines`` when no limit was hit.
|
|
55
|
+
added_line_numbers: tuple[int, ...] = field(default=(), repr=False)
|
|
56
|
+
# Identifiers only (function/class names): the definitions that contain
|
|
57
|
+
# changed lines, e.g. "Cart.total". Filled in by
|
|
58
|
+
# :func:`gitgatekeeper.intelligence.context.add_touched_definitions`.
|
|
59
|
+
touched: tuple[str, ...] = ()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(frozen=True, slots=True)
|
|
63
|
+
class DiffSummary:
|
|
64
|
+
files: tuple[FileDiff, ...]
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def total_added(self) -> int:
|
|
68
|
+
return sum(f.added or 0 for f in self.files)
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def total_removed(self) -> int:
|
|
72
|
+
return sum(f.removed or 0 for f in self.files)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def parse_name_status(output: str) -> list[tuple[ChangeType, str, str | None]]:
|
|
76
|
+
"""Parse ``git diff --name-status -z -M`` into ``(status, path, old_path)``."""
|
|
77
|
+
tokens = output.split("\0")
|
|
78
|
+
entries: list[tuple[ChangeType, str, str | None]] = []
|
|
79
|
+
index = 0
|
|
80
|
+
while index < len(tokens):
|
|
81
|
+
code = tokens[index]
|
|
82
|
+
index += 1
|
|
83
|
+
if not code:
|
|
84
|
+
continue
|
|
85
|
+
status = _STATUS_LETTERS.get(code[0])
|
|
86
|
+
if status is None:
|
|
87
|
+
raise GitError(f"unsupported status {code!r} in staged diff")
|
|
88
|
+
if code[0] in "RC":
|
|
89
|
+
if index + 1 >= len(tokens) or not tokens[index + 1]:
|
|
90
|
+
raise GitError(f"malformed rename record for status {code!r}")
|
|
91
|
+
entries.append((status, tokens[index + 1], tokens[index]))
|
|
92
|
+
index += 2
|
|
93
|
+
else:
|
|
94
|
+
if index >= len(tokens) or not tokens[index]:
|
|
95
|
+
raise GitError(f"missing path for status {code!r}")
|
|
96
|
+
entries.append((status, tokens[index], None))
|
|
97
|
+
index += 1
|
|
98
|
+
return entries
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def parse_numstat(output: str) -> dict[str, tuple[int | None, int | None]]:
|
|
102
|
+
"""Parse ``git diff --numstat -z -M`` into ``{path: (added, removed)}``.
|
|
103
|
+
|
|
104
|
+
Binary files report ``None`` for both counts.
|
|
105
|
+
"""
|
|
106
|
+
tokens = output.split("\0")
|
|
107
|
+
stats: dict[str, tuple[int | None, int | None]] = {}
|
|
108
|
+
index = 0
|
|
109
|
+
while index < len(tokens):
|
|
110
|
+
record = tokens[index]
|
|
111
|
+
index += 1
|
|
112
|
+
if not record:
|
|
113
|
+
continue
|
|
114
|
+
parts = record.split("\t", 2)
|
|
115
|
+
if len(parts) != 3:
|
|
116
|
+
raise GitError(f"malformed numstat record: {record!r}")
|
|
117
|
+
added_text, removed_text, path = parts
|
|
118
|
+
if path == "": # rename or copy: the next two tokens are old and new
|
|
119
|
+
if index + 1 >= len(tokens) or not tokens[index] or not tokens[index + 1]:
|
|
120
|
+
raise GitError("malformed numstat rename record")
|
|
121
|
+
path = tokens[index + 1]
|
|
122
|
+
index += 2
|
|
123
|
+
try:
|
|
124
|
+
added = None if added_text == "-" else int(added_text)
|
|
125
|
+
removed = None if removed_text == "-" else int(removed_text)
|
|
126
|
+
except ValueError:
|
|
127
|
+
raise GitError(f"malformed numstat counts: {record!r}") from None
|
|
128
|
+
stats[path] = (added, removed)
|
|
129
|
+
return stats
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def parse_patch_lines(
|
|
133
|
+
patch: str, limit: int = MAX_LINES_PER_FILE
|
|
134
|
+
) -> tuple[tuple[str, ...], tuple[str, ...]]:
|
|
135
|
+
"""Extract added and removed lines from a ``-U0`` patch of a single file."""
|
|
136
|
+
added: list[str] = []
|
|
137
|
+
removed: list[str] = []
|
|
138
|
+
in_hunk = False
|
|
139
|
+
# Not splitlines(): it would also split on characters that can occur in code.
|
|
140
|
+
for line in patch.split("\n"):
|
|
141
|
+
if line.startswith("@@"):
|
|
142
|
+
in_hunk = True
|
|
143
|
+
elif not in_hunk:
|
|
144
|
+
continue
|
|
145
|
+
elif line.startswith("+") and len(added) < limit:
|
|
146
|
+
added.append(line[1:].rstrip("\r"))
|
|
147
|
+
elif line.startswith("-") and len(removed) < limit:
|
|
148
|
+
removed.append(line[1:].rstrip("\r"))
|
|
149
|
+
return tuple(added), tuple(removed)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
_HUNK = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@")
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def parse_added_line_numbers(patch: str, limit: int = MAX_LINES_PER_FILE) -> list[int]:
|
|
156
|
+
"""1-based line numbers, in the new file, of the lines a ``-U0`` patch adds."""
|
|
157
|
+
numbers: list[int] = []
|
|
158
|
+
for line in patch.split("\n"):
|
|
159
|
+
header = _HUNK.match(line)
|
|
160
|
+
if header:
|
|
161
|
+
cursor = int(header.group(1))
|
|
162
|
+
continue
|
|
163
|
+
if line.startswith("+") and not line.startswith("+++"):
|
|
164
|
+
if len(numbers) < limit:
|
|
165
|
+
numbers.append(cursor)
|
|
166
|
+
cursor += 1
|
|
167
|
+
return numbers
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def read_staged_text(repo: Path, path: str) -> list[str] | None:
|
|
171
|
+
"""Lines of the staged version of ``path`` (None if unavailable or huge)."""
|
|
172
|
+
result = run_git(
|
|
173
|
+
["cat-file", "blob", f":0:{path}"], cwd=repo, timeout=DIFF_TIMEOUT_SECONDS
|
|
174
|
+
)
|
|
175
|
+
if result.returncode != 0 or len(result.stdout) > MAX_BLOB_BYTES:
|
|
176
|
+
return None
|
|
177
|
+
return result.stdout.split("\n")
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _diff(repo: Path, extra: list[str], paths: Sequence[str]) -> str:
|
|
181
|
+
args = [
|
|
182
|
+
"--literal-pathspecs",
|
|
183
|
+
"diff",
|
|
184
|
+
"--cached",
|
|
185
|
+
"--no-ext-diff",
|
|
186
|
+
"--no-textconv",
|
|
187
|
+
"--no-color",
|
|
188
|
+
"-M",
|
|
189
|
+
*extra,
|
|
190
|
+
]
|
|
191
|
+
if paths:
|
|
192
|
+
args += ["--", *paths]
|
|
193
|
+
result = run_git(args, cwd=repo, timeout=DIFF_TIMEOUT_SECONDS)
|
|
194
|
+
if result.returncode != 0:
|
|
195
|
+
raise GitError(
|
|
196
|
+
f"git diff failed in {repo} (exit {result.returncode}): "
|
|
197
|
+
f"{result.stderr.strip()}"
|
|
198
|
+
)
|
|
199
|
+
return result.stdout
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def read_staged_diff(
|
|
203
|
+
repo: Path,
|
|
204
|
+
paths: Sequence[str] | None = None,
|
|
205
|
+
*,
|
|
206
|
+
max_content_files: int = MAX_CONTENT_FILES,
|
|
207
|
+
max_lines_per_file: int = MAX_LINES_PER_FILE,
|
|
208
|
+
) -> DiffSummary:
|
|
209
|
+
"""Summarise what is staged in ``repo`` (optionally limited to ``paths``).
|
|
210
|
+
|
|
211
|
+
Only the first ``max_content_files`` text files get their lines read;
|
|
212
|
+
sensitive and binary files never do. Raises :class:`GitError` if Git fails.
|
|
213
|
+
"""
|
|
214
|
+
wanted = list(paths or [])
|
|
215
|
+
entries = parse_name_status(_diff(repo, ["--name-status", "-z"], wanted))
|
|
216
|
+
stats = parse_numstat(_diff(repo, ["--numstat", "-z"], wanted))
|
|
217
|
+
|
|
218
|
+
files: list[FileDiff] = []
|
|
219
|
+
content_budget = max_content_files
|
|
220
|
+
for status, path, old_path in entries:
|
|
221
|
+
added, removed = stats.get(path, (0, 0))
|
|
222
|
+
binary = added is None
|
|
223
|
+
sensitive = is_sensitive_path(path) or (
|
|
224
|
+
old_path is not None and is_sensitive_path(old_path)
|
|
225
|
+
)
|
|
226
|
+
added_lines: tuple[str, ...] = ()
|
|
227
|
+
removed_lines: tuple[str, ...] = ()
|
|
228
|
+
content_read = False
|
|
229
|
+
line_numbers: tuple[int, ...] = ()
|
|
230
|
+
if not binary and not sensitive and content_budget > 0:
|
|
231
|
+
content_budget -= 1
|
|
232
|
+
targets = [old_path, path] if old_path else [path]
|
|
233
|
+
patch = _diff(repo, ["-U0"], targets)
|
|
234
|
+
added_lines, removed_lines = parse_patch_lines(patch, max_lines_per_file)
|
|
235
|
+
content_read = True
|
|
236
|
+
line_numbers = tuple(parse_added_line_numbers(patch, max_lines_per_file))
|
|
237
|
+
files.append(
|
|
238
|
+
FileDiff(
|
|
239
|
+
path=path,
|
|
240
|
+
status=status,
|
|
241
|
+
added=added,
|
|
242
|
+
removed=removed,
|
|
243
|
+
old_path=old_path,
|
|
244
|
+
binary=binary,
|
|
245
|
+
sensitive=sensitive,
|
|
246
|
+
content_read=content_read,
|
|
247
|
+
added_lines=added_lines,
|
|
248
|
+
removed_lines=removed_lines,
|
|
249
|
+
added_line_numbers=line_numbers,
|
|
250
|
+
)
|
|
251
|
+
)
|
|
252
|
+
return DiffSummary(tuple(files))
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Batch ``.gitignore`` evaluation through ``git check-ignore``.
|
|
2
|
+
|
|
3
|
+
Delegating to Git keeps the semantics exact (nested ``.gitignore`` files,
|
|
4
|
+
negation, ``.git/info/exclude`` and the user's global excludes) without adding
|
|
5
|
+
a dependency, and one call can answer for many paths.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Iterable
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from gitgatekeeper.git.repository import GitError, run_git
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def find_ignored(repo: Path, paths: Iterable[str]) -> set[str]:
|
|
17
|
+
"""Return the subset of ``paths`` (relative to ``repo``) that Git ignores.
|
|
18
|
+
|
|
19
|
+
Files already tracked by Git are never reported as ignored. Raises
|
|
20
|
+
:class:`GitError` if Git cannot answer (for example, ``repo`` is not a
|
|
21
|
+
repository any more).
|
|
22
|
+
"""
|
|
23
|
+
unique = list(dict.fromkeys(paths))
|
|
24
|
+
if not unique:
|
|
25
|
+
return set()
|
|
26
|
+
|
|
27
|
+
payload = "\0".join(unique) + "\0"
|
|
28
|
+
result = run_git(["check-ignore", "-z", "--stdin"], cwd=repo, input_text=payload)
|
|
29
|
+
if result.returncode == 0:
|
|
30
|
+
return {item for item in result.stdout.split("\0") if item}
|
|
31
|
+
if result.returncode == 1: # none of the paths is ignored
|
|
32
|
+
return set()
|
|
33
|
+
raise GitError(
|
|
34
|
+
f"git check-ignore failed in {repo} "
|
|
35
|
+
f"(exit {result.returncode}): {result.stderr.strip()}"
|
|
36
|
+
)
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Immutable data model describing the state of a Git repository."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from enum import StrEnum
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ChangeType(StrEnum):
|
|
11
|
+
ADDED = "added"
|
|
12
|
+
MODIFIED = "modified"
|
|
13
|
+
DELETED = "deleted"
|
|
14
|
+
RENAMED = "renamed"
|
|
15
|
+
COPIED = "copied"
|
|
16
|
+
TYPE_CHANGED = "type-changed"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Operation(StrEnum):
|
|
20
|
+
"""A multi-step Git operation that is currently in progress."""
|
|
21
|
+
|
|
22
|
+
MERGE = "merge"
|
|
23
|
+
REBASE = "rebase"
|
|
24
|
+
CHERRY_PICK = "cherry-pick"
|
|
25
|
+
REVERT = "revert"
|
|
26
|
+
BISECT = "bisect"
|
|
27
|
+
APPLY_MAILBOX = "am"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True, slots=True)
|
|
31
|
+
class FileStatus:
|
|
32
|
+
"""Status of one path.
|
|
33
|
+
|
|
34
|
+
``staged`` is the change recorded in the index (what a commit would
|
|
35
|
+
contain); ``unstaged`` is the further change in the working tree. A file
|
|
36
|
+
can have both. Untracked and conflicted files carry neither.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
path: str
|
|
40
|
+
staged: ChangeType | None = None
|
|
41
|
+
unstaged: ChangeType | None = None
|
|
42
|
+
orig_path: str | None = None # source path of a rename or copy
|
|
43
|
+
untracked: bool = False
|
|
44
|
+
conflicted: bool = False
|
|
45
|
+
submodule: bool = False
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def changes(self) -> frozenset[ChangeType]:
|
|
49
|
+
return frozenset(c for c in (self.staged, self.unstaged) if c is not None)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(frozen=True, slots=True)
|
|
53
|
+
class BranchInfo:
|
|
54
|
+
name: str | None # None when HEAD is detached
|
|
55
|
+
oid: str | None # None when the branch has no commits yet
|
|
56
|
+
detached: bool = False
|
|
57
|
+
unborn: bool = False
|
|
58
|
+
upstream: str | None = None
|
|
59
|
+
ahead: int | None = None # None when there is no (valid) upstream
|
|
60
|
+
behind: int | None = None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass(frozen=True, slots=True)
|
|
64
|
+
class RepositorySnapshot:
|
|
65
|
+
"""Point-in-time state of a repository, as reported by Git.
|
|
66
|
+
|
|
67
|
+
A snapshot goes stale the moment the user touches the repository, so
|
|
68
|
+
anything that acts on it must verify the state again right before acting.
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
root: Path
|
|
72
|
+
branch: BranchInfo
|
|
73
|
+
files: tuple[FileStatus, ...]
|
|
74
|
+
operations: tuple[Operation, ...] = ()
|
|
75
|
+
index_locked: bool = False
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
def staged(self) -> tuple[FileStatus, ...]:
|
|
79
|
+
"""Files with changes already in the index."""
|
|
80
|
+
return tuple(f for f in self.files if f.staged is not None)
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def unstaged(self) -> tuple[FileStatus, ...]:
|
|
84
|
+
"""Tracked files with working-tree changes not yet in the index."""
|
|
85
|
+
return tuple(f for f in self.files if f.unstaged is not None)
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def untracked(self) -> tuple[FileStatus, ...]:
|
|
89
|
+
return tuple(f for f in self.files if f.untracked)
|
|
90
|
+
|
|
91
|
+
@property
|
|
92
|
+
def conflicted(self) -> tuple[FileStatus, ...]:
|
|
93
|
+
return tuple(f for f in self.files if f.conflicted)
|
|
94
|
+
|
|
95
|
+
@property
|
|
96
|
+
def is_clean(self) -> bool:
|
|
97
|
+
return not self.files
|
|
98
|
+
|
|
99
|
+
def files_with(self, change: ChangeType) -> tuple[FileStatus, ...]:
|
|
100
|
+
"""Files whose staged or unstaged change is ``change``."""
|
|
101
|
+
return tuple(f for f in self.files if change in f.changes)
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def blockers(self) -> tuple[str, ...]:
|
|
105
|
+
"""Reasons why automatic commits should not run on this repository.
|
|
106
|
+
|
|
107
|
+
Empty when nothing stands in the way. This describes the state only;
|
|
108
|
+
deciding what to do about it belongs to the commit engine.
|
|
109
|
+
"""
|
|
110
|
+
reasons: list[str] = []
|
|
111
|
+
reasons.extend(f"{op.value} in progress" for op in self.operations)
|
|
112
|
+
if self.index_locked:
|
|
113
|
+
reasons.append("index is locked by another Git process")
|
|
114
|
+
if self.conflicted:
|
|
115
|
+
reasons.append("unresolved merge conflicts")
|
|
116
|
+
if self.branch.detached:
|
|
117
|
+
reasons.append("HEAD is detached")
|
|
118
|
+
return tuple(reasons)
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""Minimal, read-only Git repository helpers built on the Git CLI."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import os
|
|
7
|
+
import signal
|
|
8
|
+
import subprocess
|
|
9
|
+
from collections.abc import Mapping
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
GIT_TIMEOUT_SECONDS = 10
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class GitError(Exception):
|
|
16
|
+
"""Raised when the Git CLI is unavailable or a Git call times out."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def run_git(
|
|
20
|
+
args: list[str],
|
|
21
|
+
cwd: Path,
|
|
22
|
+
input_text: str | None = None,
|
|
23
|
+
timeout: float = GIT_TIMEOUT_SECONDS,
|
|
24
|
+
*,
|
|
25
|
+
new_session: bool = False,
|
|
26
|
+
extra_env: Mapping[str, str] | None = None,
|
|
27
|
+
) -> subprocess.CompletedProcess[str]:
|
|
28
|
+
"""Run ``git <args>`` in ``cwd`` and return the completed process.
|
|
29
|
+
|
|
30
|
+
No shell, fixed argv, bounded runtime, never prompts for credentials.
|
|
31
|
+
A non-zero exit status is returned, not raised; callers interpret it.
|
|
32
|
+
``new_session`` detaches the process from the controlling terminal, so
|
|
33
|
+
nothing it starts (ssh, credential helpers) can prompt on the user's tty.
|
|
34
|
+
``extra_env`` is added to the sanitised environment for this call only.
|
|
35
|
+
Output is decoded as UTF-8 with ``surrogateescape`` so file names that are
|
|
36
|
+
not valid UTF-8 (legal on Linux) survive a round trip instead of crashing.
|
|
37
|
+
"""
|
|
38
|
+
try:
|
|
39
|
+
if new_session:
|
|
40
|
+
return _run_in_own_session(
|
|
41
|
+
args, cwd, input_text, timeout, _git_env(extra_env)
|
|
42
|
+
)
|
|
43
|
+
return subprocess.run(
|
|
44
|
+
["git", *args],
|
|
45
|
+
cwd=cwd,
|
|
46
|
+
input=input_text,
|
|
47
|
+
capture_output=True,
|
|
48
|
+
text=True,
|
|
49
|
+
encoding="utf-8",
|
|
50
|
+
errors="surrogateescape",
|
|
51
|
+
timeout=timeout,
|
|
52
|
+
check=False,
|
|
53
|
+
env=_git_env(extra_env),
|
|
54
|
+
)
|
|
55
|
+
except FileNotFoundError as exc:
|
|
56
|
+
raise GitError("git executable not found in PATH") from exc
|
|
57
|
+
except subprocess.TimeoutExpired as exc:
|
|
58
|
+
raise GitError(f"git {' '.join(args)} timed out in {cwd}") from exc
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _run_in_own_session(
|
|
62
|
+
args: list[str],
|
|
63
|
+
cwd: Path,
|
|
64
|
+
input_text: str | None,
|
|
65
|
+
timeout: float,
|
|
66
|
+
env: dict[str, str],
|
|
67
|
+
) -> subprocess.CompletedProcess[str]:
|
|
68
|
+
"""Like ``subprocess.run`` but in a new session, killed as a whole on timeout.
|
|
69
|
+
|
|
70
|
+
Hooks and ssh started by Git live in the same process group, so a timeout
|
|
71
|
+
must not leave them running behind.
|
|
72
|
+
"""
|
|
73
|
+
process = subprocess.Popen(
|
|
74
|
+
["git", *args],
|
|
75
|
+
cwd=cwd,
|
|
76
|
+
stdin=subprocess.PIPE,
|
|
77
|
+
stdout=subprocess.PIPE,
|
|
78
|
+
stderr=subprocess.PIPE,
|
|
79
|
+
text=True,
|
|
80
|
+
encoding="utf-8",
|
|
81
|
+
errors="surrogateescape",
|
|
82
|
+
env=env,
|
|
83
|
+
start_new_session=True,
|
|
84
|
+
)
|
|
85
|
+
try:
|
|
86
|
+
stdout, stderr = process.communicate(input_text, timeout=timeout)
|
|
87
|
+
except subprocess.TimeoutExpired:
|
|
88
|
+
with contextlib.suppress(ProcessLookupError, PermissionError):
|
|
89
|
+
os.killpg(process.pid, signal.SIGKILL)
|
|
90
|
+
process.communicate()
|
|
91
|
+
raise
|
|
92
|
+
return subprocess.CompletedProcess(args, process.returncode, stdout, stderr)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _git_env(extra: Mapping[str, str] | None = None) -> dict[str, str]:
|
|
96
|
+
env = dict(os.environ)
|
|
97
|
+
env["GIT_TERMINAL_PROMPT"] = "0"
|
|
98
|
+
# Read-only commands must not grab index.lock behind the user's back.
|
|
99
|
+
env["GIT_OPTIONAL_LOCKS"] = "0"
|
|
100
|
+
env["LC_ALL"] = "C"
|
|
101
|
+
if extra:
|
|
102
|
+
env.update(extra)
|
|
103
|
+
return env
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def find_repository_root(path: Path) -> Path | None:
|
|
107
|
+
"""Return the top-level directory of the repository containing ``path``.
|
|
108
|
+
|
|
109
|
+
Returns ``None`` if ``path`` is not a directory inside a Git work tree.
|
|
110
|
+
Raises :class:`GitError` if Git itself cannot be run.
|
|
111
|
+
"""
|
|
112
|
+
if not path.is_dir():
|
|
113
|
+
return None
|
|
114
|
+
result = run_git(["rev-parse", "--show-toplevel"], cwd=path)
|
|
115
|
+
if result.returncode != 0:
|
|
116
|
+
return None
|
|
117
|
+
top_level = result.stdout.strip()
|
|
118
|
+
return Path(top_level).resolve() if top_level else None
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def is_git_repository(path: Path) -> bool:
|
|
122
|
+
"""Return True if ``path`` is inside a Git work tree."""
|
|
123
|
+
return find_repository_root(path) is not None
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""Content-based detection of credentials in text about to be committed.
|
|
2
|
+
|
|
3
|
+
Complements :mod:`gitgatekeeper.git.sensitive`, which only looks at file names. The
|
|
4
|
+
rules are deliberately narrow (well-known token formats plus quoted hard-coded
|
|
5
|
+
assignments) so that a hit is worth stopping for; they are not a replacement for
|
|
6
|
+
a dedicated scanner.
|
|
7
|
+
|
|
8
|
+
A finding names the file and the rule that matched. It never carries the
|
|
9
|
+
matched text, so it is always safe to log.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import re
|
|
15
|
+
from collections.abc import Iterable, Sequence
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
|
|
18
|
+
from gitgatekeeper.git.sensitive import is_env_template
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True, slots=True)
|
|
22
|
+
class SecretFinding:
|
|
23
|
+
path: str
|
|
24
|
+
rule: str
|
|
25
|
+
line: int | None = None # line number in the new file; never the content
|
|
26
|
+
|
|
27
|
+
def describe(self) -> str:
|
|
28
|
+
"""``path:line (rule)``: where to look, never what was matched."""
|
|
29
|
+
place = f"{self.path}:{self.line}" if self.line else self.path
|
|
30
|
+
return f"{place} ({self.rule})"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
_TOKEN_RULES: tuple[tuple[str, re.Pattern[str]], ...] = (
|
|
34
|
+
(
|
|
35
|
+
"private-key",
|
|
36
|
+
re.compile(r"-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----"),
|
|
37
|
+
),
|
|
38
|
+
("aws-access-key", re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b")),
|
|
39
|
+
(
|
|
40
|
+
"github-token",
|
|
41
|
+
re.compile(r"\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{22,})"),
|
|
42
|
+
),
|
|
43
|
+
("slack-token", re.compile(r"\bxox[abprs]-[A-Za-z0-9-]{10,}")),
|
|
44
|
+
("google-api-key", re.compile(r"\bAIza[0-9A-Za-z_-]{35}")),
|
|
45
|
+
("stripe-key", re.compile(r"\b[sr]k_live_[0-9A-Za-z]{16,}")),
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
_URL_CREDENTIALS = re.compile(
|
|
49
|
+
r"\b[a-z][a-z0-9+.-]*://[^\s/:@'\"]+:([^\s/@'\"]{3,})@([^\s/'\"]+)"
|
|
50
|
+
)
|
|
51
|
+
# Passwords nobody picks for real: the scaffolding values of DB/Redis images.
|
|
52
|
+
_STOCK_PASSWORDS = frozenset(
|
|
53
|
+
{"pass", "password", "passwd", "pwd", "secret", "root", "admin", "postgres"}
|
|
54
|
+
| {"mysql", "guest", "test", "user"}
|
|
55
|
+
)
|
|
56
|
+
_LOCAL_HOSTS = frozenset({"localhost", "127.0.0.1", "0.0.0.0", "[::1]"})
|
|
57
|
+
|
|
58
|
+
_ASSIGNMENT = re.compile(
|
|
59
|
+
r"""\b[\w.-]*(?:password|passwd|pwd|secret|api[_-]?key|access[_-]?key"""
|
|
60
|
+
r"""|auth[_-]?token|token)\b["']?\s*[:=]\s*["']([^"'\s]{8,})["']""",
|
|
61
|
+
re.IGNORECASE,
|
|
62
|
+
)
|
|
63
|
+
_PLACEHOLDER_HINTS = (
|
|
64
|
+
"example",
|
|
65
|
+
"changeme",
|
|
66
|
+
"change-me",
|
|
67
|
+
"change_me",
|
|
68
|
+
"your",
|
|
69
|
+
"placeholder",
|
|
70
|
+
"dummy",
|
|
71
|
+
"sample",
|
|
72
|
+
"xxxx",
|
|
73
|
+
"****",
|
|
74
|
+
"<",
|
|
75
|
+
">",
|
|
76
|
+
"${",
|
|
77
|
+
"{{",
|
|
78
|
+
"%(",
|
|
79
|
+
"environ",
|
|
80
|
+
"getenv",
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _is_local_host(authority: str) -> bool:
|
|
85
|
+
host = authority.lower()
|
|
86
|
+
if not host.startswith("["):
|
|
87
|
+
host = host.split(":", 1)[0]
|
|
88
|
+
else:
|
|
89
|
+
host = host.split("]", 1)[0] + "]"
|
|
90
|
+
return host in _LOCAL_HOSTS or host == "host.docker.internal" or "." not in host
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _benign_url_credentials(path: str, password: str, authority: str) -> bool:
|
|
94
|
+
"""Placeholders, stock passwords and local examples in template files."""
|
|
95
|
+
lowered = password.lower()
|
|
96
|
+
if lowered in _STOCK_PASSWORDS or any(h in lowered for h in _PLACEHOLDER_HINTS):
|
|
97
|
+
return True
|
|
98
|
+
return is_env_template(path) and _is_local_host(authority)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _has_real_url_credentials(path: str, line: str) -> bool:
|
|
102
|
+
return any(
|
|
103
|
+
not _benign_url_credentials(path, m.group(1), m.group(2))
|
|
104
|
+
for m in _URL_CREDENTIALS.finditer(line)
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _looks_like_secret(value: str) -> bool:
|
|
109
|
+
lowered = value.lower()
|
|
110
|
+
if any(hint in lowered for hint in _PLACEHOLDER_HINTS):
|
|
111
|
+
return False
|
|
112
|
+
if len(set(value)) <= 2: # "aaaaaaaa", "12121212"
|
|
113
|
+
return False
|
|
114
|
+
has_letter = any(c.isalpha() for c in value)
|
|
115
|
+
has_digit = any(c.isdigit() for c in value)
|
|
116
|
+
return (has_letter and has_digit) or len(value) >= 24
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def scan_lines(
|
|
120
|
+
path: str,
|
|
121
|
+
lines: Iterable[str],
|
|
122
|
+
numbers: Sequence[int] = (),
|
|
123
|
+
*,
|
|
124
|
+
allow_hardcoded: bool = False,
|
|
125
|
+
) -> list[SecretFinding]:
|
|
126
|
+
"""Return at most one finding per rule for ``lines`` of file ``path``.
|
|
127
|
+
|
|
128
|
+
``numbers`` optionally gives each line's number in the new file, so a
|
|
129
|
+
finding can say where to look. ``allow_hardcoded`` switches off the
|
|
130
|
+
``password = "..."`` heuristic only (for files known to hold examples);
|
|
131
|
+
token formats and URL credentials are always checked. URL credentials that
|
|
132
|
+
are placeholders, stock passwords (``postgres``, ``password``...) or local
|
|
133
|
+
examples inside ``.env.example``-style files do not count.
|
|
134
|
+
"""
|
|
135
|
+
lines = list(lines)
|
|
136
|
+
known = len(numbers) == len(lines)
|
|
137
|
+
found: dict[str, int | None] = {}
|
|
138
|
+
for index, line in enumerate(lines):
|
|
139
|
+
where = numbers[index] if known else None
|
|
140
|
+
for name, pattern in _TOKEN_RULES:
|
|
141
|
+
if name not in found and pattern.search(line):
|
|
142
|
+
found[name] = where
|
|
143
|
+
if "credentials-in-url" not in found and _has_real_url_credentials(path, line):
|
|
144
|
+
found["credentials-in-url"] = where
|
|
145
|
+
if not allow_hardcoded and "hardcoded-secret" not in found:
|
|
146
|
+
for match in _ASSIGNMENT.finditer(line):
|
|
147
|
+
if _looks_like_secret(match.group(1)):
|
|
148
|
+
found["hardcoded-secret"] = where
|
|
149
|
+
break
|
|
150
|
+
return [SecretFinding(path, rule, line) for rule, line in found.items()]
|