margin-core 0.1.0__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.
- margin_core/__init__.py +68 -0
- margin_core/_fs.py +37 -0
- margin_core/agent.py +255 -0
- margin_core/config.py +184 -0
- margin_core/errors.py +49 -0
- margin_core/inputs.py +71 -0
- margin_core/llm/__init__.py +30 -0
- margin_core/llm/_chat_completions.py +34 -0
- margin_core/llm/_http.py +42 -0
- margin_core/llm/anthropic.py +80 -0
- margin_core/llm/base.py +338 -0
- margin_core/llm/catalog.py +126 -0
- margin_core/llm/factory.py +75 -0
- margin_core/llm/local.py +196 -0
- margin_core/llm/mock.py +85 -0
- margin_core/llm/openai.py +62 -0
- margin_core/llm/pricing.py +55 -0
- margin_core/loaders/__init__.py +53 -0
- margin_core/loaders/base.py +213 -0
- margin_core/loaders/filters.py +247 -0
- margin_core/loaders/git.py +176 -0
- margin_core/loaders/github.py +186 -0
- margin_core/loaders/local.py +163 -0
- margin_core/logging.py +20 -0
- margin_core/models.py +130 -0
- margin_core/py.typed +1 -0
- margin_core/registry.py +111 -0
- margin_core/reporting/__init__.py +6 -0
- margin_core/reporting/json_report.py +18 -0
- margin_core/reporting/markdown_report.py +84 -0
- margin_core/runner.py +27 -0
- margin_core-0.1.0.dist-info/METADATA +106 -0
- margin_core-0.1.0.dist-info/RECORD +35 -0
- margin_core-0.1.0.dist-info/WHEEL +4 -0
- margin_core-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""Rules deciding which files a workspace keeps.
|
|
2
|
+
|
|
3
|
+
Two passes: :func:`classify_path` (name-only, cheap) and :func:`classify_content`
|
|
4
|
+
(inspects the first few KB). Every exclusion carries a reason string.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import fnmatch
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from pathlib import PurePosixPath
|
|
12
|
+
|
|
13
|
+
from pydantic import BaseModel, Field
|
|
14
|
+
|
|
15
|
+
HEAD_BYTES = 8192
|
|
16
|
+
|
|
17
|
+
# Directories that are always skipped (tooling, caches, build output).
|
|
18
|
+
IGNORED_DIRS = frozenset(
|
|
19
|
+
{
|
|
20
|
+
".git",
|
|
21
|
+
".hg",
|
|
22
|
+
".svn",
|
|
23
|
+
"node_modules",
|
|
24
|
+
"bower_components",
|
|
25
|
+
"__pycache__",
|
|
26
|
+
".venv",
|
|
27
|
+
"venv",
|
|
28
|
+
".tox",
|
|
29
|
+
".nox",
|
|
30
|
+
".mypy_cache",
|
|
31
|
+
".pytest_cache",
|
|
32
|
+
".ruff_cache",
|
|
33
|
+
".gradle",
|
|
34
|
+
".next",
|
|
35
|
+
".nuxt",
|
|
36
|
+
".turbo",
|
|
37
|
+
".cache",
|
|
38
|
+
"dist",
|
|
39
|
+
"build",
|
|
40
|
+
"coverage",
|
|
41
|
+
"htmlcov",
|
|
42
|
+
".idea",
|
|
43
|
+
".vscode",
|
|
44
|
+
}
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
# Third-party code checked into the repo. Skipped unless include_vendored=True.
|
|
48
|
+
VENDORED_DIRS = frozenset({"vendor", "vendors", "third_party", "third-party", "external", "deps"})
|
|
49
|
+
|
|
50
|
+
LOCKFILES = frozenset(
|
|
51
|
+
{
|
|
52
|
+
"package-lock.json",
|
|
53
|
+
"npm-shrinkwrap.json",
|
|
54
|
+
"yarn.lock",
|
|
55
|
+
"pnpm-lock.yaml",
|
|
56
|
+
"bun.lockb",
|
|
57
|
+
"poetry.lock",
|
|
58
|
+
"uv.lock",
|
|
59
|
+
"Pipfile.lock",
|
|
60
|
+
"pdm.lock",
|
|
61
|
+
"Cargo.lock",
|
|
62
|
+
"Gemfile.lock",
|
|
63
|
+
"composer.lock",
|
|
64
|
+
"go.sum",
|
|
65
|
+
"mix.lock",
|
|
66
|
+
"pubspec.lock",
|
|
67
|
+
"packages.lock.json",
|
|
68
|
+
"flake.lock",
|
|
69
|
+
}
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
BINARY_EXTENSIONS = frozenset(
|
|
73
|
+
{
|
|
74
|
+
# images
|
|
75
|
+
".png", ".jpg", ".jpeg", ".gif", ".bmp", ".ico", ".webp", ".tiff", ".psd", ".svgz",
|
|
76
|
+
# audio / video
|
|
77
|
+
".mp3", ".wav", ".ogg", ".flac", ".mp4", ".mov", ".avi", ".mkv", ".webm",
|
|
78
|
+
# archives
|
|
79
|
+
".zip", ".tar", ".gz", ".tgz", ".bz2", ".xz", ".7z", ".rar", ".jar", ".war", ".whl",
|
|
80
|
+
# binaries / objects
|
|
81
|
+
".exe", ".dll", ".so", ".dylib", ".bin", ".o", ".a", ".lib", ".class", ".pyc", ".pyo",
|
|
82
|
+
".wasm",
|
|
83
|
+
# documents / fonts / data
|
|
84
|
+
".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx",
|
|
85
|
+
".ttf", ".otf", ".woff", ".woff2", ".eot",
|
|
86
|
+
".db", ".sqlite", ".sqlite3", ".parquet", ".npy", ".npz", ".pkl", ".pt", ".onnx",
|
|
87
|
+
}
|
|
88
|
+
) # fmt: skip
|
|
89
|
+
|
|
90
|
+
MINIFIED_SUFFIXES = (".min.js", ".min.css", ".min.mjs", ".js.map", ".css.map", ".map")
|
|
91
|
+
|
|
92
|
+
GENERATED_SUFFIXES = (
|
|
93
|
+
"_pb2.py",
|
|
94
|
+
"_pb2.pyi",
|
|
95
|
+
"_pb2_grpc.py",
|
|
96
|
+
".pb.go",
|
|
97
|
+
".pb.cc",
|
|
98
|
+
".pb.h",
|
|
99
|
+
".pb.swift",
|
|
100
|
+
".g.dart",
|
|
101
|
+
".freezed.dart",
|
|
102
|
+
".designer.cs",
|
|
103
|
+
".generated.ts",
|
|
104
|
+
".generated.js",
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
GENERATED_MARKERS = (
|
|
108
|
+
b"@generated",
|
|
109
|
+
b"DO NOT EDIT",
|
|
110
|
+
b"Code generated by",
|
|
111
|
+
b"auto-generated",
|
|
112
|
+
b"autogenerated",
|
|
113
|
+
b"This file was automatically generated",
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
MINIFIABLE_EXTENSIONS = frozenset({".js", ".mjs", ".cjs", ".css"})
|
|
117
|
+
|
|
118
|
+
LANGUAGE_BY_EXTENSION: dict[str, str] = {
|
|
119
|
+
".py": "python", ".pyi": "python",
|
|
120
|
+
".js": "javascript", ".mjs": "javascript", ".cjs": "javascript", ".jsx": "javascript",
|
|
121
|
+
".ts": "typescript", ".tsx": "typescript", ".mts": "typescript", ".cts": "typescript",
|
|
122
|
+
".java": "java", ".kt": "kotlin", ".kts": "kotlin", ".scala": "scala",
|
|
123
|
+
".go": "go", ".rs": "rust", ".rb": "ruby", ".php": "php", ".swift": "swift",
|
|
124
|
+
".c": "c", ".h": "c", ".cc": "cpp", ".cpp": "cpp", ".cxx": "cpp", ".hpp": "cpp",
|
|
125
|
+
".cs": "csharp", ".fs": "fsharp", ".dart": "dart", ".lua": "lua", ".r": "r",
|
|
126
|
+
".m": "objective-c", ".mm": "objective-c", ".ex": "elixir", ".exs": "elixir",
|
|
127
|
+
".erl": "erlang", ".hs": "haskell", ".clj": "clojure", ".jl": "julia", ".zig": "zig",
|
|
128
|
+
".sh": "shell", ".bash": "shell", ".zsh": "shell", ".ps1": "powershell",
|
|
129
|
+
".sql": "sql", ".html": "html", ".htm": "html", ".css": "css", ".scss": "scss",
|
|
130
|
+
".vue": "vue", ".svelte": "svelte",
|
|
131
|
+
".md": "markdown", ".rst": "restructuredtext", ".txt": "text",
|
|
132
|
+
".json": "json", ".yaml": "yaml", ".yml": "yaml", ".toml": "toml", ".xml": "xml",
|
|
133
|
+
".ini": "ini", ".cfg": "ini", ".svg": "svg",
|
|
134
|
+
} # fmt: skip
|
|
135
|
+
|
|
136
|
+
LANGUAGE_BY_FILENAME: dict[str, str] = {
|
|
137
|
+
"Dockerfile": "dockerfile",
|
|
138
|
+
"Makefile": "makefile",
|
|
139
|
+
"CMakeLists.txt": "cmake",
|
|
140
|
+
"Jenkinsfile": "groovy",
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class FilterConfig(BaseModel):
|
|
145
|
+
"""User-tunable filter behaviour."""
|
|
146
|
+
|
|
147
|
+
include_vendored: bool = False
|
|
148
|
+
include_generated: bool = False
|
|
149
|
+
extra_ignored_dirs: frozenset[str] = Field(default_factory=frozenset)
|
|
150
|
+
extra_ignored_globs: tuple[str, ...] = ()
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
@dataclass(frozen=True)
|
|
154
|
+
class FilterDecision:
|
|
155
|
+
"""Outcome of a filter check."""
|
|
156
|
+
|
|
157
|
+
keep: bool
|
|
158
|
+
reason: str | None = None
|
|
159
|
+
is_generated: bool = False
|
|
160
|
+
is_vendored: bool = False
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
KEEP = FilterDecision(keep=True)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def ignored_dir_reason(name: str, config: FilterConfig | None = None) -> str | None:
|
|
167
|
+
"""Reason to skip a whole directory by name, or ``None`` to descend into it."""
|
|
168
|
+
config = config or FilterConfig()
|
|
169
|
+
if name in IGNORED_DIRS or name in config.extra_ignored_dirs:
|
|
170
|
+
return "ignored_dir"
|
|
171
|
+
if name in VENDORED_DIRS and not config.include_vendored:
|
|
172
|
+
return "vendored"
|
|
173
|
+
return None
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def classify_path(rel_path: str, config: FilterConfig | None = None) -> FilterDecision:
|
|
177
|
+
"""Name-based rules (lockfiles, binaries, minified, generated, globs, dirs)."""
|
|
178
|
+
config = config or FilterConfig()
|
|
179
|
+
path = PurePosixPath(rel_path)
|
|
180
|
+
name = path.name
|
|
181
|
+
lower = name.lower()
|
|
182
|
+
|
|
183
|
+
for pattern in config.extra_ignored_globs:
|
|
184
|
+
if fnmatch.fnmatch(rel_path, pattern) or fnmatch.fnmatch(name, pattern):
|
|
185
|
+
return FilterDecision(keep=False, reason="ignored_glob")
|
|
186
|
+
|
|
187
|
+
is_vendored = False
|
|
188
|
+
for part in path.parts[:-1]:
|
|
189
|
+
reason = ignored_dir_reason(part, config)
|
|
190
|
+
if reason:
|
|
191
|
+
return FilterDecision(keep=False, reason=reason)
|
|
192
|
+
if part in VENDORED_DIRS:
|
|
193
|
+
is_vendored = True
|
|
194
|
+
|
|
195
|
+
if name in LOCKFILES:
|
|
196
|
+
return FilterDecision(keep=False, reason="lockfile")
|
|
197
|
+
if path.suffix.lower() in BINARY_EXTENSIONS:
|
|
198
|
+
return FilterDecision(keep=False, reason="binary")
|
|
199
|
+
if lower.endswith(MINIFIED_SUFFIXES):
|
|
200
|
+
return FilterDecision(keep=False, reason="minified")
|
|
201
|
+
if lower.endswith(GENERATED_SUFFIXES):
|
|
202
|
+
if not config.include_generated:
|
|
203
|
+
return FilterDecision(keep=False, reason="generated")
|
|
204
|
+
return FilterDecision(keep=True, is_generated=True, is_vendored=is_vendored)
|
|
205
|
+
return FilterDecision(keep=True, is_vendored=is_vendored)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def looks_binary(head: bytes) -> bool:
|
|
209
|
+
return b"\x00" in head
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def looks_minified(rel_path: str, head: bytes) -> bool:
|
|
213
|
+
"""Very long lines in a JS/CSS file indicate minified/bundled output."""
|
|
214
|
+
if PurePosixPath(rel_path).suffix.lower() not in MINIFIABLE_EXTENSIONS:
|
|
215
|
+
return False
|
|
216
|
+
if len(head) < 2000:
|
|
217
|
+
return False
|
|
218
|
+
lines = head.count(b"\n") + 1
|
|
219
|
+
return len(head) / lines > 300
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def has_generated_marker(head: bytes) -> bool:
|
|
223
|
+
first_lines = b"\n".join(head.splitlines()[:5])
|
|
224
|
+
return any(marker in first_lines for marker in GENERATED_MARKERS)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def classify_content(
|
|
228
|
+
rel_path: str, head: bytes, config: FilterConfig | None = None
|
|
229
|
+
) -> FilterDecision:
|
|
230
|
+
"""Content-based rules applied to the first :data:`HEAD_BYTES` of a file."""
|
|
231
|
+
config = config or FilterConfig()
|
|
232
|
+
if looks_binary(head):
|
|
233
|
+
return FilterDecision(keep=False, reason="binary")
|
|
234
|
+
if looks_minified(rel_path, head):
|
|
235
|
+
return FilterDecision(keep=False, reason="minified")
|
|
236
|
+
if has_generated_marker(head):
|
|
237
|
+
if not config.include_generated:
|
|
238
|
+
return FilterDecision(keep=False, reason="generated")
|
|
239
|
+
return FilterDecision(keep=True, is_generated=True)
|
|
240
|
+
return KEEP
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def detect_language(rel_path: str) -> str | None:
|
|
244
|
+
path = PurePosixPath(rel_path)
|
|
245
|
+
if path.name in LANGUAGE_BY_FILENAME:
|
|
246
|
+
return LANGUAGE_BY_FILENAME[path.name]
|
|
247
|
+
return LANGUAGE_BY_EXTENSION.get(path.suffix.lower())
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""Thin wrappers around the ``git`` CLI. Repository code is never executed."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import os
|
|
7
|
+
import shutil
|
|
8
|
+
import subprocess
|
|
9
|
+
from datetime import datetime
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from margin_core.loaders.base import GitCommit, GitInfo
|
|
13
|
+
from margin_core.logging import get_logger
|
|
14
|
+
|
|
15
|
+
logger = get_logger("git")
|
|
16
|
+
|
|
17
|
+
RECORD_SEP = "\x1e"
|
|
18
|
+
FIELD_SEP = "\x1f"
|
|
19
|
+
_LOG_FORMAT = RECORD_SEP + FIELD_SEP.join(
|
|
20
|
+
["%H", "%an", "%ae", "%aI", "%cn", "%ce", "%cI", "%P", "%B"]
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class GitCommandError(RuntimeError):
|
|
25
|
+
"""A git command exited with a non-zero status."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def git_available() -> bool:
|
|
29
|
+
return shutil.which("git") is not None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def safe_git_env() -> dict[str, str]:
|
|
33
|
+
"""Environment that prevents git from ever prompting (terminal, GUI, credential manager)."""
|
|
34
|
+
env = dict(os.environ)
|
|
35
|
+
env.update(
|
|
36
|
+
{
|
|
37
|
+
"GIT_TERMINAL_PROMPT": "0",
|
|
38
|
+
"GIT_ASKPASS": "",
|
|
39
|
+
"SSH_ASKPASS": "",
|
|
40
|
+
"GCM_INTERACTIVE": "never",
|
|
41
|
+
}
|
|
42
|
+
)
|
|
43
|
+
return env
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def run_git(args: list[str], cwd: Path | None = None, timeout_s: float = 60.0) -> str:
|
|
47
|
+
"""Run ``git <args>`` and return stdout (UTF-8). Raises :class:`GitCommandError`."""
|
|
48
|
+
cmd = ["git", "-c", "i18n.logOutputEncoding=UTF-8", *args]
|
|
49
|
+
proc = subprocess.run(
|
|
50
|
+
cmd,
|
|
51
|
+
cwd=cwd,
|
|
52
|
+
capture_output=True,
|
|
53
|
+
timeout=timeout_s,
|
|
54
|
+
env=safe_git_env(),
|
|
55
|
+
stdin=subprocess.DEVNULL,
|
|
56
|
+
check=False,
|
|
57
|
+
)
|
|
58
|
+
if proc.returncode != 0:
|
|
59
|
+
stderr = proc.stderr.decode("utf-8", errors="replace").strip()
|
|
60
|
+
raise GitCommandError(f"git {' '.join(args)} failed: {stderr}")
|
|
61
|
+
return proc.stdout.decode("utf-8", errors="replace")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def detect_git(path: Path, scopes: list[str] | None = None) -> GitInfo | None:
|
|
65
|
+
"""Return :class:`GitInfo` if ``path`` is inside a git work tree, else ``None``.
|
|
66
|
+
|
|
67
|
+
History is limited to ``path`` (when it is a sub-folder of the repository) and, within
|
|
68
|
+
it, to ``scopes`` (workspace-relative paths), so commit signals only describe the code
|
|
69
|
+
being analysed.
|
|
70
|
+
"""
|
|
71
|
+
if not git_available():
|
|
72
|
+
return None
|
|
73
|
+
try:
|
|
74
|
+
top = run_git(["rev-parse", "--show-toplevel"], cwd=path).strip()
|
|
75
|
+
except (GitCommandError, OSError, subprocess.TimeoutExpired):
|
|
76
|
+
return None
|
|
77
|
+
root = Path(top)
|
|
78
|
+
try:
|
|
79
|
+
prefix = path.resolve().relative_to(root.resolve()).as_posix()
|
|
80
|
+
except ValueError:
|
|
81
|
+
logger.warning("Could not place %s inside repository %s; using full history", path, root)
|
|
82
|
+
prefix = "."
|
|
83
|
+
prefix = "" if prefix == "." else prefix
|
|
84
|
+
pathspecs = [f"{prefix}/{s}" if prefix else s for s in scopes or [] if s]
|
|
85
|
+
if not pathspecs and prefix:
|
|
86
|
+
pathspecs = [prefix]
|
|
87
|
+
head: str | None
|
|
88
|
+
try:
|
|
89
|
+
head = run_git(["rev-parse", "HEAD"], cwd=root).strip()
|
|
90
|
+
except GitCommandError:
|
|
91
|
+
head = None # repository without commits
|
|
92
|
+
try:
|
|
93
|
+
branch = run_git(["rev-parse", "--abbrev-ref", "HEAD"], cwd=root).strip() or None
|
|
94
|
+
except GitCommandError:
|
|
95
|
+
branch = None
|
|
96
|
+
return GitInfo(root=root, head=head, branch=branch, prefix=prefix, pathspecs=pathspecs)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def parse_log(output: str) -> list[GitCommit]:
|
|
100
|
+
"""Parse output produced with :data:`_LOG_FORMAT`."""
|
|
101
|
+
commits: list[GitCommit] = []
|
|
102
|
+
for record in output.split(RECORD_SEP):
|
|
103
|
+
if not record.strip():
|
|
104
|
+
continue
|
|
105
|
+
fields = record.split(FIELD_SEP, 8)
|
|
106
|
+
if len(fields) != 9:
|
|
107
|
+
logger.warning("Skipping malformed git log record")
|
|
108
|
+
continue
|
|
109
|
+
sha, an, ae, ad, cn, ce, cd, parents, message = fields
|
|
110
|
+
commits.append(
|
|
111
|
+
GitCommit(
|
|
112
|
+
sha=sha.strip(),
|
|
113
|
+
author_name=an,
|
|
114
|
+
author_email=ae,
|
|
115
|
+
authored_at=datetime.fromisoformat(ad),
|
|
116
|
+
committer_name=cn,
|
|
117
|
+
committer_email=ce,
|
|
118
|
+
committed_at=datetime.fromisoformat(cd),
|
|
119
|
+
parents=parents.split(),
|
|
120
|
+
message=message.strip("\n"),
|
|
121
|
+
)
|
|
122
|
+
)
|
|
123
|
+
return commits
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _pathspec_args(pathspecs: list[str] | None) -> list[str]:
|
|
127
|
+
return ["--", *pathspecs] if pathspecs else []
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def read_commits_sync(
|
|
131
|
+
root: Path, max_count: int | None = None, pathspecs: list[str] | None = None
|
|
132
|
+
) -> list[GitCommit]:
|
|
133
|
+
args = ["log", f"--format={_LOG_FORMAT}"]
|
|
134
|
+
if max_count is not None:
|
|
135
|
+
args.append(f"--max-count={max_count}")
|
|
136
|
+
return parse_log(run_git(args + _pathspec_args(pathspecs), cwd=root, timeout_s=120.0))
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
async def read_commits(
|
|
140
|
+
root: Path, max_count: int | None = None, pathspecs: list[str] | None = None
|
|
141
|
+
) -> list[GitCommit]:
|
|
142
|
+
return await asyncio.to_thread(read_commits_sync, root, max_count, pathspecs)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def read_changed_files_sync(
|
|
146
|
+
root: Path, pathspecs: list[str] | None = None, max_count: int | None = None
|
|
147
|
+
) -> list[tuple[str, list[str]]]:
|
|
148
|
+
"""``(sha, repo-relative paths)`` per commit, newest first, without reading any blob.
|
|
149
|
+
|
|
150
|
+
Only ``--name-only --no-renames`` is safe on blobless clones: ``--numstat``, ``--stat``,
|
|
151
|
+
``-p`` and rename detection need file contents and would download every historical blob
|
|
152
|
+
(verified 2026-10-18: ``--numstat`` fetched all 97 missing blobs of a test clone).
|
|
153
|
+
"""
|
|
154
|
+
args = [
|
|
155
|
+
"-c",
|
|
156
|
+
"core.quotepath=off",
|
|
157
|
+
"log",
|
|
158
|
+
"--name-only",
|
|
159
|
+
"--no-renames",
|
|
160
|
+
f"--format={RECORD_SEP}%H",
|
|
161
|
+
]
|
|
162
|
+
if max_count is not None:
|
|
163
|
+
args.append(f"--max-count={max_count}")
|
|
164
|
+
output = run_git(args + _pathspec_args(pathspecs), cwd=root, timeout_s=120.0)
|
|
165
|
+
changes: list[tuple[str, list[str]]] = []
|
|
166
|
+
for record in output.split(RECORD_SEP):
|
|
167
|
+
lines = [line for line in record.splitlines() if line.strip()]
|
|
168
|
+
if lines:
|
|
169
|
+
changes.append((lines[0].strip(), lines[1:]))
|
|
170
|
+
return changes
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
async def read_changed_files(
|
|
174
|
+
root: Path, pathspecs: list[str] | None = None, max_count: int | None = None
|
|
175
|
+
) -> list[tuple[str, list[str]]]:
|
|
176
|
+
return await asyncio.to_thread(read_changed_files_sync, root, pathspecs, max_count)
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""Clone a public GitHub repository into a temporary workspace.
|
|
2
|
+
|
|
3
|
+
Security posture: only ``https://github.com/<owner>/<repo>`` URLs are accepted by default,
|
|
4
|
+
submodules are not fetched, symlinks are checked out as plain files, all credential prompts
|
|
5
|
+
are disabled, and the clone is size- and time-limited. Repository code is never executed.
|
|
6
|
+
|
|
7
|
+
Before cloning, the repository size reported by the GitHub API is checked against the limit,
|
|
8
|
+
so oversized repositories are refused without downloading them. If the API cannot be reached
|
|
9
|
+
(offline, rate-limited), the clone goes ahead with a warning and the post-clone check and
|
|
10
|
+
timeout still apply. ``GITHUB_TOKEN`` is only used for that API call (higher rate limits);
|
|
11
|
+
it is never given to ``git``.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import asyncio
|
|
17
|
+
import re
|
|
18
|
+
import subprocess
|
|
19
|
+
import tempfile
|
|
20
|
+
from collections.abc import Sequence
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
import httpx
|
|
24
|
+
|
|
25
|
+
from margin_core._fs import directory_size, force_rmtree
|
|
26
|
+
from margin_core.config import get_settings
|
|
27
|
+
from margin_core.errors import InvalidTargetError, LimitExceededError, LoaderError
|
|
28
|
+
from margin_core.loaders.base import Loader, LoaderLimits, Workspace
|
|
29
|
+
from margin_core.loaders.filters import FilterConfig
|
|
30
|
+
from margin_core.loaders.git import GitCommandError, git_available, run_git
|
|
31
|
+
from margin_core.loaders.local import LocalLoader
|
|
32
|
+
|
|
33
|
+
GITHUB_URL_RE = re.compile(
|
|
34
|
+
r"^https://github\.com/"
|
|
35
|
+
r"(?P<owner>[A-Za-z0-9](?:[A-Za-z0-9-]{0,38}))/"
|
|
36
|
+
r"(?P<repo>[A-Za-z0-9._-]{1,100}?)"
|
|
37
|
+
r"(?:\.git)?/?$"
|
|
38
|
+
)
|
|
39
|
+
BRANCH_RE = re.compile(r"^[A-Za-z0-9._/-]{1,200}$")
|
|
40
|
+
GITHUB_API = "https://api.github.com"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def parse_github_url(url: str) -> tuple[str, str]:
|
|
44
|
+
"""Return ``(owner, repo)`` for a valid GitHub repository URL."""
|
|
45
|
+
match = GITHUB_URL_RE.match(url.strip())
|
|
46
|
+
if not match or match.group("repo") in {".", ".."}:
|
|
47
|
+
raise InvalidTargetError(
|
|
48
|
+
f"Not a GitHub repository URL: {url!r} (expected https://github.com/<owner>/<repo>)"
|
|
49
|
+
)
|
|
50
|
+
return match.group("owner"), match.group("repo")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class GitHubLoader(Loader):
|
|
54
|
+
"""Loads ``https://github.com/<owner>/<repo>`` via a blobless clone.
|
|
55
|
+
|
|
56
|
+
``--filter=blob:none`` downloads full commit history cheaply; only the blobs needed
|
|
57
|
+
for the checked-out tree are fetched.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
def __init__(
|
|
61
|
+
self,
|
|
62
|
+
limits: LoaderLimits | None = None,
|
|
63
|
+
filters: FilterConfig | None = None,
|
|
64
|
+
*,
|
|
65
|
+
allow_non_github_urls: bool = False,
|
|
66
|
+
api_base: str = GITHUB_API,
|
|
67
|
+
github_token: str | None = None,
|
|
68
|
+
http_client: httpx.AsyncClient | None = None,
|
|
69
|
+
) -> None:
|
|
70
|
+
self.limits = limits or LoaderLimits()
|
|
71
|
+
self.filters = filters or FilterConfig()
|
|
72
|
+
self.allow_non_github_urls = allow_non_github_urls # tests only (file:// fixtures)
|
|
73
|
+
self.api_base = api_base.rstrip("/")
|
|
74
|
+
if github_token is None:
|
|
75
|
+
secret = get_settings().github_token # GITHUB_TOKEN env var or .env
|
|
76
|
+
github_token = secret.get_secret_value() if secret else None
|
|
77
|
+
self.github_token = github_token or None
|
|
78
|
+
self._http_client = http_client
|
|
79
|
+
|
|
80
|
+
@staticmethod
|
|
81
|
+
def can_handle(target: str) -> bool:
|
|
82
|
+
return target.strip().lower().startswith("https://github.com/")
|
|
83
|
+
|
|
84
|
+
def _validate(self, target: str, branch: str | None) -> str:
|
|
85
|
+
if branch is not None and (not BRANCH_RE.match(branch) or branch.startswith("-")):
|
|
86
|
+
raise InvalidTargetError(f"Invalid branch name: {branch!r}")
|
|
87
|
+
if self.allow_non_github_urls:
|
|
88
|
+
return target
|
|
89
|
+
owner, repo = parse_github_url(target)
|
|
90
|
+
return f"https://github.com/{owner}/{repo}.git"
|
|
91
|
+
|
|
92
|
+
async def check_remote_size(self, owner: str, repo: str) -> str | None:
|
|
93
|
+
"""Refuse repositories GitHub reports as too large.
|
|
94
|
+
|
|
95
|
+
Returns a warning when the check could not be done; raises
|
|
96
|
+
:class:`LimitExceededError` when the repository is over the limit and
|
|
97
|
+
:class:`InvalidTargetError` when it does not exist (or is private).
|
|
98
|
+
"""
|
|
99
|
+
url = f"{self.api_base}/repos/{owner}/{repo}"
|
|
100
|
+
headers = {"Accept": "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28"}
|
|
101
|
+
if self.github_token:
|
|
102
|
+
headers["Authorization"] = f"Bearer {self.github_token}"
|
|
103
|
+
try:
|
|
104
|
+
if self._http_client is not None:
|
|
105
|
+
response = await self._http_client.get(url, headers=headers, timeout=10.0)
|
|
106
|
+
else:
|
|
107
|
+
async with httpx.AsyncClient(timeout=10.0) as client:
|
|
108
|
+
response = await client.get(url, headers=headers)
|
|
109
|
+
except httpx.HTTPError as exc:
|
|
110
|
+
return f"Could not check the repository size before cloning ({type(exc).__name__})"
|
|
111
|
+
if response.status_code == 404:
|
|
112
|
+
raise InvalidTargetError(
|
|
113
|
+
f"GitHub repository {owner}/{repo} was not found. It may be private; "
|
|
114
|
+
"private repositories are not supported."
|
|
115
|
+
)
|
|
116
|
+
if response.status_code != 200:
|
|
117
|
+
return (
|
|
118
|
+
"Could not check the repository size before cloning "
|
|
119
|
+
f"(GitHub API returned HTTP {response.status_code})"
|
|
120
|
+
)
|
|
121
|
+
try:
|
|
122
|
+
size_kb = response.json().get("size")
|
|
123
|
+
except ValueError:
|
|
124
|
+
return "Could not check the repository size before cloning (invalid API response)"
|
|
125
|
+
if isinstance(size_kb, int) and size_kb * 1024 > self.limits.max_repo_size_bytes:
|
|
126
|
+
raise LimitExceededError(
|
|
127
|
+
f"Repository is about {size_kb * 1024} bytes according to GitHub, above the "
|
|
128
|
+
f"{self.limits.max_repo_size_bytes} byte limit"
|
|
129
|
+
)
|
|
130
|
+
return None
|
|
131
|
+
|
|
132
|
+
def _clone(self, url: str, dest: Path, branch: str | None) -> None:
|
|
133
|
+
args = [
|
|
134
|
+
"-c",
|
|
135
|
+
"core.symlinks=false",
|
|
136
|
+
"-c",
|
|
137
|
+
"credential.helper=",
|
|
138
|
+
"clone",
|
|
139
|
+
"--quiet",
|
|
140
|
+
"--filter=blob:none",
|
|
141
|
+
"--single-branch",
|
|
142
|
+
"--no-recurse-submodules",
|
|
143
|
+
]
|
|
144
|
+
if branch:
|
|
145
|
+
args += ["--branch", branch]
|
|
146
|
+
args += ["--", url, str(dest)]
|
|
147
|
+
try:
|
|
148
|
+
run_git(args, timeout_s=self.limits.clone_timeout_s)
|
|
149
|
+
except subprocess.TimeoutExpired as exc:
|
|
150
|
+
raise LimitExceededError(
|
|
151
|
+
f"Clone timed out after {self.limits.clone_timeout_s:.0f}s"
|
|
152
|
+
) from exc
|
|
153
|
+
except GitCommandError as exc:
|
|
154
|
+
raise LoaderError(f"Could not clone {url}: {exc}") from exc
|
|
155
|
+
|
|
156
|
+
async def load(
|
|
157
|
+
self,
|
|
158
|
+
target: str,
|
|
159
|
+
*,
|
|
160
|
+
paths: Sequence[str] | None = None,
|
|
161
|
+
branch: str | None = None,
|
|
162
|
+
) -> Workspace:
|
|
163
|
+
if not git_available():
|
|
164
|
+
raise LoaderError("git is not installed or not on PATH")
|
|
165
|
+
url = self._validate(target, branch)
|
|
166
|
+
size_warning: str | None = None
|
|
167
|
+
if not self.allow_non_github_urls:
|
|
168
|
+
size_warning = await self.check_remote_size(*parse_github_url(target))
|
|
169
|
+
tmp = Path(tempfile.mkdtemp(prefix="margin-"))
|
|
170
|
+
try:
|
|
171
|
+
dest = tmp / "repo"
|
|
172
|
+
await asyncio.to_thread(self._clone, url, dest, branch)
|
|
173
|
+
size = await asyncio.to_thread(directory_size, dest)
|
|
174
|
+
if size > self.limits.max_repo_size_bytes:
|
|
175
|
+
raise LimitExceededError(
|
|
176
|
+
f"Repository is {size} bytes, above the {self.limits.max_repo_size_bytes} limit"
|
|
177
|
+
)
|
|
178
|
+
local = LocalLoader(self.limits, self.filters)
|
|
179
|
+
ws = await asyncio.to_thread(local.load_sync, str(dest), paths=paths, source=target)
|
|
180
|
+
except BaseException:
|
|
181
|
+
force_rmtree(tmp)
|
|
182
|
+
raise
|
|
183
|
+
ws.add_cleanup(lambda: force_rmtree(tmp))
|
|
184
|
+
if size_warning:
|
|
185
|
+
ws.warnings.append(size_warning)
|
|
186
|
+
return ws
|