acceptbox 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.
acceptbox/command.py ADDED
@@ -0,0 +1,92 @@
1
+ """Прогон одного коммита в режиме command: argv после --, без shell (L19)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import signal
7
+ import subprocess
8
+ import time
9
+ from pathlib import Path
10
+
11
+ from .git import strip_local_env_vars
12
+ from .verdict import RunOutcome
13
+
14
+ LOG_NAME = "command.log"
15
+ # Сколько ждать закрытия pipe после SIGKILL группы (потомок мог уйти в свою сессию).
16
+ _DRAIN_TIMEOUT_SEC = 5.0
17
+
18
+
19
+ def _kill_group(pgid: int) -> None:
20
+ try:
21
+ os.killpg(pgid, signal.SIGKILL)
22
+ except (ProcessLookupError, PermissionError):
23
+ pass
24
+
25
+
26
+ def run_process_group(argv: list[str], *, cwd: str, env: dict[str, str],
27
+ timeout: float) -> subprocess.CompletedProcess:
28
+ """Аналог ``subprocess.run(capture_output=True, timeout=...)`` в отдельной сессии.
29
+
30
+ По таймауту и после завершения убивается вся группа процессов: потомки
31
+ (раннеры тестов, серверы) не переживают прогон и не мешают следующему.
32
+ Таймаут — ``subprocess.TimeoutExpired`` с выводом, собранным до SIGKILL.
33
+ """
34
+ process = subprocess.Popen(argv, cwd=cwd, env=env, stdout=subprocess.PIPE,
35
+ stderr=subprocess.PIPE, start_new_session=True)
36
+ try:
37
+ try:
38
+ stdout, stderr = process.communicate(timeout=timeout)
39
+ except subprocess.TimeoutExpired:
40
+ _kill_group(process.pid)
41
+ try:
42
+ stdout, stderr = process.communicate(timeout=_DRAIN_TIMEOUT_SEC)
43
+ except subprocess.TimeoutExpired:
44
+ stdout = stderr = b""
45
+ raise subprocess.TimeoutExpired(argv, timeout, output=stdout,
46
+ stderr=stderr) from None
47
+ finally:
48
+ _kill_group(process.pid)
49
+ if process.poll() is None:
50
+ process.kill()
51
+ process.wait()
52
+ for stream in (process.stdout, process.stderr):
53
+ stream.close()
54
+ return subprocess.CompletedProcess(argv, process.returncode, stdout, stderr)
55
+
56
+
57
+ def run_commit(worktree: Path, commit_sha: str, run_dir: Path, env: dict[str, str],
58
+ timeout: float, *, cmd_argv: list[str]) -> RunOutcome:
59
+ """Выполнить команду в detached-worktree коммита и классифицировать исход.
60
+
61
+ Код 0 → green; код 1 → red; любой другой код, завершение по сигналу,
62
+ ошибка запуска (OSError) или таймаут → error.
63
+ """
64
+ run_dir = Path(run_dir)
65
+ run_dir.mkdir(parents=True, exist_ok=True)
66
+ clean_env = strip_local_env_vars(env)
67
+ exit_code: int | None = None
68
+ stdout = stderr = b""
69
+ started = time.monotonic()
70
+ try:
71
+ completed = run_process_group(list(cmd_argv), cwd=str(worktree),
72
+ env=clean_env, timeout=timeout)
73
+ except subprocess.TimeoutExpired as expired:
74
+ stdout, stderr = expired.stdout or b"", expired.stderr or b""
75
+ status, reason = "error", f"команда превысила таймаут {timeout:g} с"
76
+ except OSError as os_error:
77
+ status, reason = "error", f"не удалось запустить команду: {os_error}"
78
+ else:
79
+ stdout, stderr = completed.stdout, completed.stderr
80
+ exit_code = completed.returncode
81
+ if completed.returncode == 0:
82
+ status, reason = "green", "команда завершилась с кодом 0"
83
+ elif completed.returncode == 1:
84
+ status, reason = "red", "команда завершилась с кодом 1"
85
+ elif completed.returncode < 0:
86
+ status, reason = "error", f"команда завершена сигналом {-completed.returncode}"
87
+ else:
88
+ status, reason = "error", f"команда завершилась с кодом {completed.returncode}"
89
+ duration_ms = int((time.monotonic() - started) * 1000)
90
+ (run_dir / LOG_NAME).write_bytes(stdout + stderr)
91
+ return RunOutcome(status=status, exit_code=exit_code, reason=reason,
92
+ duration_ms=duration_ms, log_path=LOG_NAME, artifacts=None)
acceptbox/config.py ADDED
@@ -0,0 +1,244 @@
1
+ """Проектный конфиг AcceptBox (.acceptbox.toml), чтение строго из коммита base (L23).
2
+
3
+ Схема формата 1 (секционная, fail-closed):
4
+ - Верхний уровень: ``format = 1`` (обязателен), ``mode``, ``timeout``,
5
+ ``protect``, ``env``, таблицы ``[command]`` и ``[witnessbox]``.
6
+ - ``[command]``: ``tests`` (непустой список pathspec), ``argv`` (непустой список строк).
7
+ - ``[witnessbox]``: ``ebt_repo`` (строка), ``ebt_ref`` (строка).
8
+
9
+ Неизвестные ключи, пер-задачные поля (``inv``, ``ebt_sha``, ``approved_tree``,
10
+ ``base``, ``repro``, ``head``, ``repo``, ``out``), симлинки, невалидные типы и
11
+ относительный локальный путь ``ebt_repo`` отклоняются с ConfigError.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import hashlib
17
+ import os
18
+ import re
19
+ import tomllib
20
+ from dataclasses import dataclass
21
+ from pathlib import Path
22
+
23
+ from .git import run_git
24
+ from .inputs import (InputError, parse_env_entry, validate_pathspec,
25
+ validate_ref, validate_repo_source, validate_timeout)
26
+
27
+ CONFIG_FILENAME = ".acceptbox.toml"
28
+ CONFIG_FORMAT = 1
29
+
30
+ _TOP_KEYS = frozenset({"format", "mode", "timeout", "protect", "env",
31
+ "command", "witnessbox"})
32
+ _COMMAND_KEYS = frozenset({"tests", "argv"})
33
+ _WITNESSBOX_KEYS = frozenset({"ebt_repo", "ebt_ref"})
34
+ _VALID_MODES = frozenset({"command", "witnessbox"})
35
+ # URL (scheme://) или scp-подобный адрес host:path — не локальный путь.
36
+ _REMOTE_SOURCE_RE = re.compile(r"[A-Za-z][A-Za-z0-9+.-]*://|[^/]+:")
37
+
38
+
39
+ class ConfigError(ValueError):
40
+ """Некорректный .acceptbox.toml в базовом коммите → config-invalid (код 2).
41
+
42
+ ``commit`` и ``sha256`` заполняет load_config_from_commit для отчёта.
43
+ """
44
+
45
+ commit: str | None = None
46
+ sha256: str | None = None
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class ProjectConfig:
51
+ """Разобранный и провалидированный .acceptbox.toml из коммита base."""
52
+
53
+ source_commit: str
54
+ sha256: str
55
+ mode: str | None = None
56
+ timeout: float | None = None
57
+ protect: tuple[str, ...] = ()
58
+ env: tuple[tuple[str, str | None], ...] = ()
59
+ command_tests: tuple[str, ...] = ()
60
+ command_argv: tuple[str, ...] = ()
61
+ witnessbox_ebt_repo: str | None = None
62
+ witnessbox_ebt_ref: str | None = None
63
+
64
+
65
+ def _reject_unknown_keys(table: dict, allowed: frozenset[str], section: str) -> None:
66
+ unknown = sorted(set(table) - allowed)
67
+ if unknown:
68
+ raise ConfigError(
69
+ f"{CONFIG_FILENAME} ({section}): неизвестные ключи: {', '.join(unknown)}")
70
+
71
+
72
+ def _require_str_list(value: object, *, label: str, allow_empty: bool = True) -> list[str]:
73
+ if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
74
+ raise ConfigError(f"{label} должен быть списком строк")
75
+ if not allow_empty and not value:
76
+ raise ConfigError(f"{label} не может быть пустым списком")
77
+ return value
78
+
79
+
80
+ def parse_config(raw_bytes: bytes, *, commit_sha: str) -> ProjectConfig:
81
+ """Разобрать и провалидировать содержимое .acceptbox.toml (fail-closed)."""
82
+ sha256 = hashlib.sha256(raw_bytes).hexdigest()
83
+ try:
84
+ text = raw_bytes.decode("utf-8")
85
+ except UnicodeDecodeError as error:
86
+ raise ConfigError(f"{CONFIG_FILENAME}: некорректная кодировка UTF-8: {error}") from error
87
+ try:
88
+ data = tomllib.loads(text)
89
+ except tomllib.TOMLDecodeError as error:
90
+ raise ConfigError(f"{CONFIG_FILENAME}: ошибка разбора TOML: {error}") from error
91
+ if not isinstance(data, dict):
92
+ raise ConfigError(f"{CONFIG_FILENAME}: корень должен быть таблицей TOML")
93
+
94
+ _reject_unknown_keys(data, _TOP_KEYS, "верхний уровень")
95
+
96
+ fmt = data.get("format")
97
+ if type(fmt) is not int or fmt != CONFIG_FORMAT:
98
+ raise ConfigError(
99
+ f"{CONFIG_FILENAME}: обязателен ключ format = {CONFIG_FORMAT} (получено: {fmt!r})")
100
+
101
+ mode: str | None = None
102
+ if "mode" in data:
103
+ raw_mode = data["mode"]
104
+ if not isinstance(raw_mode, str) or raw_mode not in _VALID_MODES:
105
+ raise ConfigError(
106
+ f"{CONFIG_FILENAME}: mode должен быть 'command' или 'witnessbox'")
107
+ mode = raw_mode
108
+
109
+ timeout: float | None = None
110
+ if "timeout" in data:
111
+ raw_timeout = data["timeout"]
112
+ if type(raw_timeout) not in (int, float):
113
+ raise ConfigError(f"{CONFIG_FILENAME}: timeout должен быть числом секунд")
114
+ try:
115
+ timeout = validate_timeout(raw_timeout, flag=f"{CONFIG_FILENAME}: timeout")
116
+ except InputError as error:
117
+ raise ConfigError(str(error)) from error
118
+
119
+ protect: list[str] = []
120
+ if "protect" in data:
121
+ raw_protect = _require_str_list(data["protect"], label=f"{CONFIG_FILENAME}: protect")
122
+ try:
123
+ protect = [validate_pathspec(item, flag=f"{CONFIG_FILENAME}: protect")
124
+ for item in raw_protect]
125
+ except InputError as error:
126
+ raise ConfigError(str(error)) from error
127
+
128
+ env_entries: list[tuple[str, str | None]] = []
129
+ if "env" in data:
130
+ raw_env = _require_str_list(data["env"], label=f"{CONFIG_FILENAME}: env")
131
+ try:
132
+ env_entries = [parse_env_entry(item, flag=f"{CONFIG_FILENAME}: env")
133
+ for item in raw_env]
134
+ except InputError as error:
135
+ raise ConfigError(str(error)) from error
136
+
137
+ command_tests: list[str] = []
138
+ command_argv: list[str] = []
139
+ if "command" in data:
140
+ cmd_table = data["command"]
141
+ if not isinstance(cmd_table, dict):
142
+ raise ConfigError(f"{CONFIG_FILENAME}: секция [command] должна быть таблицей")
143
+ _reject_unknown_keys(cmd_table, _COMMAND_KEYS, "[command]")
144
+ if "tests" in cmd_table:
145
+ raw_tests = _require_str_list(
146
+ cmd_table["tests"], label=f"{CONFIG_FILENAME}: [command].tests",
147
+ allow_empty=False,
148
+ )
149
+ try:
150
+ command_tests = [
151
+ validate_pathspec(item, flag=f"{CONFIG_FILENAME}: [command].tests")
152
+ for item in raw_tests
153
+ ]
154
+ except InputError as error:
155
+ raise ConfigError(str(error)) from error
156
+ if "argv" in cmd_table:
157
+ raw_argv = _require_str_list(
158
+ cmd_table["argv"], label=f"{CONFIG_FILENAME}: [command].argv",
159
+ allow_empty=False,
160
+ )
161
+ if not raw_argv[0].strip():
162
+ raise ConfigError(
163
+ f"{CONFIG_FILENAME}: [command].argv[0] не может быть пустым")
164
+ if any("\x00" in item for item in raw_argv):
165
+ raise ConfigError(
166
+ f"{CONFIG_FILENAME}: [command].argv содержит недопустимый NUL-байт")
167
+ command_argv = list(raw_argv)
168
+
169
+ wb_ebt_repo: str | None = None
170
+ wb_ebt_ref: str | None = None
171
+ if "witnessbox" in data:
172
+ wb_table = data["witnessbox"]
173
+ if not isinstance(wb_table, dict):
174
+ raise ConfigError(f"{CONFIG_FILENAME}: секция [witnessbox] должна быть таблицей")
175
+ _reject_unknown_keys(wb_table, _WITNESSBOX_KEYS, "[witnessbox]")
176
+ if "ebt_repo" in wb_table:
177
+ raw_ebt_repo = wb_table["ebt_repo"]
178
+ if not isinstance(raw_ebt_repo, str):
179
+ raise ConfigError(
180
+ f"{CONFIG_FILENAME}: [witnessbox].ebt_repo должен быть строкой")
181
+ try:
182
+ wb_ebt_repo = validate_repo_source(
183
+ raw_ebt_repo, flag=f"{CONFIG_FILENAME}: [witnessbox].ebt_repo")
184
+ except InputError as error:
185
+ raise ConfigError(str(error)) from error
186
+ # Относительный путь зависел бы от каталога запуска acceptbox, а не от --repo.
187
+ if not _REMOTE_SOURCE_RE.match(wb_ebt_repo) and not os.path.isabs(wb_ebt_repo):
188
+ raise ConfigError(
189
+ f"{CONFIG_FILENAME}: [witnessbox].ebt_repo должен быть URL или "
190
+ f"абсолютным путём (получено: {raw_ebt_repo!r})")
191
+ if "ebt_ref" in wb_table:
192
+ raw_ebt_ref = wb_table["ebt_ref"]
193
+ if not isinstance(raw_ebt_ref, str):
194
+ raise ConfigError(
195
+ f"{CONFIG_FILENAME}: [witnessbox].ebt_ref должен быть строкой")
196
+ try:
197
+ wb_ebt_ref = validate_ref(
198
+ raw_ebt_ref, flag=f"{CONFIG_FILENAME}: [witnessbox].ebt_ref")
199
+ except InputError as error:
200
+ raise ConfigError(str(error)) from error
201
+
202
+ return ProjectConfig(
203
+ source_commit=commit_sha,
204
+ sha256=sha256,
205
+ mode=mode,
206
+ timeout=timeout,
207
+ protect=tuple(protect),
208
+ env=tuple(env_entries),
209
+ command_tests=tuple(command_tests),
210
+ command_argv=tuple(command_argv),
211
+ witnessbox_ebt_repo=wb_ebt_repo,
212
+ witnessbox_ebt_ref=wb_ebt_ref,
213
+ )
214
+
215
+
216
+ def load_config_from_commit(repo: Path, env: dict[str, str],
217
+ commit_sha: str) -> ProjectConfig | None:
218
+ """Прочитать .acceptbox.toml строго из объектов Git коммита ``commit_sha``.
219
+
220
+ Возвращает None, если файл отсутствует в коммите. Симлинки, каталоги,
221
+ сабмодули, ошибки разбора TOML и нарушения схемы → ConfigError.
222
+ """
223
+ listing = run_git(repo, env, "ls-tree", "-z", commit_sha, "--", CONFIG_FILENAME)
224
+ entries = [entry for entry in listing.split(b"\0") if entry]
225
+ if not entries:
226
+ return None
227
+ metadata, _path = entries[0].split(b"\t", 1)
228
+ mode, kind, object_id = metadata.split()
229
+ if kind != b"blob" or mode not in (b"100644", b"100755"):
230
+ mode_text = mode.decode("ascii", "replace")
231
+ kind_text = kind.decode("ascii", "replace")
232
+ error = ConfigError(
233
+ f"{CONFIG_FILENAME} в коммите {commit_sha} должен быть обычным файлом "
234
+ f"(получено: mode={mode_text}, kind={kind_text})"
235
+ )
236
+ error.commit = commit_sha
237
+ raise error
238
+ raw = run_git(repo, env, "cat-file", "blob", object_id.decode("ascii"))
239
+ try:
240
+ return parse_config(raw, commit_sha=commit_sha)
241
+ except ConfigError as error:
242
+ error.commit = commit_sha
243
+ error.sha256 = hashlib.sha256(raw).hexdigest()
244
+ raise
acceptbox/git.py ADDED
@@ -0,0 +1,252 @@
1
+ """Изоляция Git: временный клон, fetch по полному SHA, detached-worktree, ancestry, diff.
2
+
3
+ Правила изоляции (L17): каждый вызов git получает ``--no-replace-objects``;
4
+ клонирование, fetch и создание worktree дополнительно получают
5
+ ``-c core.hooksPath=/dev/null``; каждый diff получает
6
+ ``-c diff.renames=false --no-renames -z``; из окружения везде удаляются
7
+ переменные из ``git rev-parse --local-env-vars``.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import functools
13
+ import os
14
+ import re
15
+ import shutil
16
+ import subprocess
17
+ from pathlib import Path
18
+
19
+ GIT_TIMEOUT_SEC = 600.0
20
+
21
+ # Резерв на случай, когда `git rev-parse --local-env-vars` недоступен (git не
22
+ # установлен): список стабилен для всех актуальных версий git.
23
+ _FALLBACK_LOCAL_ENV_VARS = (
24
+ "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_CONFIG", "GIT_CONFIG_PARAMETERS",
25
+ "GIT_CONFIG_COUNT", "GIT_OBJECT_DIRECTORY", "GIT_DIR", "GIT_WORK_TREE",
26
+ "GIT_IMPLICIT_WORK_TREE", "GIT_GRAFT_FILE", "GIT_INDEX_FILE",
27
+ "GIT_NO_REPLACE_OBJECTS", "GIT_REPLACE_REF_BASE", "GIT_PREFIX",
28
+ "GIT_SHALLOW_FILE", "GIT_COMMON_DIR",
29
+ )
30
+
31
+
32
+ class GitError(Exception):
33
+ """Сбой git-инфраструктуры: git недоступен, репозиторий недостижим, таймаут."""
34
+
35
+
36
+ @functools.lru_cache(maxsize=1)
37
+ def local_env_var_names() -> tuple[str, ...]:
38
+ """Имена переменных git-изоляции; работает и вне git-репозитория."""
39
+ try:
40
+ result = subprocess.run(
41
+ ["git", "rev-parse", "--local-env-vars"],
42
+ capture_output=True, timeout=30, check=False,
43
+ )
44
+ except (OSError, subprocess.SubprocessError):
45
+ return _FALLBACK_LOCAL_ENV_VARS
46
+ if result.returncode == 0:
47
+ names = tuple(result.stdout.decode("ascii", "replace").split())
48
+ if names:
49
+ return names
50
+ return _FALLBACK_LOCAL_ENV_VARS
51
+
52
+
53
+ def strip_local_env_vars(env: dict[str, str]) -> dict[str, str]:
54
+ """Копия окружения без переменных git-изоляции (защита от GIT_DIR и т.п.)."""
55
+ clean = dict(env)
56
+ for name in local_env_var_names():
57
+ clean.pop(name, None)
58
+ return clean
59
+
60
+
61
+ def base_env() -> dict[str, str]:
62
+ """Окружение git-операций acceptbox: os.environ без local-env-vars."""
63
+ env = strip_local_env_vars(dict(os.environ))
64
+ # Репозиторий может требовать авторизацию: без подсказок git падает, а не висит.
65
+ env.setdefault("GIT_TERMINAL_PROMPT", "0")
66
+ return env
67
+
68
+
69
+ def run_git(repo: Path | None, env: dict[str, str], *args: str,
70
+ timeout: float = GIT_TIMEOUT_SEC) -> bytes:
71
+ """Вызов git с ``--no-replace-objects``; любая ошибка или таймаут — GitError."""
72
+ argv = ["git", "--no-replace-objects"]
73
+ if repo is not None:
74
+ argv += ["-C", str(repo)]
75
+ argv += list(args)
76
+ try:
77
+ result = subprocess.run(argv, env=env, capture_output=True, timeout=timeout, check=False)
78
+ except subprocess.TimeoutExpired as error:
79
+ raise GitError(f"git {args[0]}: превышен таймаут {timeout:g} с") from error
80
+ except OSError as error:
81
+ raise GitError(f"не удалось запустить git: {error}") from error
82
+ if result.returncode != 0:
83
+ detail = result.stderr.decode("utf-8", "replace").strip().splitlines()
84
+ message = f"git {' '.join(args[:2])}: код {result.returncode}"
85
+ raise GitError(f"{message}: {detail[-1]}" if detail else message)
86
+ return result.stdout
87
+
88
+
89
+ def probe_git() -> dict:
90
+ """Диагностика git для ``acceptbox --installation``."""
91
+ executable = shutil.which("git")
92
+ if executable is None:
93
+ return {"path": None, "version": None, "status": "missing"}
94
+ try:
95
+ result = subprocess.run([executable, "--version"], capture_output=True, timeout=15, check=False)
96
+ except (OSError, subprocess.SubprocessError):
97
+ return {"path": executable, "version": None, "status": "error"}
98
+ if result.returncode != 0:
99
+ return {"path": executable, "version": None, "status": "error"}
100
+ match = re.search(r"git version\s+(\S+)", result.stdout.decode("utf-8", "replace"))
101
+ if match is None:
102
+ return {"path": executable, "version": None, "status": "error"}
103
+ return {"path": executable, "version": match.group(1), "status": "ok"}
104
+
105
+
106
+ def clone_no_checkout(source: str, destination: Path, env: dict[str, str]) -> None:
107
+ """Временный клон без checkout; локальные пути клонируются с ``--no-local``.
108
+
109
+ ``--no-local`` исключает hardlink'и на объекты репозитория пользователя и
110
+ гарантирует полноту передачи через transport (все объявленные ссылки).
111
+ """
112
+ args = ["-c", "core.hooksPath=/dev/null", "clone", "--quiet", "--no-checkout"]
113
+ if os.path.exists(source):
114
+ args.append("--no-local")
115
+ args += ["--", source, str(destination)]
116
+ run_git(None, env, *args)
117
+
118
+
119
+ def commit_present(repo: Path, env: dict[str, str], sha: str) -> bool:
120
+ """True, только если sha разрешается в коммит; любое несоответствие — False."""
121
+ try:
122
+ kind = run_git(repo, env, "cat-file", "-t", f"{sha}^{{commit}}")
123
+ except GitError:
124
+ return False
125
+ return kind.strip() == b"commit"
126
+
127
+
128
+ def _fetch(repo: Path, env: dict[str, str], source: str, *refspecs: str) -> None:
129
+ run_git(repo, env, "-c", "core.hooksPath=/dev/null", "fetch", "--no-tags", source, *refspecs)
130
+
131
+
132
+ def fetch_all_refs(repo: Path, env: dict[str, str], source: str) -> None:
133
+ """Вытянуть все ссылки источника в отдельное пространство имён.
134
+
135
+ Гарантирует доступность коммитов с не-дефолтных веток и PR-ссылок как в
136
+ локальных репозиториях (без ``uploadpack.allowAnySHA1InWant``), так и на серверах.
137
+ """
138
+ _fetch(repo, env, source, "+refs/*:refs/acceptbox-fetch/*")
139
+
140
+
141
+ def ensure_commit(repo: Path, env: dict[str, str], source: str, sha: str) -> bool:
142
+ """Гарантировать наличие коммита в клоне: cat-file → fetch по SHA → fetch всех ссылок.
143
+
144
+ True — коммит доступен; False — источник достижим, но коммита нет;
145
+ GitError — недостижимый источник или сбой сети (gate-error).
146
+ """
147
+ if commit_present(repo, env, sha):
148
+ return True
149
+ try:
150
+ _fetch(repo, env, source, sha)
151
+ except GitError:
152
+ fetch_all_refs(repo, env, source)
153
+ return commit_present(repo, env, sha)
154
+
155
+
156
+ def resolve_ref(repo: Path, env: dict[str, str], *candidates: str) -> str | None:
157
+ """Полный SHA коммита первого подходящего кандидата, иначе None."""
158
+ for candidate in candidates:
159
+ try:
160
+ output = run_git(repo, env, "rev-parse", "--verify", f"{candidate}^{{commit}}")
161
+ except GitError:
162
+ continue
163
+ return output.strip().decode("ascii")
164
+ return None
165
+
166
+
167
+ def resolve_repo_head(source: str, env: dict[str, str]) -> str:
168
+ """Разрешить HEAD репозитория ``source`` в полный SHA коммита (L22).
169
+
170
+ Для локального каталога использует ``rev-parse --verify HEAD^{commit}``,
171
+ для URL — ``ls-remote -- <source> HEAD``. Любой сбой — GitError.
172
+ """
173
+ local_path = Path(source).expanduser()
174
+ if local_path.is_dir():
175
+ output = run_git(local_path, env, "rev-parse", "--verify", "HEAD^{commit}")
176
+ sha = output.strip().decode("ascii", "replace")
177
+ if not sha:
178
+ raise GitError(f"не удалось разрешить HEAD в {source}")
179
+ return sha
180
+ output = run_git(None, env, "-c", "core.hooksPath=/dev/null",
181
+ "ls-remote", "--", source, "HEAD")
182
+ for line in output.decode("ascii", "replace").splitlines():
183
+ parts = line.split("\t", 1)
184
+ if len(parts) == 2 and parts[1] == "HEAD" and parts[0]:
185
+ return parts[0]
186
+ raise GitError(f"ссылка HEAD не найдена в репозитории {source}")
187
+
188
+
189
+ def fetch_ref(repo: Path, env: dict[str, str], source: str, ref: str) -> str | None:
190
+ """Вытянуть ссылку EBT и вернуть SHA коммита, на который она указывает.
191
+
192
+ Короткое имя разрешается явно: сначала ``refs/heads/<ref>``, затем
193
+ ``refs/tags/<ref>`` (DWIM git fetch предпочёл бы одноимённый тег ветке).
194
+ При неудаче — все ссылки источника в том же порядке.
195
+ None — ссылка не найдена (источник достижим); GitError — сбой источника/сети.
196
+ """
197
+ if ref.startswith("refs/"):
198
+ candidates = (ref,)
199
+ else:
200
+ candidates = (f"refs/heads/{ref}", f"refs/tags/{ref}")
201
+ for candidate in candidates:
202
+ try:
203
+ _fetch(repo, env, source, f"+{candidate}:refs/acceptbox-ebt/ref")
204
+ except GitError:
205
+ continue
206
+ return resolve_ref(repo, env, "refs/acceptbox-ebt/ref")
207
+ fetch_all_refs(repo, env, source)
208
+ mapped = tuple(f"refs/acceptbox-fetch/{name[len('refs/'):]}" for name in candidates)
209
+ return resolve_ref(repo, env, *mapped)
210
+
211
+
212
+ def add_worktree(repo: Path, env: dict[str, str], sha: str, path: Path) -> None:
213
+ """Detached-worktree для прогона: checkout пользователя не переключается, хуки отключены."""
214
+ run_git(repo, env, "-c", "core.hooksPath=/dev/null", "worktree", "add", "--quiet",
215
+ "--detach", str(path), sha)
216
+
217
+
218
+ def rev_parse_tree(repo: Path, env: dict[str, str], sha: str) -> str:
219
+ """SHA дерева коммита (L13): связывает проверенное дерево с доставленным коммитом."""
220
+ return run_git(repo, env, "rev-parse", "--verify", f"{sha}^{{tree}}").strip().decode("ascii")
221
+
222
+
223
+ def is_ancestor(repo: Path, env: dict[str, str], ancestor: str, descendant: str) -> bool:
224
+ """``git merge-base --is-ancestor``: True/False; любой иной исход — GitError."""
225
+ argv = ["git", "--no-replace-objects", "-C", str(repo),
226
+ "merge-base", "--is-ancestor", ancestor, descendant]
227
+ try:
228
+ result = subprocess.run(argv, env=env, capture_output=True,
229
+ timeout=GIT_TIMEOUT_SEC, check=False)
230
+ except subprocess.TimeoutExpired as error:
231
+ raise GitError("git merge-base: превышен таймаут") from error
232
+ except OSError as error:
233
+ raise GitError(f"не удалось запустить git: {error}") from error
234
+ if result.returncode == 0:
235
+ return True
236
+ if result.returncode == 1:
237
+ return False
238
+ detail = result.stderr.decode("utf-8", "replace").strip().splitlines()
239
+ message = f"git merge-base --is-ancestor: код {result.returncode}"
240
+ raise GitError(f"{message}: {detail[-1]}" if detail else message)
241
+
242
+
243
+ def changed_paths(repo: Path, env: dict[str, str], older: str, newer: str,
244
+ pathspecs: list[str] | None = None) -> list[str]:
245
+ """Пути, изменённые между деревьями двух коммитов; ``--no-renames``:
246
+ переименование распадается в удаление старого пути и добавление нового.
247
+ """
248
+ args = ["-c", "diff.renames=false", "diff", "--name-only", "--no-renames", "-z", older, newer]
249
+ if pathspecs:
250
+ args += ["--", *pathspecs]
251
+ output = run_git(repo, env, *args)
252
+ return [path for path in output.decode("utf-8", "replace").split("\0") if path]