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.
Files changed (52) hide show
  1. gitgatekeeper/__init__.py +10 -0
  2. gitgatekeeper/cli/main.py +1074 -0
  3. gitgatekeeper/config/__init__.py +18 -0
  4. gitgatekeeper/config/loader.py +100 -0
  5. gitgatekeeper/config/models.py +205 -0
  6. gitgatekeeper/core/__init__.py +46 -0
  7. gitgatekeeper/core/buffer.py +125 -0
  8. gitgatekeeper/core/commit_engine.py +900 -0
  9. gitgatekeeper/core/detector.py +154 -0
  10. gitgatekeeper/core/discovery.py +172 -0
  11. gitgatekeeper/core/doctor.py +220 -0
  12. gitgatekeeper/core/events.py +89 -0
  13. gitgatekeeper/core/filters.py +79 -0
  14. gitgatekeeper/core/grouping.py +139 -0
  15. gitgatekeeper/core/inactivity.py +154 -0
  16. gitgatekeeper/core/instance.py +202 -0
  17. gitgatekeeper/core/locking.py +85 -0
  18. gitgatekeeper/core/migrate.py +134 -0
  19. gitgatekeeper/core/monitor.py +408 -0
  20. gitgatekeeper/core/project_manager.py +141 -0
  21. gitgatekeeper/core/push_engine.py +441 -0
  22. gitgatekeeper/core/service.py +703 -0
  23. gitgatekeeper/core/systemd.py +223 -0
  24. gitgatekeeper/core/undo.py +104 -0
  25. gitgatekeeper/git/__init__.py +43 -0
  26. gitgatekeeper/git/analyzer.py +96 -0
  27. gitgatekeeper/git/diff.py +252 -0
  28. gitgatekeeper/git/ignore.py +36 -0
  29. gitgatekeeper/git/models.py +118 -0
  30. gitgatekeeper/git/repository.py +123 -0
  31. gitgatekeeper/git/secrets.py +150 -0
  32. gitgatekeeper/git/sensitive.py +114 -0
  33. gitgatekeeper/git/status_parser.py +134 -0
  34. gitgatekeeper/intelligence/__init__.py +23 -0
  35. gitgatekeeper/intelligence/analysis.py +358 -0
  36. gitgatekeeper/intelligence/context.py +57 -0
  37. gitgatekeeper/intelligence/message.py +117 -0
  38. gitgatekeeper/intelligence/profile.py +213 -0
  39. gitgatekeeper/intelligence/provider.py +65 -0
  40. gitgatekeeper/intelligence/rules.py +561 -0
  41. gitgatekeeper/logging_setup.py +122 -0
  42. gitgatekeeper/storage/__init__.py +16 -0
  43. gitgatekeeper/storage/database.py +235 -0
  44. gitgatekeeper/storage/history.py +440 -0
  45. gitgatekeeper/storage/models.py +78 -0
  46. gitgatekeeper/storage/recorder.py +178 -0
  47. gitgatekeeper-0.1.1.dist-info/METADATA +671 -0
  48. gitgatekeeper-0.1.1.dist-info/RECORD +52 -0
  49. gitgatekeeper-0.1.1.dist-info/WHEEL +5 -0
  50. gitgatekeeper-0.1.1.dist-info/entry_points.txt +2 -0
  51. gitgatekeeper-0.1.1.dist-info/licenses/LICENSE +21 -0
  52. gitgatekeeper-0.1.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,117 @@
