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,114 @@
|
|
|
1
|
+
"""Name-based detection of files that commonly hold secrets.
|
|
2
|
+
|
|
3
|
+
This looks at paths only. It is deliberately conservative: when a name is
|
|
4
|
+
ambiguous (a ``.pem`` can be a public certificate) it is treated as sensitive,
|
|
5
|
+
because wrongly skipping a file is cheap and wrongly committing a key is not.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from pathlib import PurePosixPath
|
|
11
|
+
|
|
12
|
+
_EXACT_NAMES = frozenset(
|
|
13
|
+
{
|
|
14
|
+
".netrc",
|
|
15
|
+
"_netrc",
|
|
16
|
+
".git-credentials",
|
|
17
|
+
".pypirc",
|
|
18
|
+
".npmrc",
|
|
19
|
+
".htpasswd",
|
|
20
|
+
".pgpass",
|
|
21
|
+
"credentials",
|
|
22
|
+
"credentials.json",
|
|
23
|
+
"secrets.json",
|
|
24
|
+
"secrets.yaml",
|
|
25
|
+
"secrets.yml",
|
|
26
|
+
"secrets.toml",
|
|
27
|
+
"secret.json",
|
|
28
|
+
"secret.yaml",
|
|
29
|
+
"secret.yml",
|
|
30
|
+
"id_rsa",
|
|
31
|
+
"id_dsa",
|
|
32
|
+
"id_ecdsa",
|
|
33
|
+
"id_ed25519",
|
|
34
|
+
"kubeconfig",
|
|
35
|
+
"terraform.tfstate",
|
|
36
|
+
"terraform.tfstate.backup",
|
|
37
|
+
}
|
|
38
|
+
)
|
|
39
|
+
_SUFFIXES = (
|
|
40
|
+
".pem",
|
|
41
|
+
".key",
|
|
42
|
+
".p12",
|
|
43
|
+
".pfx",
|
|
44
|
+
".jks",
|
|
45
|
+
".keystore",
|
|
46
|
+
".ppk",
|
|
47
|
+
".kdbx",
|
|
48
|
+
".tfvars",
|
|
49
|
+
# local databases: they change on every run and may hold real data
|
|
50
|
+
".sqlite",
|
|
51
|
+
".sqlite3",
|
|
52
|
+
".db",
|
|
53
|
+
".db-wal",
|
|
54
|
+
".db-shm",
|
|
55
|
+
".db-journal",
|
|
56
|
+
".sqlite-wal",
|
|
57
|
+
".sqlite-shm",
|
|
58
|
+
".sqlite-journal",
|
|
59
|
+
)
|
|
60
|
+
_PREFIXES = ("service-account", "serviceaccount", "client_secret")
|
|
61
|
+
_SENSITIVE_DIRS = frozenset({".ssh", ".aws", ".gnupg"})
|
|
62
|
+
_ENV_TEMPLATES = frozenset(
|
|
63
|
+
{".env.example", ".env.sample", ".env.template", ".env.dist", ".env.defaults"}
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
_LOCKFILES = frozenset(
|
|
68
|
+
{
|
|
69
|
+
"package-lock.json",
|
|
70
|
+
"npm-shrinkwrap.json",
|
|
71
|
+
"yarn.lock",
|
|
72
|
+
"pnpm-lock.yaml",
|
|
73
|
+
"bun.lock",
|
|
74
|
+
"composer.lock",
|
|
75
|
+
"gemfile.lock",
|
|
76
|
+
"poetry.lock",
|
|
77
|
+
"pipfile.lock",
|
|
78
|
+
"uv.lock",
|
|
79
|
+
"cargo.lock",
|
|
80
|
+
"go.sum",
|
|
81
|
+
"pubspec.lock",
|
|
82
|
+
"mix.lock",
|
|
83
|
+
"podfile.lock",
|
|
84
|
+
"packages.lock.json",
|
|
85
|
+
"gradle.lockfile",
|
|
86
|
+
}
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def is_lockfile(path: str) -> bool:
|
|
91
|
+
"""True for generated dependency lockfiles (huge, machine-written)."""
|
|
92
|
+
return PurePosixPath(path).name.lower() in _LOCKFILES
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def is_env_template(path: str) -> bool:
|
|
96
|
+
"""True for ``.env.example``-style files, which exist to be committed."""
|
|
97
|
+
return PurePosixPath(path).name.lower() in _ENV_TEMPLATES
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def is_sensitive_path(path: str) -> bool:
|
|
101
|
+
"""True if ``path`` (POSIX, relative or absolute) looks like a secrets file."""
|
|
102
|
+
pure = PurePosixPath(path)
|
|
103
|
+
name = pure.name.lower()
|
|
104
|
+
if not name:
|
|
105
|
+
return False
|
|
106
|
+
if name in _ENV_TEMPLATES:
|
|
107
|
+
return False
|
|
108
|
+
if name == ".env" or name.startswith(".env.") or name.endswith(".env"):
|
|
109
|
+
return True
|
|
110
|
+
if name in _EXACT_NAMES or name.endswith(_SUFFIXES):
|
|
111
|
+
return True
|
|
112
|
+
if name.startswith(_PREFIXES) and name.endswith(".json"):
|
|
113
|
+
return True
|
|
114
|
+
return any(part.lower() in _SENSITIVE_DIRS for part in pure.parts[:-1])
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""Parser for ``git status --porcelain=v2 --branch -z`` output.
|
|
2
|
+
|
|
3
|
+
A pure function over text, so every record shape can be tested without a
|
|
4
|
+
repository. The format is documented in ``git-status(1)``; in ``-z`` mode all
|
|
5
|
+
records are NUL-terminated and paths are never quoted.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from gitgatekeeper.git.models import BranchInfo, ChangeType, FileStatus
|
|
11
|
+
from gitgatekeeper.git.repository import GitError
|
|
12
|
+
|
|
13
|
+
_CODES = {
|
|
14
|
+
"M": ChangeType.MODIFIED,
|
|
15
|
+
"A": ChangeType.ADDED,
|
|
16
|
+
"D": ChangeType.DELETED,
|
|
17
|
+
"R": ChangeType.RENAMED,
|
|
18
|
+
"C": ChangeType.COPIED,
|
|
19
|
+
"T": ChangeType.TYPE_CHANGED,
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _change(code: str, record: str) -> ChangeType | None:
|
|
24
|
+
if code == ".":
|
|
25
|
+
return None
|
|
26
|
+
try:
|
|
27
|
+
return _CODES[code]
|
|
28
|
+
except KeyError:
|
|
29
|
+
raise GitError(f"unexpected status code {code!r} in {record!r}") from None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _parse_xy(xy: str, record: str) -> tuple[ChangeType | None, ChangeType | None]:
|
|
33
|
+
if len(xy) != 2:
|
|
34
|
+
raise GitError(f"malformed status code in {record!r}")
|
|
35
|
+
return _change(xy[0], record), _change(xy[1], record)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _parse_branch(headers: dict[str, str]) -> BranchInfo:
|
|
39
|
+
try:
|
|
40
|
+
head = headers["head"]
|
|
41
|
+
oid = headers["oid"]
|
|
42
|
+
except KeyError:
|
|
43
|
+
raise GitError("git status output has no branch headers") from None
|
|
44
|
+
|
|
45
|
+
ahead = behind = None
|
|
46
|
+
if "ab" in headers:
|
|
47
|
+
try:
|
|
48
|
+
ahead_text, behind_text = headers["ab"].split()
|
|
49
|
+
ahead, behind = int(ahead_text.lstrip("+")), int(behind_text.lstrip("-"))
|
|
50
|
+
except ValueError:
|
|
51
|
+
raise GitError(f"malformed branch.ab header: {headers['ab']!r}") from None
|
|
52
|
+
|
|
53
|
+
unborn = oid == "(initial)"
|
|
54
|
+
detached = head == "(detached)"
|
|
55
|
+
return BranchInfo(
|
|
56
|
+
name=None if detached else head,
|
|
57
|
+
oid=None if unborn else oid,
|
|
58
|
+
detached=detached,
|
|
59
|
+
unborn=unborn,
|
|
60
|
+
upstream=headers.get("upstream"),
|
|
61
|
+
ahead=ahead,
|
|
62
|
+
behind=behind,
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def parse_status(output: str) -> tuple[BranchInfo, tuple[FileStatus, ...]]:
|
|
67
|
+
"""Parse ``git status --porcelain=v2 --branch -z`` output.
|
|
68
|
+
|
|
69
|
+
Ignored entries (``!``) are skipped. Raises :class:`GitError` on anything
|
|
70
|
+
that does not match the documented format, rather than guessing.
|
|
71
|
+
"""
|
|
72
|
+
tokens = output.split("\0")
|
|
73
|
+
headers: dict[str, str] = {}
|
|
74
|
+
files: list[FileStatus] = []
|
|
75
|
+
|
|
76
|
+
index = 0
|
|
77
|
+
while index < len(tokens):
|
|
78
|
+
record = tokens[index]
|
|
79
|
+
index += 1
|
|
80
|
+
if not record:
|
|
81
|
+
continue
|
|
82
|
+
|
|
83
|
+
kind = record[0]
|
|
84
|
+
if record.startswith("# "):
|
|
85
|
+
name, _, value = record[2:].partition(" ")
|
|
86
|
+
if name.startswith("branch."):
|
|
87
|
+
headers[name.removeprefix("branch.")] = value
|
|
88
|
+
elif kind == "1": # ordinary change
|
|
89
|
+
parts = record.split(" ", 8)
|
|
90
|
+
if len(parts) != 9:
|
|
91
|
+
raise GitError(f"malformed status record: {record!r}")
|
|
92
|
+
staged, unstaged = _parse_xy(parts[1], record)
|
|
93
|
+
files.append(
|
|
94
|
+
FileStatus(
|
|
95
|
+
path=parts[8],
|
|
96
|
+
staged=staged,
|
|
97
|
+
unstaged=unstaged,
|
|
98
|
+
submodule=parts[2].startswith("S"),
|
|
99
|
+
)
|
|
100
|
+
)
|
|
101
|
+
elif kind == "2": # rename or copy: the original path is the next token
|
|
102
|
+
parts = record.split(" ", 9)
|
|
103
|
+
if len(parts) != 10 or index >= len(tokens):
|
|
104
|
+
raise GitError(f"malformed rename record: {record!r}")
|
|
105
|
+
staged, unstaged = _parse_xy(parts[1], record)
|
|
106
|
+
files.append(
|
|
107
|
+
FileStatus(
|
|
108
|
+
path=parts[9],
|
|
109
|
+
staged=staged,
|
|
110
|
+
unstaged=unstaged,
|
|
111
|
+
orig_path=tokens[index],
|
|
112
|
+
submodule=parts[2].startswith("S"),
|
|
113
|
+
)
|
|
114
|
+
)
|
|
115
|
+
index += 1
|
|
116
|
+
elif kind == "u": # unmerged (conflict)
|
|
117
|
+
parts = record.split(" ", 10)
|
|
118
|
+
if len(parts) != 11:
|
|
119
|
+
raise GitError(f"malformed unmerged record: {record!r}")
|
|
120
|
+
files.append(
|
|
121
|
+
FileStatus(
|
|
122
|
+
path=parts[10],
|
|
123
|
+
conflicted=True,
|
|
124
|
+
submodule=parts[2].startswith("S"),
|
|
125
|
+
)
|
|
126
|
+
)
|
|
127
|
+
elif kind == "?":
|
|
128
|
+
files.append(FileStatus(path=record[2:], untracked=True))
|
|
129
|
+
elif kind == "!":
|
|
130
|
+
continue
|
|
131
|
+
else:
|
|
132
|
+
raise GitError(f"unrecognised status record: {record!r}")
|
|
133
|
+
|
|
134
|
+
return _parse_branch(headers), tuple(files)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Commit message intelligence."""
|
|
2
|
+
|
|
3
|
+
from gitgatekeeper.intelligence.message import (
|
|
4
|
+
CommitMessage,
|
|
5
|
+
CommitType,
|
|
6
|
+
Confidence,
|
|
7
|
+
validate_message,
|
|
8
|
+
)
|
|
9
|
+
from gitgatekeeper.intelligence.provider import (
|
|
10
|
+
MessageGenerator,
|
|
11
|
+
generate_commit_message,
|
|
12
|
+
)
|
|
13
|
+
from gitgatekeeper.intelligence.rules import RuleBasedGenerator
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"CommitMessage",
|
|
17
|
+
"CommitType",
|
|
18
|
+
"Confidence",
|
|
19
|
+
"MessageGenerator",
|
|
20
|
+
"RuleBasedGenerator",
|
|
21
|
+
"generate_commit_message",
|
|
22
|
+
"validate_message",
|
|
23
|
+
]
|
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
"""Evidence extraction from file paths and diff lines.
|
|
2
|
+
|
|
3
|
+
Everything here is a pure function over strings. Nothing returned contains
|
|
4
|
+
diff *content* beyond identifiers (function and class names) and yes/no
|
|
5
|
+
answers, so results are safe to put in a commit message.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
import unicodedata
|
|
12
|
+
from collections.abc import Iterable, Sequence
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from enum import StrEnum
|
|
15
|
+
from pathlib import PurePosixPath
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class FileCategory(StrEnum):
|
|
19
|
+
SOURCE = "source"
|
|
20
|
+
TEST = "test"
|
|
21
|
+
DOCS = "docs"
|
|
22
|
+
CI = "ci"
|
|
23
|
+
BUILD = "build"
|
|
24
|
+
CONFIG = "config"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
_CI_NAMES = frozenset(
|
|
28
|
+
{
|
|
29
|
+
".gitlab-ci.yml",
|
|
30
|
+
".travis.yml",
|
|
31
|
+
"jenkinsfile",
|
|
32
|
+
"azure-pipelines.yml",
|
|
33
|
+
"bitbucket-pipelines.yml",
|
|
34
|
+
}
|
|
35
|
+
)
|
|
36
|
+
_CI_DIRS = (".github/workflows", ".github/actions", ".circleci")
|
|
37
|
+
_TEST_DIRS = frozenset({"tests", "test", "__tests__", "spec", "specs"})
|
|
38
|
+
_TEST_NAME = re.compile(
|
|
39
|
+
r"^(test_.*\.py|.*_test\.(py|go|rs)|.*\.(test|spec)\.[a-z]+|conftest\.py)$"
|
|
40
|
+
)
|
|
41
|
+
_BUILD_NAMES = frozenset(
|
|
42
|
+
{
|
|
43
|
+
"pyproject.toml",
|
|
44
|
+
"setup.py",
|
|
45
|
+
"setup.cfg",
|
|
46
|
+
"manifest.in",
|
|
47
|
+
"pipfile",
|
|
48
|
+
"pipfile.lock",
|
|
49
|
+
"poetry.lock",
|
|
50
|
+
"uv.lock",
|
|
51
|
+
"package.json",
|
|
52
|
+
"package-lock.json",
|
|
53
|
+
"yarn.lock",
|
|
54
|
+
"pnpm-lock.yaml",
|
|
55
|
+
"pnpm-workspace.yaml",
|
|
56
|
+
"bun.lock",
|
|
57
|
+
"bun.lockb",
|
|
58
|
+
"composer.json",
|
|
59
|
+
"composer.lock",
|
|
60
|
+
"gemfile",
|
|
61
|
+
"gemfile.lock",
|
|
62
|
+
"mix.exs",
|
|
63
|
+
"mix.lock",
|
|
64
|
+
"pubspec.yaml",
|
|
65
|
+
"pubspec.lock",
|
|
66
|
+
"build.sbt",
|
|
67
|
+
"package.swift",
|
|
68
|
+
"package.resolved",
|
|
69
|
+
"podfile",
|
|
70
|
+
"podfile.lock",
|
|
71
|
+
"cargo.toml",
|
|
72
|
+
"cargo.lock",
|
|
73
|
+
"go.mod",
|
|
74
|
+
"go.sum",
|
|
75
|
+
"pom.xml",
|
|
76
|
+
"makefile",
|
|
77
|
+
"cmakelists.txt",
|
|
78
|
+
".dockerignore",
|
|
79
|
+
}
|
|
80
|
+
)
|
|
81
|
+
_BUILD_PATTERN = re.compile(
|
|
82
|
+
r"^(requirements.*\.txt|build\.gradle.*|dockerfile.*|docker-compose.*\.ya?ml)$"
|
|
83
|
+
)
|
|
84
|
+
_DOC_SUFFIXES = (".md", ".rst", ".adoc")
|
|
85
|
+
_DOC_DIRS = frozenset({"docs", "doc"})
|
|
86
|
+
_DOC_STEMS = ("readme", "changelog", "license", "contributing", "authors", "notice")
|
|
87
|
+
# Tool configuration written in code: vite.config.ts, .eslintrc.cjs, .prettierrc...
|
|
88
|
+
_TOOL_CONFIG = re.compile(
|
|
89
|
+
r"^(?:[\w-]+\.config\.[cm]?[jt]s"
|
|
90
|
+
r"|\.(?:eslintrc|prettierrc|stylelintrc|babelrc|npmrc|nvmrc|browserslistrc)(?:\.\w+)?"
|
|
91
|
+
r"|(?:ts|js)config(?:\.[\w-]+)?\.json)$"
|
|
92
|
+
)
|
|
93
|
+
_CONFIG_NAMES = frozenset(
|
|
94
|
+
{".gitignore", ".gitattributes", ".editorconfig", ".pre-commit-config.yaml"}
|
|
95
|
+
)
|
|
96
|
+
_CONFIG_SUFFIXES = (
|
|
97
|
+
".yaml",
|
|
98
|
+
".yml",
|
|
99
|
+
".toml",
|
|
100
|
+
".ini",
|
|
101
|
+
".cfg",
|
|
102
|
+
".json",
|
|
103
|
+
".conf",
|
|
104
|
+
".cnf",
|
|
105
|
+
".properties",
|
|
106
|
+
".service",
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def categorize(path: str) -> FileCategory:
|
|
111
|
+
"""Classify a POSIX relative path by what kind of file it is."""
|
|
112
|
+
pure = PurePosixPath(path)
|
|
113
|
+
name = pure.name.lower()
|
|
114
|
+
parts = [p.lower() for p in pure.parts[:-1]]
|
|
115
|
+
posix = pure.as_posix().lower()
|
|
116
|
+
|
|
117
|
+
if name in _CI_NAMES or any(posix.startswith(d + "/") for d in _CI_DIRS):
|
|
118
|
+
return FileCategory.CI
|
|
119
|
+
if _TEST_DIRS.intersection(parts) or _TEST_NAME.match(name):
|
|
120
|
+
return FileCategory.TEST
|
|
121
|
+
if name in _BUILD_NAMES or _BUILD_PATTERN.match(name):
|
|
122
|
+
return FileCategory.BUILD
|
|
123
|
+
if (
|
|
124
|
+
name.endswith(_DOC_SUFFIXES)
|
|
125
|
+
or _DOC_DIRS.intersection(parts)
|
|
126
|
+
or name.startswith(_DOC_STEMS)
|
|
127
|
+
):
|
|
128
|
+
return FileCategory.DOCS
|
|
129
|
+
if (
|
|
130
|
+
name in _CONFIG_NAMES
|
|
131
|
+
or name.startswith(".env")
|
|
132
|
+
or name.endswith(_CONFIG_SUFFIXES)
|
|
133
|
+
or _TOOL_CONFIG.match(name)
|
|
134
|
+
):
|
|
135
|
+
return FileCategory.CONFIG
|
|
136
|
+
return FileCategory.SOURCE
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
@dataclass(frozen=True, slots=True)
|
|
140
|
+
class Definition:
|
|
141
|
+
kind: str # "function", "class" or "type"
|
|
142
|
+
name: str
|
|
143
|
+
indent: int
|
|
144
|
+
|
|
145
|
+
@property
|
|
146
|
+
def is_public(self) -> bool:
|
|
147
|
+
return not self.name.startswith("_")
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
_DEFINITION_PATTERNS = (
|
|
151
|
+
("function", re.compile(r"^(\s*)(?:async\s+)?def\s+([A-Za-z_]\w*)\s*\(")),
|
|
152
|
+
("class", re.compile(r"^(\s*)class\s+([A-Za-z_]\w*)\s*[(:]")),
|
|
153
|
+
(
|
|
154
|
+
"function",
|
|
155
|
+
re.compile(
|
|
156
|
+
r"^(\s*)(?:export\s+)?(?:default\s+)?(?:async\s+)?"
|
|
157
|
+
r"function\s*\*?\s*([A-Za-z_$][\w$]*)\s*\("
|
|
158
|
+
),
|
|
159
|
+
),
|
|
160
|
+
(
|
|
161
|
+
"class",
|
|
162
|
+
re.compile(
|
|
163
|
+
r"^(\s*)(?:export\s+)?(?:default\s+)?(?:abstract\s+)?"
|
|
164
|
+
r"class\s+([A-Za-z_$][\w$]*)"
|
|
165
|
+
),
|
|
166
|
+
),
|
|
167
|
+
(
|
|
168
|
+
"function",
|
|
169
|
+
re.compile(
|
|
170
|
+
r"^(\s*)(?:export\s+)?const\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?"
|
|
171
|
+
r"(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>"
|
|
172
|
+
),
|
|
173
|
+
),
|
|
174
|
+
("function", re.compile(r"^(\s*)func\s+(?:\([^)]*\)\s*)?([A-Za-z_]\w*)\s*\(")),
|
|
175
|
+
("type", re.compile(r"^(\s*)type\s+([A-Za-z_]\w*)\s+(?:struct|interface)\b")),
|
|
176
|
+
(
|
|
177
|
+
"function",
|
|
178
|
+
re.compile(r"^(\s*)(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([A-Za-z_]\w*)"),
|
|
179
|
+
),
|
|
180
|
+
(
|
|
181
|
+
"type",
|
|
182
|
+
re.compile(
|
|
183
|
+
r"^(\s*)(?:pub(?:\([^)]*\))?\s+)?(?:struct|enum|trait)\s+([A-Za-z_]\w*)"
|
|
184
|
+
),
|
|
185
|
+
),
|
|
186
|
+
# PHP: methods with modifiers, and classes/interfaces/traits/enums.
|
|
187
|
+
(
|
|
188
|
+
"function",
|
|
189
|
+
re.compile(
|
|
190
|
+
r"^(\s*)(?:(?:public|protected|private|static|final|abstract)\s+)*"
|
|
191
|
+
r"function\s+&?([A-Za-z_]\w*)\s*\("
|
|
192
|
+
),
|
|
193
|
+
),
|
|
194
|
+
(
|
|
195
|
+
"class",
|
|
196
|
+
re.compile(
|
|
197
|
+
r"^(\s*)(?:(?:final|abstract|readonly)\s+)*"
|
|
198
|
+
r"(?:class|interface|trait|enum)\s+([A-Za-z_]\w*)"
|
|
199
|
+
),
|
|
200
|
+
),
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def match_definition(line: str) -> Definition | None:
|
|
205
|
+
for kind, pattern in _DEFINITION_PATTERNS:
|
|
206
|
+
match = pattern.match(line)
|
|
207
|
+
if match:
|
|
208
|
+
return Definition(kind, match.group(2), len(match.group(1).expandtabs(4)))
|
|
209
|
+
return None
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def enclosing_definitions(
|
|
213
|
+
source_lines: Sequence[str], changed: Iterable[int]
|
|
214
|
+
) -> list[str]:
|
|
215
|
+
"""Names of the definitions that contain the 1-based ``changed`` line numbers.
|
|
216
|
+
|
|
217
|
+
Works for any language whose nesting follows indentation: for each changed
|
|
218
|
+
line the nearest definition above it with a smaller indent is its owner (a
|
|
219
|
+
class around a method is reported as ``Class.method``). A line that is
|
|
220
|
+
itself a definition counts as that definition. Order of first appearance,
|
|
221
|
+
no duplicates.
|
|
222
|
+
"""
|
|
223
|
+
marks: list[tuple[int, Definition]] = []
|
|
224
|
+
for number, text in enumerate(source_lines, start=1):
|
|
225
|
+
definition = match_definition(text)
|
|
226
|
+
if definition is not None:
|
|
227
|
+
marks.append((number, definition))
|
|
228
|
+
|
|
229
|
+
found: dict[str, None] = {}
|
|
230
|
+
for line_number in changed:
|
|
231
|
+
if not 1 <= line_number <= len(source_lines):
|
|
232
|
+
continue
|
|
233
|
+
text = source_lines[line_number - 1]
|
|
234
|
+
if not text.strip():
|
|
235
|
+
continue
|
|
236
|
+
indent = len(text) - len(text.lstrip(" \t"))
|
|
237
|
+
indent = len(text[:indent].expandtabs(4))
|
|
238
|
+
chain: list[str] = []
|
|
239
|
+
limit = indent
|
|
240
|
+
for number, definition in reversed(marks):
|
|
241
|
+
if number > line_number:
|
|
242
|
+
continue
|
|
243
|
+
if number == line_number:
|
|
244
|
+
chain.append(definition.name)
|
|
245
|
+
limit = definition.indent
|
|
246
|
+
continue
|
|
247
|
+
if definition.indent < limit:
|
|
248
|
+
chain.append(definition.name)
|
|
249
|
+
limit = definition.indent
|
|
250
|
+
if limit == 0:
|
|
251
|
+
break
|
|
252
|
+
if chain:
|
|
253
|
+
found.setdefault(".".join(reversed(chain[:2])), None)
|
|
254
|
+
return list(found)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
_CSS_CLASS = re.compile(r"\.([A-Za-z_][\w-]*)")
|
|
258
|
+
_CSS_EXTENSIONS = (".css", ".scss", ".sass", ".less")
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def is_stylesheet(path: str) -> bool:
|
|
262
|
+
return path.lower().endswith(_CSS_EXTENSIONS)
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def extract_css_names(lines: Iterable[str]) -> list[str]:
|
|
266
|
+
"""Class names used as selectors (``.heatmap-cell {``), in order, once each."""
|
|
267
|
+
names: dict[str, None] = {}
|
|
268
|
+
for line in lines:
|
|
269
|
+
head, brace, _ = line.partition("{")
|
|
270
|
+
if brace and not head.lstrip().startswith(("/*", "//", "@")):
|
|
271
|
+
for match in _CSS_CLASS.finditer(head):
|
|
272
|
+
names.setdefault(match.group(1), None)
|
|
273
|
+
return list(names)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
_HEADING = re.compile(r"^(#{1,4})\s+(.+?)\s*#*\s*$")
|
|
277
|
+
_MAX_HEADING_LENGTH = 50
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def extract_headings(lines: Iterable[str], min_level: int = 2) -> list[str]:
|
|
281
|
+
"""Markdown headings of at least ``min_level`` (``##``), skipping code fences.
|
|
282
|
+
|
|
283
|
+
Level 1 is normally the document title, which says nothing about a change.
|
|
284
|
+
"""
|
|
285
|
+
headings: dict[str, None] = {}
|
|
286
|
+
fenced = False
|
|
287
|
+
for line in lines:
|
|
288
|
+
stripped = line.strip()
|
|
289
|
+
if stripped.startswith(("```", "~~~")):
|
|
290
|
+
fenced = not fenced
|
|
291
|
+
continue
|
|
292
|
+
if fenced:
|
|
293
|
+
continue
|
|
294
|
+
match = _HEADING.match(line)
|
|
295
|
+
if match and len(match.group(1)) >= min_level:
|
|
296
|
+
text = re.sub(r"[`*_\[\]]", "", match.group(2)).strip()
|
|
297
|
+
text = re.sub(r"\s+", " ", text)
|
|
298
|
+
if text and not any(unicodedata.category(c) == "Cc" for c in text):
|
|
299
|
+
headings.setdefault(text[:_MAX_HEADING_LENGTH].rstrip(), None)
|
|
300
|
+
return list(headings)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def extract_definitions(lines: Iterable[str]) -> list[Definition]:
|
|
304
|
+
"""Find function/class/type definitions (Python, JS/TS, Go, Rust).
|
|
305
|
+
|
|
306
|
+
Each name is reported once, in order of appearance.
|
|
307
|
+
"""
|
|
308
|
+
found: dict[str, Definition] = {}
|
|
309
|
+
for line in lines:
|
|
310
|
+
definition = match_definition(line)
|
|
311
|
+
if definition is not None:
|
|
312
|
+
found.setdefault(definition.name, definition)
|
|
313
|
+
return list(found.values())
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
FIX_PATTERN = re.compile(
|
|
317
|
+
r"\b(fix(?:es|ed)?|bugs?|crash(?:es)?|race condition|regression|workaround"
|
|
318
|
+
r"|off-by-one|leaks?)\b",
|
|
319
|
+
re.IGNORECASE,
|
|
320
|
+
)
|
|
321
|
+
PERF_PATTERN = re.compile(
|
|
322
|
+
r"\b(optimi[sz]\w*|performance|speed ?up|faster|memoi[sz]\w*|lru_cache"
|
|
323
|
+
r"|vectori[sz]\w*)\b",
|
|
324
|
+
re.IGNORECASE,
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def has_signal(lines: Iterable[str], pattern: re.Pattern[str]) -> bool:
|
|
329
|
+
return any(pattern.search(line) for line in lines)
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
_COMMENT_LINE = re.compile(r"^\s*(?:#|//|/\*|\*(?:\s|/|$)|<!--)")
|
|
333
|
+
_BLOCK_COMMENT_ONLY = re.compile(r"^\s*(?:/\*|\*(?:\s|/|$)|<!--)")
|
|
334
|
+
_BLOCK_COMMENT_SUFFIXES = (".css", ".scss", ".sass", ".less")
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def is_comment_only(path: str, added: Iterable[str], removed: Iterable[str]) -> bool:
|
|
338
|
+
"""True if every non-blank changed line is a comment (``#``, ``//``, ``/* */``).
|
|
339
|
+
|
|
340
|
+
Stylesheets only count ``/* */``, because ``#id {`` is a selector there.
|
|
341
|
+
"""
|
|
342
|
+
pattern = (
|
|
343
|
+
_BLOCK_COMMENT_ONLY
|
|
344
|
+
if path.lower().endswith(_BLOCK_COMMENT_SUFFIXES)
|
|
345
|
+
else _COMMENT_LINE
|
|
346
|
+
)
|
|
347
|
+
changed = [line for line in (*added, *removed) if line.strip()]
|
|
348
|
+
return bool(changed) and all(pattern.match(line) for line in changed)
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def _squash(lines: Iterable[str]) -> str:
|
|
352
|
+
return "".join("".join(line.split()) for line in lines)
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def is_formatting_only(added: Iterable[str], removed: Iterable[str]) -> bool:
|
|
356
|
+
"""True if the change only moves whitespace (indentation, wrapping, blanks)."""
|
|
357
|
+
added, removed = tuple(added), tuple(removed)
|
|
358
|
+
return bool(added or removed) and _squash(added) == _squash(removed)
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Local enrichment of a staged diff: which definitions did the change touch?
|
|
2
|
+
|
|
3
|
+
For each source file the staged version is read with ``git cat-file`` and every
|
|
4
|
+
added line is mapped to the function or class that contains it. Only
|
|
5
|
+
identifiers are kept. Nothing leaves the machine and no program from the
|
|
6
|
+
repository is executed.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import logging
|
|
12
|
+
from dataclasses import replace
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from gitgatekeeper.git.diff import DiffSummary, FileDiff, read_staged_text
|
|
16
|
+
from gitgatekeeper.git.models import ChangeType
|
|
17
|
+
from gitgatekeeper.intelligence.analysis import (
|
|
18
|
+
FileCategory,
|
|
19
|
+
categorize,
|
|
20
|
+
enclosing_definitions,
|
|
21
|
+
is_stylesheet,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
logger = logging.getLogger(__name__)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _wants_context(f: FileDiff) -> bool:
|
|
28
|
+
return (
|
|
29
|
+
f.content_read
|
|
30
|
+
and not f.binary
|
|
31
|
+
and not f.sensitive
|
|
32
|
+
and f.status is not ChangeType.DELETED
|
|
33
|
+
and bool(f.added_line_numbers)
|
|
34
|
+
and categorize(f.path) is FileCategory.SOURCE
|
|
35
|
+
and not is_stylesheet(f.path)
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def add_touched_definitions(summary: DiffSummary, repo: Path) -> DiffSummary:
|
|
40
|
+
"""Return ``summary`` with ``FileDiff.touched`` filled in where possible.
|
|
41
|
+
|
|
42
|
+
Best effort: any problem leaves a file without extra context and never
|
|
43
|
+
blocks a commit.
|
|
44
|
+
"""
|
|
45
|
+
files: list[FileDiff] = []
|
|
46
|
+
for f in summary.files:
|
|
47
|
+
if _wants_context(f):
|
|
48
|
+
try:
|
|
49
|
+
text = read_staged_text(repo, f.path)
|
|
50
|
+
except Exception: # context is optional; never block a commit
|
|
51
|
+
logger.warning("could not read staged text of %s", f.path)
|
|
52
|
+
text = None
|
|
53
|
+
if text is not None:
|
|
54
|
+
names = enclosing_definitions(text, f.added_line_numbers)
|
|
55
|
+
f = replace(f, touched=tuple(names))
|
|
56
|
+
files.append(f)
|
|
57
|
+
return DiffSummary(tuple(files))
|