1
+ """Commit message model and Conventional Commits validation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass
7
+ from enum import StrEnum
8
+
9
+ MAX_HEADER_LENGTH = 72
10
+
11
+
12
+ class CommitType(StrEnum):
13
+ FEAT = "feat"
14
+ FIX = "fix"
15
+ REFACTOR = "refactor"
16
+ DOCS = "docs"
17
+ TEST = "test"
18
+ CHORE = "chore"
19
+ PERF = "perf"
20
+ STYLE = "style"
21
+ BUILD = "build"
22
+ CI = "ci"
23
+
24
+
25
+ class Confidence(StrEnum):
26
+ """How much the evidence supports the chosen commit *type*."""
27
+
28
+ HIGH = "high"
29
+ MEDIUM = "medium"
30
+ LOW = "low"
31
+
32
+
33
+ @dataclass(frozen=True, slots=True)
34
+ class CommitMessage:
35
+ type: CommitType
36
+ subject: str
37
+ scope: str | None = None
38
+ body: str = ""
39
+ confidence: Confidence = Confidence.MEDIUM
40
+ reasons: tuple[str, ...] = () # why the generator decided what it did
41
+
42
+ @property
43
+ def header(self) -> str:
44
+ scope = f"({self.scope})" if self.scope else ""
45
+ return f"{self.type.value}{scope}: {self.subject}"
46
+
47
+ @property
48
+ def text(self) -> str:
49
+ """The full message, ready to pass to ``git commit``."""
50
+ return f"{self.header}\n\n{self.body}" if self.body else self.header
51
+
52
+
53
+ _HEADER = re.compile(
54
+ r"^(?P<type>[a-z]+)(?:\((?P<scope>[a-z0-9][a-z0-9._/-]*)\))?!?: (?P<subject>\S.*)$"
55
+ )
56
+
57
+ GENERIC_SUBJECTS = frozenset(
58
+ {
59
+ "update",
60
+ "updates",
61
+ "update file",
62
+ "update files",
63
+ "update code",
64
+ "change",
65
+ "changes",
66
+ "misc",
67
+ "stuff",
68
+ "wip",
69
+ "fix",
70
+ "fixes",
71
+ "fix bug",
72
+ "fix bugs",
73
+ "fix issue",
74
+ "fix issues",
75
+ "improvements",
76
+ "minor changes",
77
+ "various changes",
78
+ "cleanup",
79
+ "refactor",
80
+ "refactoring",
81
+ }
82
+ )
83
+
84
+
85
+ def validate_message(
86
+ text: str, *, max_header_length: int = MAX_HEADER_LENGTH
87
+ ) -> list[str]:
88
+ """Return the problems found in ``text``; an empty list means it is valid.
89
+
90
+ Used on messages from any generator, in particular future language-model
91
+ ones, before they are allowed anywhere near a commit.
92
+ """
93
+ if not text.strip():
94
+ return ["message is empty"]
95
+
96
+ lines = text.split("\n")
97
+ header = lines[0]
98
+ problems: list[str] = []
99
+
100
+ match = _HEADER.match(header)
101
+ if match is None:
102
+ problems.append("header must look like 'type(scope): subject'")
103
+ else:
104
+ if match["type"] not in {t.value for t in CommitType}:
105
+ problems.append(f"unknown commit type {match['type']!r}")
106
+ subject = match["subject"]
107
+ if subject.endswith("."):
108
+ problems.append("subject must not end with a period")
109
+ if subject.strip().lower() in GENERIC_SUBJECTS:
110
+ problems.append(f"subject is too generic: {subject!r}")
111
+ if len(header) > max_header_length:
112
+ problems.append(
113
+ f"header is {len(header)} characters (limit {max_header_length})"
114
+ )
115
+ if len(lines) > 1 and lines[1].strip():
116
+ problems.append("a blank line must separate the header from the body")
117
+ return problems
@@ -0,0 +1,213 @@
1
+ """A local picture of how a project is organised.
2
+
3
+ The profile answers one question for the message generator: *which part of the
4
+ project does this file belong to?* That name becomes the commit scope
5
+ (``feat(activity): ...``) and is used to group the commit body.
6
+
7
+ It is detected from the repository itself (the list of tracked files, read with
8
+ ``git ls-files``) and can be refined by the user with a ``modules`` block in the
9
+ project's YAML configuration. Nothing here uses the network.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import fnmatch
15
+ import logging
16
+ import re
17
+ from collections import Counter
18
+ from collections.abc import Mapping, Sequence
19
+ from dataclasses import dataclass, field
20
+ from pathlib import Path, PurePosixPath
21
+
22
+ from gitgatekeeper.git.repository import GitError, run_git
23
+ from gitgatekeeper.intelligence.analysis import is_stylesheet
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+ MAX_TRACKED_FILES = 50_000
28
+ LS_FILES_TIMEOUT_SECONDS = 20.0
29
+
30
+ # Folders that only say *what kind* of thing lives in them, not *what it is for*.
31
+ _GENERIC_DIRS = frozenset(
32
+ {
33
+ "src", "lib", "app", "apps", "tests", "test", "docs", "doc", "public",
34
+ "assets", "static", "resources", "includes", "inc", "source", "sources",
35
+ }
36
+ ) # fmt: skip
37
+ _ROLE_DIRS = frozenset(
38
+ {
39
+ "http", "controllers", "models", "services", "repositories", "views",
40
+ "templates", "handlers", "middleware", "utils", "helpers", "components",
41
+ "pages", "routes", "entities", "providers", "partials", "layouts",
42
+ "exceptions", "interfaces", "traits", "dto", "dtos",
43
+ }
44
+ ) # fmt: skip
45
+ _ROLE_WORDS = frozenset(
46
+ {
47
+ "controller", "service", "repository", "model", "manager", "handler",
48
+ "provider", "factory", "middleware", "request", "resource", "command",
49
+ "event", "listener", "job", "policy", "view", "helper", "store",
50
+ "exception", "interface", "trait", "test", "tests", "spec",
51
+ }
52
+ ) # fmt: skip
53
+ _GENERIC_STEMS = frozenset(
54
+ {"index", "main", "app", "__init__", "__main__", "setup", "conftest", "init"}
55
+ )
56
+ _MARKERS = {
57
+ "pyproject.toml": "python",
58
+ "setup.py": "python",
59
+ "requirements.txt": "python",
60
+ "composer.json": "php",
61
+ "package.json": "node",
62
+ "go.mod": "go",
63
+ "Cargo.toml": "rust",
64
+ "pom.xml": "java",
65
+ "build.gradle": "java",
66
+ "Gemfile": "ruby",
67
+ }
68
+ _LANGUAGES = {
69
+ ".py": "Python", ".php": "PHP", ".js": "JavaScript", ".mjs": "JavaScript",
70
+ ".ts": "TypeScript", ".tsx": "TypeScript", ".jsx": "JavaScript", ".go": "Go",
71
+ ".rs": "Rust", ".java": "Java", ".kt": "Kotlin", ".rb": "Ruby", ".cs": "C#",
72
+ ".c": "C", ".h": "C", ".cpp": "C++", ".swift": "Swift", ".sh": "Shell",
73
+ ".html": "HTML", ".css": "CSS", ".scss": "CSS", ".vue": "Vue",
74
+ ".svelte": "Svelte",
75
+ } # fmt: skip
76
+ _VIEW_SUFFIXES = (
77
+ ".twig", ".blade.php", ".jinja", ".jinja2", ".j2", ".erb", ".hbs", ".vue",
78
+ ".svelte", ".html", ".htm",
79
+ ) # fmt: skip
80
+ _SLUG_INVALID = re.compile(r"[^a-z0-9._-]+")
81
+ _MODULE_NAME = re.compile(r"^[a-z0-9][a-z0-9._-]*$")
82
+
83
+
84
+ def slugify(text: str) -> str | None:
85
+ """CamelCase / snake_case / free text -> a valid commit scope, or ``None``."""
86
+ spaced = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "-", text)
87
+ slug = _SLUG_INVALID.sub("-", spaced.lower().replace("_", "-")).strip("-._")
88
+ slug = re.sub(r"-{2,}", "-", slug)
89
+ return slug if slug and _MODULE_NAME.match(slug) else None
90
+
91
+
92
+ def module_from_filename(path: str) -> str | None:
93
+ """Name a module after its file: ``ActivityService.php`` -> ``activity``."""
94
+ name = PurePosixPath(path).name
95
+ stem = name.split(".", 1)[0]
96
+ if not stem or stem.lower() in _GENERIC_STEMS:
97
+ return None
98
+ words = re.findall(r"[A-Z]+(?![a-z])|[A-Z]?[a-z0-9]+", stem.replace("_", " "))
99
+ if len(words) > 1 and words[-1].lower() in _ROLE_WORDS:
100
+ words = words[:-1]
101
+ return slugify("-".join(w.lower() for w in words))
102
+
103
+
104
+ @dataclass(frozen=True, slots=True)
105
+ class ModuleRule:
106
+ """A user-defined module: a name and the paths (prefixes or globs) it owns."""
107
+
108
+ name: str
109
+ patterns: tuple[str, ...]
110
+
111
+ def matches(self, path: str) -> bool:
112
+ for pattern in self.patterns:
113
+ if any(c in pattern for c in "*?["):
114
+ if fnmatch.fnmatchcase(path, pattern):
115
+ return True
116
+ else:
117
+ prefix = pattern.rstrip("/")
118
+ if path == prefix or path.startswith(prefix + "/"):
119
+ return True
120
+ return False
121
+
122
+
123
+ @dataclass(frozen=True, slots=True)
124
+ class ProjectProfile:
125
+ languages: tuple[str, ...] = ()
126
+ kinds: tuple[str, ...] = () # "python", "php", "node", ...
127
+ python_packages: frozenset[str] = field(default_factory=frozenset)
128
+ rules: tuple[ModuleRule, ...] = ()
129
+ tracked_files: int = 0
130
+
131
+ def module_for(self, path: str) -> str | None:
132
+ """The module ``path`` belongs to, or ``None`` when it has no clear one."""
133
+ for rule in self.rules:
134
+ if rule.matches(path):
135
+ return rule.name
136
+ pure = PurePosixPath(path)
137
+ dirs = list(pure.parts[:-1])
138
+ if dirs and dirs[0] == "src":
139
+ dirs = dirs[1:]
140
+ if dirs and dirs[0] in self.python_packages:
141
+ dirs = dirs[1:]
142
+ for part in dirs:
143
+ lowered = part.lower()
144
+ if part.startswith("."):
145
+ return None # tooling folders (.github, .circleci) are not modules
146
+ if lowered in _GENERIC_DIRS:
147
+ continue
148
+ if lowered in _ROLE_DIRS:
149
+ continue
150
+ return slugify(part)
151
+ if is_stylesheet(path):
152
+ return "styles"
153
+ return module_from_filename(path)
154
+
155
+ def describe(self) -> dict[str, object]:
156
+ return {
157
+ "languages": list(self.languages),
158
+ "kinds": list(self.kinds),
159
+ "python_packages": sorted(self.python_packages),
160
+ "modules": {r.name: list(r.patterns) for r in self.rules},
161
+ "tracked_files": self.tracked_files,
162
+ }
163
+
164
+
165
+ def build_rules(modules: Mapping[str, Sequence[str]] | None) -> tuple[ModuleRule, ...]:
166
+ return tuple(
167
+ ModuleRule(name, tuple(patterns)) for name, patterns in (modules or {}).items()
168
+ )
169
+
170
+
171
+ def detect_profile(
172
+ repo: Path, modules: Mapping[str, Sequence[str]] | None = None
173
+ ) -> ProjectProfile:
174
+ """Inspect ``repo`` (read-only) and return its profile.
175
+
176
+ Never raises: if Git cannot list the files the profile only carries the
177
+ user's rules.
178
+ """
179
+ rules = build_rules(modules)
180
+ try:
181
+ result = run_git(
182
+ ["ls-files", "-z", "--cached"], cwd=repo, timeout=LS_FILES_TIMEOUT_SECONDS
183
+ )
184
+ except (GitError, OSError):
185
+ return ProjectProfile(rules=rules)
186
+ if result.returncode != 0:
187
+ return ProjectProfile(rules=rules)
188
+
189
+ files = [f for f in result.stdout.split("\0") if f][:MAX_TRACKED_FILES]
190
+ counts: Counter[str] = Counter()
191
+ kinds: dict[str, None] = {}
192
+ packages: set[str] = set()
193
+ for path in files:
194
+ pure = PurePosixPath(path)
195
+ language = _LANGUAGES.get(pure.suffix.lower())
196
+ if language:
197
+ counts[language] += 1
198
+ marker = _MARKERS.get(pure.name)
199
+ if marker and len(pure.parts) == 1:
200
+ kinds.setdefault(marker, None)
201
+ if (
202
+ len(pure.parts) == 3
203
+ and pure.parts[0] == "src"
204
+ and pure.name == "__init__.py"
205
+ ):
206
+ packages.add(pure.parts[1])
207
+ return ProjectProfile(
208
+ languages=tuple(name for name, _ in counts.most_common(4)),
209
+ kinds=tuple(kinds),
210
+ python_packages=frozenset(packages),
211
+ rules=rules,
212
+ tracked_files=len(files),
213
+ )
@@ -0,0 +1,65 @@
1
+ """Pluggable message generation with a safe fallback.
2
+
3
+ A language-model generator can be plugged in later by implementing
4
+ :class:`MessageGenerator`. Nothing here requires an external API: without a
5
+ custom generator, the rule-based one is used. A custom generator that raises or
6
+ returns an invalid or generic message is replaced by the rules, so a flaky or
7
+ careless model can never block or pollute a commit.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import logging
13
+ from dataclasses import replace
14
+ from typing import Protocol
15
+
16
+ from gitgatekeeper.git.diff import DiffSummary
17
+ from gitgatekeeper.intelligence.message import (
18
+ MAX_HEADER_LENGTH,
19
+ CommitMessage,
20
+ validate_message,
21
+ )
22
+ from gitgatekeeper.intelligence.rules import RuleBasedGenerator
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+
27
+ class MessageGenerator(Protocol):
28
+ def generate(self, summary: DiffSummary) -> CommitMessage: ...
29
+
30
+
31
+ def generate_commit_message(
32
+ summary: DiffSummary,
33
+ *,
34
+ generator: MessageGenerator | None = None,
35
+ fallback: MessageGenerator | None = None,
36
+ max_header_length: int = MAX_HEADER_LENGTH,
37
+ ) -> CommitMessage:
38
+ """Return a valid commit message for ``summary``.
39
+
40
+ ``generator`` is tried first when given; ``fallback`` (default: the
41
+ rule-based generator) is used if it fails or its output is rejected.
42
+ """
43
+ rules = fallback or RuleBasedGenerator(max_header_length=max_header_length)
44
+ if generator is None:
45
+ return rules.generate(summary)
46
+
47
+ note: str
48
+ try:
49
+ message = generator.generate(summary)
50
+ except Exception:
51
+ # The generator is foreign code (possibly a network call): contain it.
52
+ logger.warning("custom message generator failed", exc_info=True)
53
+ note = "custom generator raised an error"
54
+ else:
55
+ problems = validate_message(message.text, max_header_length=max_header_length)
56
+ if not problems:
57
+ return message
58
+ logger.warning("rejected generated message: %s", "; ".join(problems))
59
+ note = f"custom generator output rejected: {'; '.join(problems)}"
60
+
61
+ fallback_message = rules.generate(summary)
62
+ return replace(
63
+ fallback_message,
64
+ reasons=(*fallback_message.reasons, f"fell back to rules: {note}"),
65
+ )