pr-proof 0.0.0-stage → 0.1.0-beta.0
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.
- package/LICENSE +21 -0
- package/Procfile +2 -0
- package/README.md +300 -2
- package/app/__init__.py +1 -0
- package/app/api/__init__.py +1 -0
- package/app/api/cli.py +35 -0
- package/app/api/github.py +168 -0
- package/app/api/history.py +123 -0
- package/app/api/main.py +95 -0
- package/app/api/queue.py +45 -0
- package/app/api/responses.py +28 -0
- package/app/api/signature.py +19 -0
- package/app/api/sync.py +189 -0
- package/app/api/sync_rules_pure.py +71 -0
- package/app/api/webhook.py +166 -0
- package/app/setup/__init__.py +4 -0
- package/app/setup/cli.py +90 -0
- package/app/setup/configure.py +720 -0
- package/app/setup/files.py +93 -0
- package/app/setup/github_setup.py +149 -0
- package/app/setup/install_hints.json +32 -0
- package/app/setup/setup_pure.py +312 -0
- package/app/setup/start.py +113 -0
- package/app/shared/__init__.py +1 -0
- package/app/shared/comment_pure.py +29 -0
- package/app/shared/config.py +106 -0
- package/app/shared/db_pure.py +339 -0
- package/app/shared/embed_models_pure.py +55 -0
- package/app/shared/feedback_pure.py +84 -0
- package/app/shared/github_auth.py +74 -0
- package/app/shared/job_pure.py +43 -0
- package/app/shared/notify.py +97 -0
- package/app/shared/ops_alert_pure.py +38 -0
- package/app/shared/state_keys_pure.py +24 -0
- package/app/shared/version.py +27 -0
- package/app/worker/__init__.py +1 -0
- package/app/worker/access_pure.py +180 -0
- package/app/worker/ai/__init__.py +1 -0
- package/app/worker/ai/claude_cli.py +684 -0
- package/app/worker/ai/mcp_relay.py +42 -0
- package/app/worker/ai/path_hook.py +103 -0
- package/app/worker/ai/tool_server.py +139 -0
- package/app/worker/ai/workdir.py +333 -0
- package/app/worker/base_config.py +173 -0
- package/app/worker/budget.py +100 -0
- package/app/worker/cache_key_pure.py +34 -0
- package/app/worker/call_budget_pure.py +132 -0
- package/app/worker/checker_authoring_pure.py +599 -0
- package/app/worker/checker_pure.py +196 -0
- package/app/worker/cli.py +97 -0
- package/app/worker/command.py +191 -0
- package/app/worker/command_pure.py +38 -0
- package/app/worker/coverage.py +123 -0
- package/app/worker/coverage_pure.py +202 -0
- package/app/worker/deps.py +22 -0
- package/app/worker/diff_pure.py +419 -0
- package/app/worker/doc_rules_pure.py +201 -0
- package/app/worker/doc_rules_report.py +979 -0
- package/app/worker/eval_run_pure.py +241 -0
- package/app/worker/evaluation.py +151 -0
- package/app/worker/feedback.py +448 -0
- package/app/worker/feedback_pure.py +131 -0
- package/app/worker/feedback_report_pure.py +90 -0
- package/app/worker/feedback_triage.py +85 -0
- package/app/worker/feedback_triage_pure.py +363 -0
- package/app/worker/fix/__init__.py +1 -0
- package/app/worker/fix/decide.py +197 -0
- package/app/worker/fix/feedback_fix_pure.py +125 -0
- package/app/worker/fix/fix_decision_pure.py +386 -0
- package/app/worker/fix/fix_pure.py +70 -0
- package/app/worker/fix/mechanical_fix.py +214 -0
- package/app/worker/fix/model_fix.py +575 -0
- package/app/worker/fix/model_fix_pure.py +593 -0
- package/app/worker/fix/proposal.py +584 -0
- package/app/worker/fix/proposal_pure.py +103 -0
- package/app/worker/fix/scope.py +40 -0
- package/app/worker/fix/scope_pure.py +222 -0
- package/app/worker/generated_tests_pure.py +442 -0
- package/app/worker/github.py +471 -0
- package/app/worker/graph.py +963 -0
- package/app/worker/guard.py +91 -0
- package/app/worker/lang/__init__.py +0 -0
- package/app/worker/lang/install_pure.py +25 -0
- package/app/worker/lang/python.py +862 -0
- package/app/worker/loop.py +200 -0
- package/app/worker/main.py +76 -0
- package/app/worker/markdown_pure.py +29 -0
- package/app/worker/mcp_pure.py +150 -0
- package/app/worker/memory.py +503 -0
- package/app/worker/merged_fix_pure.py +236 -0
- package/app/worker/pr_check_report_pure.py +201 -0
- package/app/worker/pr_description_report_pure.py +112 -0
- package/app/worker/preflight.py +125 -0
- package/app/worker/rag_pure.py +285 -0
- package/app/worker/rag_switch_pure.py +203 -0
- package/app/worker/records.py +207 -0
- package/app/worker/records_pure.py +239 -0
- package/app/worker/repo.py +588 -0
- package/app/worker/repo_config_pure.py +269 -0
- package/app/worker/report.py +300 -0
- package/app/worker/retry.py +65 -0
- package/app/worker/rule_pure.py +223 -0
- package/app/worker/rule_reading_pure.py +503 -0
- package/app/worker/rules/__init__.py +1 -0
- package/app/worker/rules/checkers.py +615 -0
- package/app/worker/rules/detect.py +154 -0
- package/app/worker/rules/doc_rules.py +301 -0
- package/app/worker/rules/doc_sections_pure.py +168 -0
- package/app/worker/rules/judge.py +410 -0
- package/app/worker/rules/judge_pure.py +627 -0
- package/app/worker/rules/pr_check.py +404 -0
- package/app/worker/rules/pr_check_pure.py +922 -0
- package/app/worker/rules/pr_description.py +218 -0
- package/app/worker/rules/pr_description_pure.py +743 -0
- package/app/worker/rules/rules.py +314 -0
- package/app/worker/rules/run_check.py +95 -0
- package/app/worker/rules/run_check_pure.py +219 -0
- package/app/worker/rules/tool_choice_pure.py +135 -0
- package/app/worker/sandbox/__init__.py +1 -0
- package/app/worker/sandbox/checker_runner.py +412 -0
- package/app/worker/sandbox/container.py +130 -0
- package/app/worker/sandbox/docker_cli.py +170 -0
- package/app/worker/sandbox/safe_read.py +32 -0
- package/app/worker/sandbox/toolcache.py +425 -0
- package/app/worker/state.py +602 -0
- package/app/worker/test_lines.py +77 -0
- package/app/worker/test_run_pure.py +133 -0
- package/app/worker/text_edit_pure.py +66 -0
- package/app/worker/tools_pure.py +152 -0
- package/app/worker/update.py +305 -0
- package/app/worker/violation_pure.py +33 -0
- package/bin/pr-proof.js +173 -0
- package/docker/sandbox/Dockerfile +12 -0
- package/docker/sandbox/coveragerc +19 -0
- package/docker-compose.yml +5 -0
- package/package.json +31 -4
- package/pyproject.toml +60 -0
|
@@ -0,0 +1,588 @@
|
|
|
1
|
+
"""PR 코드 준비: bare clone 캐시, worktree, changes.diff (docs/DESIGN.md F4).
|
|
2
|
+
|
|
3
|
+
git은 호스트에서만 실행한다. worktree의 `.git`은 bare 저장소를 가리키므로 컨테이너 안에서는
|
|
4
|
+
동작하지 않는다. 인증은 gh를 명령 단위의 자격 증명 도우미로 빌려 쓰고(gh 로그인 또는 토큰 파일,
|
|
5
|
+
`app/shared/github_auth.py`), 전역 git 설정은 바꾸지 않는다. 토큰은 GitHub과 주고받는 명령에만
|
|
6
|
+
넘긴다.
|
|
7
|
+
|
|
8
|
+
worktree 안의 `.git` 파일은 믿지 않는다. 샌드박스의 PR 코드(그리고 3단계의 AI)가 worktree에 쓸 수
|
|
9
|
+
있어서, `.git`을 자기가 만든 저장소로 바꾸면 그 저장소 설정(`core.fsmonitor`, 필터 등)으로 호스트
|
|
10
|
+
git이 임의 명령을 실행한다. 그래서 worktree를 만든 직후, 아무것도 실행하기 전에 저장소 경로를
|
|
11
|
+
worktree 밖 파일에 적고(`record_git_dir`), worktree에서 도는 git은 모두 그 경로를 `--git-dir`로
|
|
12
|
+
넘긴다(`_tree_git`). 기록이 없으면 실행하지 않는다.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import os
|
|
16
|
+
import re
|
|
17
|
+
import shutil
|
|
18
|
+
import subprocess
|
|
19
|
+
import uuid
|
|
20
|
+
from collections.abc import Iterator, Sequence
|
|
21
|
+
from contextlib import contextmanager
|
|
22
|
+
from dataclasses import dataclass
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Final
|
|
25
|
+
|
|
26
|
+
from app.shared import config, github_auth
|
|
27
|
+
from app.worker.rule_reading_pure import TreeEntry
|
|
28
|
+
from app.worker.rules.pr_check_pure import RawCommit
|
|
29
|
+
from app.worker.sandbox.container import OUT_DIR
|
|
30
|
+
|
|
31
|
+
CHANGES_DIFF: Final = f"{OUT_DIR}/changes.diff"
|
|
32
|
+
GIT_TIMEOUT: Final = 300
|
|
33
|
+
_ENV_PASSTHROUGH: Final = ("PATH", "HOME", "GH_CONFIG_DIR")
|
|
34
|
+
# 이 명령에서만 gh를 자격 증명 도우미로 쓴다. 앞의 빈 값은 사용자의 다른 도우미를 끈다
|
|
35
|
+
_GH_CREDENTIAL: Final = (
|
|
36
|
+
"-c",
|
|
37
|
+
"credential.helper=",
|
|
38
|
+
"-c",
|
|
39
|
+
"credential.helper=!gh auth git-credential",
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class GitError(RuntimeError):
|
|
44
|
+
"""git 명령 실패. 네트워크·인증 문제일 수 있어 환경 오류로 다룬다."""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True)
|
|
48
|
+
class Checkout:
|
|
49
|
+
path: Path
|
|
50
|
+
head_sha: str
|
|
51
|
+
base_sha: str # base 브랜치의 지금 커밋. 설정·규칙은 여기서 읽는다
|
|
52
|
+
# PR 브랜치가 갈라진 커밋. PR이 바꾼 줄은 여기와 비교한다. base가 앞서 나가면 base_sha와 다르다
|
|
53
|
+
merge_base: str
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _git(*args: str, cwd: Path | None = None, network: bool = False) -> str:
|
|
57
|
+
"""network는 GitHub과 주고받는 명령(clone, fetch, push)이다. 토큰 방식이면 그 명령에만 토큰을
|
|
58
|
+
넘긴다. 자격 증명 도우미(`gh auth git-credential`)가 git의 환경을 물려받아 읽는다."""
|
|
59
|
+
try:
|
|
60
|
+
env = (
|
|
61
|
+
github_auth.gh_env(_ENV_PASSTHROUGH)
|
|
62
|
+
if network
|
|
63
|
+
else {k: os.environ[k] for k in _ENV_PASSTHROUGH if k in os.environ}
|
|
64
|
+
)
|
|
65
|
+
except config.ConfigError as e:
|
|
66
|
+
raise GitError(f"GitHub 토큰을 읽지 못함: {e}") from e
|
|
67
|
+
env["GIT_TERMINAL_PROMPT"] = "0"
|
|
68
|
+
try:
|
|
69
|
+
proc = subprocess.run(
|
|
70
|
+
["git", *_GH_CREDENTIAL, *args],
|
|
71
|
+
cwd=cwd,
|
|
72
|
+
capture_output=True,
|
|
73
|
+
text=True,
|
|
74
|
+
env=env,
|
|
75
|
+
timeout=GIT_TIMEOUT,
|
|
76
|
+
check=False,
|
|
77
|
+
)
|
|
78
|
+
except (OSError, subprocess.TimeoutExpired) as e:
|
|
79
|
+
raise GitError(f"git {args[0]} 실행 실패: {e}") from e
|
|
80
|
+
if proc.returncode != 0:
|
|
81
|
+
detail = github_auth.redact(proc.stderr.strip(), env)[-1000:]
|
|
82
|
+
raise GitError(f"git {args[0]} 실패 ({proc.returncode}): {detail}")
|
|
83
|
+
return proc.stdout
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _git_dir_record(worktree: Path) -> Path:
|
|
87
|
+
"""worktree의 저장소 경로를 적는 파일. worktree 밖(옆)에 두어 샌드박스가 바꾸지 못한다."""
|
|
88
|
+
return worktree.parent / f".{worktree.name}.gitdir"
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def record_git_dir(worktree: Path) -> None:
|
|
92
|
+
"""worktree를 막 만든 뒤(그 안에서 아무것도 실행하기 전)에만 부른다."""
|
|
93
|
+
git_dir = _git("rev-parse", "--absolute-git-dir", cwd=worktree).strip()
|
|
94
|
+
_git_dir_record(worktree).write_text(git_dir)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _forget_git_dir(worktree: Path) -> None:
|
|
98
|
+
_git_dir_record(worktree).unlink(missing_ok=True)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _tree_git(worktree: Path, *args: str, network: bool = False) -> str:
|
|
102
|
+
"""worktree에서 git을 실행한다. worktree 안의 `.git` 대신 만들 때 적어 둔 저장소를 쓴다."""
|
|
103
|
+
try:
|
|
104
|
+
git_dir = _git_dir_record(worktree).read_text().strip()
|
|
105
|
+
except OSError as e:
|
|
106
|
+
raise GitError(f"worktree의 저장소 기록이 없음: {worktree}") from e
|
|
107
|
+
return _git(
|
|
108
|
+
f"--git-dir={git_dir}", f"--work-tree={worktree}", *args, cwd=worktree, network=network
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def worktree_file(worktree: Path, rel: str) -> Path | None:
|
|
113
|
+
"""호스트에서 읽고 써도 되는 worktree 안의 일반 파일이면 그 경로, 아니면 None.
|
|
114
|
+
|
|
115
|
+
PR(과 샌드박스에서 돈 PR 코드)이 심볼릭 링크를 넣을 수 있다. 호스트에서 링크를 따라가면
|
|
116
|
+
worktree 밖 파일(`~/.ssh` 등)을 읽거나 고친다. 링크 자체는 건너뛰고, 상위 폴더가 링크라
|
|
117
|
+
실제 위치가 worktree 밖이면 거부한다.
|
|
118
|
+
"""
|
|
119
|
+
path = worktree / rel
|
|
120
|
+
if path.is_symlink():
|
|
121
|
+
return None
|
|
122
|
+
try:
|
|
123
|
+
real = path.resolve(strict=True)
|
|
124
|
+
except (OSError, RuntimeError): # 없음, 링크 순환
|
|
125
|
+
return None
|
|
126
|
+
if not real.is_relative_to(worktree.resolve()) or not real.is_file():
|
|
127
|
+
return None
|
|
128
|
+
return path
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def remote_url(repo: str) -> str:
|
|
132
|
+
return f"https://github.com/{repo}.git"
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def bare_path(data_dir: Path, repo: str) -> Path:
|
|
136
|
+
return data_dir / "repos" / f"{repo.replace('/', '__')}.git"
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def ensure_bare(data_dir: Path, repo: str, url: str | None = None) -> Path:
|
|
140
|
+
"""리포마다 처음 한 번만 bare clone한다."""
|
|
141
|
+
path = bare_path(data_dir, repo)
|
|
142
|
+
if not (path / "HEAD").is_file():
|
|
143
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
144
|
+
_git("clone", "--bare", "--quiet", url or remote_url(repo), str(path), network=True)
|
|
145
|
+
return path
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def fetch_pr(bare: Path, pr_number: int, base_sha: str) -> None:
|
|
149
|
+
"""PR head와 base 커밋을 가져온다. base는 SHA로 가져온다 (GitHub은 도달 가능한 SHA를 허용)."""
|
|
150
|
+
_git(
|
|
151
|
+
"fetch", "--quiet", "--no-tags", "origin",
|
|
152
|
+
f"+refs/pull/{pr_number}/head:refs/pipeline/pr/{pr_number}",
|
|
153
|
+
base_sha,
|
|
154
|
+
cwd=bare,
|
|
155
|
+
network=True,
|
|
156
|
+
) # fmt: skip
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def fetch_commit(bare: Path, sha: str) -> None:
|
|
160
|
+
"""커밋 하나를 bare 캐시로 가져온다. 이미 있으면 받지 않는다. PR head는 가져오지 않는다."""
|
|
161
|
+
if not re.fullmatch(r"[0-9a-f]{40}", sha):
|
|
162
|
+
raise GitError(f"커밋 해시가 아님: {sha!r}")
|
|
163
|
+
try:
|
|
164
|
+
_git("cat-file", "-e", f"{sha}^{{commit}}", cwd=bare)
|
|
165
|
+
return
|
|
166
|
+
except GitError:
|
|
167
|
+
pass
|
|
168
|
+
_git("fetch", "--quiet", "--no-tags", "origin", sha, cwd=bare, network=True)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def bare_entries(bare: Path, sha: str, paths: Sequence[str]) -> dict[str, TreeEntry]:
|
|
172
|
+
"""worktree 없이 bare 캐시의 커밋에서 paths의 (모드, blob 해시, 크기)를 읽는다."""
|
|
173
|
+
if not paths:
|
|
174
|
+
return {}
|
|
175
|
+
listed = _git("ls-tree", "-l", "-z", sha, "--", *paths, cwd=bare)
|
|
176
|
+
wanted = set(paths)
|
|
177
|
+
return {path: e for path, e in _tree_entries(listed).items() if path in wanted}
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def bare_blob(bare: Path, blob_sha: str) -> str:
|
|
181
|
+
"""bare 캐시의 blob 하나를 글로 읽는다. 글로 읽을 수 없는 바이트면 UnicodeDecodeError."""
|
|
182
|
+
return _git("cat-file", "blob", blob_sha, cwd=bare)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def commit_parents(bare: Path, sha: str) -> tuple[str, ...]:
|
|
186
|
+
"""bare 캐시의 커밋 하나의 부모 SHA들 (머지 커밋이면 둘)."""
|
|
187
|
+
return tuple(_git("rev-list", "--parents", "-n", "1", sha, cwd=bare).split()[1:])
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def tree_of(bare: Path, sha: str) -> str:
|
|
191
|
+
"""커밋의 트리 해시. 트리가 같으면 모든 파일의 경로·모드·내용이 같다."""
|
|
192
|
+
return _git("rev-parse", "--verify", f"{sha}^{{tree}}", cwd=bare).strip()
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def patched_tree(bare: Path, sha: str, patch: bytes, scratch: Path) -> str:
|
|
196
|
+
"""sha의 트리에 patch를 적용한 트리의 해시. worktree 없이 임시 인덱스(scratch 아래)로만 한다.
|
|
197
|
+
|
|
198
|
+
수정안을 머지한 커밋의 내용이 "검증한 커밋 + 저장한 패치"와 같은지 보는 데 쓴다. 패치가 맞지
|
|
199
|
+
않으면 GitError. 패치는 파이프라인이 검증하고 저장한 것이고 bare 캐시의 설정은 파이프라인이 만든
|
|
200
|
+
것이라 훅과 필터를 끄기만 한다.
|
|
201
|
+
"""
|
|
202
|
+
scratch.mkdir(parents=True, exist_ok=True)
|
|
203
|
+
index = scratch / f"index-{uuid.uuid4().hex[:8]}"
|
|
204
|
+
env = {k: os.environ[k] for k in _ENV_PASSTHROUGH if k in os.environ}
|
|
205
|
+
env |= {"GIT_TERMINAL_PROMPT": "0", "GIT_INDEX_FILE": str(index)}
|
|
206
|
+
safe = ("-c", "core.hooksPath=/dev/null", "-c", "core.autocrlf=false")
|
|
207
|
+
|
|
208
|
+
def run(*args: str, stdin: bytes | None = None) -> str:
|
|
209
|
+
try:
|
|
210
|
+
proc = subprocess.run(
|
|
211
|
+
["git", *safe, *args], cwd=bare, input=stdin, capture_output=True, env=env,
|
|
212
|
+
timeout=GIT_TIMEOUT, check=False,
|
|
213
|
+
) # fmt: skip
|
|
214
|
+
except (OSError, subprocess.TimeoutExpired) as e:
|
|
215
|
+
raise GitError(f"git {args[0]} 실행 실패: {e}") from e
|
|
216
|
+
if proc.returncode != 0:
|
|
217
|
+
detail = proc.stderr.decode(errors="replace").strip()[-500:]
|
|
218
|
+
raise GitError(f"git {args[0]} 실패 ({proc.returncode}): {detail}")
|
|
219
|
+
return proc.stdout.decode().strip()
|
|
220
|
+
|
|
221
|
+
try:
|
|
222
|
+
run("read-tree", sha)
|
|
223
|
+
run("apply", "--cached", "--binary", "--whitespace=nowarn", "-", stdin=patch)
|
|
224
|
+
return run("write-tree")
|
|
225
|
+
finally:
|
|
226
|
+
index.unlink(missing_ok=True)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def bare_lines(
|
|
230
|
+
bare: Path, sha: str, path: str, max_bytes: int = 5 * 1024 * 1024
|
|
231
|
+
) -> list[str] | None:
|
|
232
|
+
"""bare 캐시의 커밋에서 일반 파일 하나의 줄들. 없거나, 링크·폴더이거나, max_bytes보다 크거나,
|
|
233
|
+
글로 읽을 수 없으면 None. 줄은 worktree에서 읽을 때(`records._reader`)와 같이 "\\n"으로
|
|
234
|
+
나눈다."""
|
|
235
|
+
entry = bare_entries(bare, sha, [path]).get(path)
|
|
236
|
+
if entry is None or entry.mode not in ("100644", "100755"):
|
|
237
|
+
return None
|
|
238
|
+
if entry.size is None or entry.size > max_bytes:
|
|
239
|
+
return None
|
|
240
|
+
try:
|
|
241
|
+
return bare_blob(bare, entry.sha).split("\n")
|
|
242
|
+
except (GitError, UnicodeDecodeError):
|
|
243
|
+
return None
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def bare_pr_facts(
|
|
247
|
+
bare: Path, base_sha: str, head_sha: str, *, limit: int
|
|
248
|
+
) -> tuple[list[str], list[str]]:
|
|
249
|
+
"""worktree 없이 PR의 커밋 제목(새 커밋부터 limit개)과 바뀐 파일 경로 (4.11 PR 사실).
|
|
250
|
+
|
|
251
|
+
`fetch_pr`로 두 커밋을 받아 둔 bare 캐시에서 읽는다. 제목은 작성자의 글이라 자료로만 쓴다.
|
|
252
|
+
"""
|
|
253
|
+
fork = _git("merge-base", base_sha, head_sha, cwd=bare).strip()
|
|
254
|
+
subjects = _git(
|
|
255
|
+
"log", f"--max-count={limit}", "--format=%s", f"{fork}..{head_sha}", cwd=bare
|
|
256
|
+
).splitlines()
|
|
257
|
+
files = _git("diff", "--name-only", "-z", fork, head_sha, cwd=bare).split("\0")
|
|
258
|
+
return subjects, [f for f in files if f]
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def list_base_entries(worktree: Path, base_sha: str, paths: Sequence[str]) -> dict[str, TreeEntry]:
|
|
262
|
+
"""base 커밋에서 paths 중 있는 것의 (모드, blob 해시, 크기). 경로가 정확히 같은 것만 남긴다.
|
|
263
|
+
|
|
264
|
+
내용은 읽지 않는다. 모드로 심볼릭 링크(120000)와 폴더를 가려낸 뒤 `read_blob`으로 읽는다.
|
|
265
|
+
"""
|
|
266
|
+
if not paths: # 경로 없이 부르면 루트의 모든 파일이 나온다
|
|
267
|
+
return {}
|
|
268
|
+
listed = _tree_git(worktree, "ls-tree", "-l", "-z", base_sha, "--", *paths)
|
|
269
|
+
wanted = set(paths)
|
|
270
|
+
return {path: e for path, e in _tree_entries(listed).items() if path in wanted}
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def base_root_entries(worktree: Path, base_sha: str) -> dict[str, TreeEntry]:
|
|
274
|
+
"""base 커밋 루트의 모든 항목 (모드, blob 해시, 크기). 설정 파일을 고를 때 쓴다."""
|
|
275
|
+
return _tree_entries(_tree_git(worktree, "ls-tree", "-l", "-z", base_sha))
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _tree_entries(listed: str) -> dict[str, TreeEntry]:
|
|
279
|
+
entries = {}
|
|
280
|
+
for record in filter(None, listed.split("\0")):
|
|
281
|
+
meta, _, path = record.partition("\t")
|
|
282
|
+
mode, _kind, sha, size = meta.split()
|
|
283
|
+
entries[path] = TreeEntry(path, mode, sha, int(size) if size != "-" else None)
|
|
284
|
+
return entries
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def list_base_files(worktree: Path, base_sha: str) -> tuple[str, ...]:
|
|
288
|
+
"""base 커밋의 모든 파일 경로 (저장소 기준). 내용은 읽지 않는다."""
|
|
289
|
+
listed = _tree_git(worktree, "ls-tree", "-r", "--name-only", "-z", base_sha)
|
|
290
|
+
return tuple(filter(None, listed.split("\0")))
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def read_blob(worktree: Path, sha: str) -> str:
|
|
294
|
+
"""blob 하나를 글로 읽는다. 글로 읽을 수 없는 바이트면 UnicodeDecodeError."""
|
|
295
|
+
return _tree_git(worktree, "cat-file", "blob", sha)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def merge_base(worktree: Path, base_sha: str, head_sha: str) -> str:
|
|
299
|
+
return _tree_git(worktree, "merge-base", base_sha, head_sha).strip()
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def changed_paths(worktree: Path, merge_base_sha: str, head_sha: str) -> tuple[str, ...]:
|
|
303
|
+
"""PR이 바꾼 파일의 경로 (4.5 PR 사실). 추가·수정·삭제이고, 이름을 바꾸면 옛 경로와 새 경로
|
|
304
|
+
둘 다다."""
|
|
305
|
+
listed = _tree_git(
|
|
306
|
+
worktree, "-c", "core.quotePath=false", "diff", "--name-only", "-z", "--no-renames",
|
|
307
|
+
merge_base_sha, head_sha,
|
|
308
|
+
) # fmt: skip
|
|
309
|
+
return tuple(filter(None, listed.split("\0")))
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
# 커밋 객체에서 메시지 앞의 머리(작성자, 서명 등)에 둘 여유. 그 뒤는 읽지 않고 버린다
|
|
313
|
+
_COMMIT_HEADER_ROOM: Final = 64 * 1024
|
|
314
|
+
_FULL_SHA_LINE: Final = re.compile(r"[0-9a-f]{40}( [0-9a-f]{40})*")
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def pr_commits(
|
|
318
|
+
worktree: Path, merge_base_sha: str, head_sha: str, *, limit: int, message_bytes: int
|
|
319
|
+
) -> tuple[list[RawCommit], bool]:
|
|
320
|
+
"""PR의 커밋(merge-base..head, 새 커밋부터) limit개까지와, 더 있었는지 (4.5 PR 사실).
|
|
321
|
+
|
|
322
|
+
해시와 부모는 `rev-list --parents`로, 메시지는 `cat-file --batch`로 객체 크기를 보며 읽는다.
|
|
323
|
+
메시지 안의 글(작성자의 글)이 구분자를 흉내 내어 다른 커밋처럼 보일 수 없다. 메시지는
|
|
324
|
+
message_bytes를 조금 넘게까지만 읽고, 객체가 더 크면 cut으로 표시한다.
|
|
325
|
+
"""
|
|
326
|
+
listed = _tree_git(
|
|
327
|
+
worktree, "rev-list", "--parents", f"--max-count={limit + 1}",
|
|
328
|
+
f"{merge_base_sha}..{head_sha}",
|
|
329
|
+
) # fmt: skip
|
|
330
|
+
rows = [line.split() for line in listed.splitlines() if line.strip()]
|
|
331
|
+
if not all(_FULL_SHA_LINE.fullmatch(" ".join(r)) for r in rows):
|
|
332
|
+
raise GitError("rev-list 출력을 읽지 못함")
|
|
333
|
+
more = len(rows) > limit
|
|
334
|
+
rows = rows[:limit]
|
|
335
|
+
messages = _commit_messages(worktree, [r[0] for r in rows], message_bytes + _COMMIT_HEADER_ROOM)
|
|
336
|
+
commits = [RawCommit(r[0], tuple(r[1:]), *messages[r[0]]) for r in rows]
|
|
337
|
+
return commits, more
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def _commit_messages(worktree: Path, shas: Sequence[str], keep: int) -> dict[str, tuple[str, bool]]:
|
|
341
|
+
"""커밋마다 (메시지, 잘렸는지). 객체의 앞 keep바이트만 메모리에 둔다."""
|
|
342
|
+
if not shas:
|
|
343
|
+
return {}
|
|
344
|
+
try:
|
|
345
|
+
git_dir = _git_dir_record(worktree).read_text().strip()
|
|
346
|
+
except OSError as e:
|
|
347
|
+
raise GitError(f"worktree의 저장소 기록이 없음: {worktree}") from e
|
|
348
|
+
env = {k: os.environ[k] for k in _ENV_PASSTHROUGH if k in os.environ}
|
|
349
|
+
command = ["git", f"--git-dir={git_dir}", "cat-file", "--batch"]
|
|
350
|
+
try:
|
|
351
|
+
proc = subprocess.Popen(
|
|
352
|
+
command, cwd=worktree, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
|
353
|
+
stderr=subprocess.DEVNULL, env=env,
|
|
354
|
+
) # fmt: skip
|
|
355
|
+
except OSError as e:
|
|
356
|
+
raise GitError(f"git cat-file 실행 실패: {e}") from e
|
|
357
|
+
out: dict[str, tuple[str, bool]] = {}
|
|
358
|
+
try:
|
|
359
|
+
assert proc.stdin is not None and proc.stdout is not None
|
|
360
|
+
proc.stdin.write(("\n".join(shas) + "\n").encode())
|
|
361
|
+
proc.stdin.close()
|
|
362
|
+
for sha in shas:
|
|
363
|
+
header = proc.stdout.readline().split()
|
|
364
|
+
if len(header) != 3 or header[0].decode() != sha or header[1] != b"commit":
|
|
365
|
+
raise GitError(f"커밋 객체를 읽지 못함: {sha}")
|
|
366
|
+
size = int(header[2])
|
|
367
|
+
head = proc.stdout.read(min(size, keep))
|
|
368
|
+
left = size - len(head)
|
|
369
|
+
while left > 0:
|
|
370
|
+
chunk = proc.stdout.read(min(left, 1 << 16))
|
|
371
|
+
if not chunk:
|
|
372
|
+
raise GitError(f"커밋 객체가 중간에 끝남: {sha}")
|
|
373
|
+
left -= len(chunk)
|
|
374
|
+
proc.stdout.read(1) # 객체 뒤의 줄바꿈
|
|
375
|
+
_, _, message = head.partition(b"\n\n")
|
|
376
|
+
out[sha] = (message.decode("utf-8", errors="replace"), size > keep)
|
|
377
|
+
finally:
|
|
378
|
+
if proc.poll() is None:
|
|
379
|
+
proc.kill()
|
|
380
|
+
proc.wait(timeout=GIT_TIMEOUT)
|
|
381
|
+
return out
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
# 사용자 전역 git 설정이 diff 형식(접두사, 경로 표기, 외부 diff 도구)을 바꾸지 않게 한다.
|
|
385
|
+
# diff_pure가 `+++ b/<경로>` 형식을 읽는다
|
|
386
|
+
_DIFF: Final = (
|
|
387
|
+
"-c", "diff.noprefix=false", "-c", "diff.mnemonicPrefix=false", "-c", "diff.relative=false",
|
|
388
|
+
"-c", "core.quotePath=false", "diff", "--no-color", "--no-ext-diff",
|
|
389
|
+
) # fmt: skip
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def working_diff(worktree: Path, merge_base_sha: str) -> str:
|
|
393
|
+
"""갈라진 커밋과 worktree의 지금 파일 사이의 diff. 수정을 적용한 뒤 바뀐 줄을 다시 셀 때 쓴다.
|
|
394
|
+
|
|
395
|
+
base 브랜치의 지금 커밋과 비교하면, PR이 갈라진 뒤 base에서 바뀐 줄까지 PR의 변경으로 잡힌다.
|
|
396
|
+
"""
|
|
397
|
+
return _tree_git(worktree, *_DIFF, merge_base_sha)
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
# 범위 검사용 status. 사용자·리포 git 설정이 결과를 바꾸거나 외부 프로그램을 부르지 않게 한다.
|
|
401
|
+
# 전역 무시 파일은 끈다 (리포의 .gitignore만 본다). fsmonitor·untracked 캐시는 결과가 오래될 수
|
|
402
|
+
# 있고 fsmonitor는 외부 명령을 부를 수 있다
|
|
403
|
+
_STATUS: Final = (
|
|
404
|
+
"-c", "core.quotePath=false", "-c", "core.excludesFile=/dev/null", "-c", "core.fsmonitor=false",
|
|
405
|
+
"-c", "core.untrackedCache=false", "-c", "status.renames=true",
|
|
406
|
+
"status", "--porcelain=v1", "-z", "--untracked-files=all", "--ignore-submodules=none",
|
|
407
|
+
) # fmt: skip
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def status(worktree: Path) -> str:
|
|
411
|
+
"""새 파일·삭제·이름 변경까지 보이는 변경 목록 (docs/DESIGN.md F7 범위 검사)."""
|
|
412
|
+
return _tree_git(worktree, *_STATUS)
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def ignored_status(worktree: Path) -> str:
|
|
416
|
+
"""무시된 파일을 하나씩 보여주는 status (`!!`). F7 무시된 파일 스냅샷용.
|
|
417
|
+
|
|
418
|
+
`--ignored=matching`은 무시된 폴더를 `!! build/` 한 줄로만 보여줘, 이미 있던 무시된 폴더 안에
|
|
419
|
+
새로 만든 `build/conftest.py`를 놓친다. `traditional`은 `--untracked-files=all`과 함께 쓰면
|
|
420
|
+
무시된 폴더 안의 파일을 하나씩 낸다.
|
|
421
|
+
"""
|
|
422
|
+
return _tree_git(worktree, *_STATUS, "--ignored=traditional")
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def outside_symlinks(worktree: Path) -> list[str]:
|
|
426
|
+
"""worktree 밖을 가리키는 추적 중인 심볼릭 링크 (리포 기준 경로).
|
|
427
|
+
|
|
428
|
+
PR이 `docs -> ~/.ssh` 같은 링크를 넣으면 그 폴더를 거친 쓰기는 worktree 밖으로 가고
|
|
429
|
+
`git status`에도 나오지 않는다. AI를 실행하기 전에 확인한다 (DESIGN.md AI 권한).
|
|
430
|
+
"""
|
|
431
|
+
root = worktree.resolve()
|
|
432
|
+
out = []
|
|
433
|
+
for entry in _tree_git(worktree, "ls-files", "-s", "-z").split("\0"):
|
|
434
|
+
meta, _, path = entry.partition("\t")
|
|
435
|
+
if not meta.startswith("120000 "):
|
|
436
|
+
continue
|
|
437
|
+
target = (worktree / path).resolve()
|
|
438
|
+
if not target.is_relative_to(root):
|
|
439
|
+
out.append(path)
|
|
440
|
+
return out
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def list_files(worktree: Path) -> list[str]:
|
|
444
|
+
"""추적 중인 파일과 무시되지 않은 새 파일 (리포 기준 경로). 모델 폴더로 복사할 후보다."""
|
|
445
|
+
out = _tree_git(
|
|
446
|
+
worktree, "-c", "core.quotePath=false", "-c", "core.excludesFile=/dev/null",
|
|
447
|
+
"-c", "core.fsmonitor=false", "ls-files", "-z", "--cached", "--others",
|
|
448
|
+
"--exclude-standard",
|
|
449
|
+
) # fmt: skip
|
|
450
|
+
return sorted({path for path in out.split("\0") if path})
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def apply_patch(worktree: Path, patch: bytes, *, reverse: bool = False) -> None:
|
|
454
|
+
"""모델 폴더에서 뽑은 diff를 worktree의 파일에 적용한다. 인덱스는 건드리지 않는다.
|
|
455
|
+
|
|
456
|
+
git은 심볼릭 링크 너머의 경로에 쓰지 않고("beyond a symbolic link"), 하나라도 맞지 않으면
|
|
457
|
+
아무것도 적용하지 않는다. reverse면 diff를 거꾸로 적용해 되돌린다.
|
|
458
|
+
"""
|
|
459
|
+
try:
|
|
460
|
+
git_dir = _git_dir_record(worktree).read_text().strip()
|
|
461
|
+
except OSError as e:
|
|
462
|
+
raise GitError(f"worktree의 저장소 기록이 없음: {worktree}") from e
|
|
463
|
+
env = {k: os.environ[k] for k in _ENV_PASSTHROUGH if k in os.environ}
|
|
464
|
+
command = [
|
|
465
|
+
"git", "-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false",
|
|
466
|
+
"-c", "core.autocrlf=false", f"--git-dir={git_dir}", f"--work-tree={worktree}",
|
|
467
|
+
"apply", "--binary", "--whitespace=nowarn", *(["-R"] if reverse else []), "-",
|
|
468
|
+
] # fmt: skip
|
|
469
|
+
try:
|
|
470
|
+
proc = subprocess.run(
|
|
471
|
+
command, cwd=worktree, input=patch, capture_output=True, env=env,
|
|
472
|
+
timeout=GIT_TIMEOUT, check=False,
|
|
473
|
+
) # fmt: skip
|
|
474
|
+
except (OSError, subprocess.TimeoutExpired) as e:
|
|
475
|
+
raise GitError(f"git apply 실행 실패: {e}") from e
|
|
476
|
+
if proc.returncode != 0:
|
|
477
|
+
detail = proc.stderr.decode(errors="replace").strip()[-500:]
|
|
478
|
+
raise GitError(f"git apply 실패 ({proc.returncode}): {detail}")
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def commit_diff(worktree: Path, old: str, new: str, path: str) -> str:
|
|
482
|
+
"""두 커밋 사이의 파일 하나의 diff. 작성자가 자기 커밋으로 고친 기록(4.10)에 쓴다."""
|
|
483
|
+
return _tree_git(worktree, *_DIFF, old, new, "--", path)
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def commit_patch(worktree: Path, sha: str) -> str:
|
|
487
|
+
"""부모가 하나인 커밋 하나가 바꾼 내용 (`git diff sha^ sha`). PR 설명 확인이 파이프라인 수정안의
|
|
488
|
+
커밋이 넣은 변경을 모델에 따로 보이는 데 쓴다 (4.5 끝)."""
|
|
489
|
+
return _tree_git(worktree, *_DIFF, f"{sha}^", sha)
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def track_new(worktree: Path, paths: Sequence[str]) -> None:
|
|
493
|
+
"""새 파일을 diff에 보이게 한다(`git add -N`). 내용은 인덱스에 넣지 않는다. 수정 작성이 만든
|
|
494
|
+
테스트 파일을 수정안 패치와 재검사의 바뀐 줄에 넣는 데 쓴다."""
|
|
495
|
+
if paths:
|
|
496
|
+
_tree_git(worktree, "add", "--intent-to-add", "--", *paths)
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def untrack(worktree: Path, path: str) -> None:
|
|
500
|
+
"""`track_new`로 보이게 한 파일을 인덱스에서 뺀다. 파일을 지운 뒤 부른다."""
|
|
501
|
+
_tree_git(worktree, "rm", "--cached", "--quiet", "--ignore-unmatch", "--", path)
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def head_diff(worktree: Path) -> str:
|
|
505
|
+
"""체크아웃한 커밋과 worktree 사이의 diff. 수정안 자체다."""
|
|
506
|
+
return _tree_git(worktree, *_DIFF, "HEAD")
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
# 사용자 전역 git 설정의 서명·훅이 파이프라인 커밋에 끼어들지 않게 한다
|
|
510
|
+
_COMMIT_SAFETY: Final = ("-c", "commit.gpgsign=false", "-c", "core.hooksPath=/dev/null")
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
def commit_and_push(
|
|
514
|
+
worktree: Path,
|
|
515
|
+
paths: Sequence[str],
|
|
516
|
+
message: str,
|
|
517
|
+
branch: str,
|
|
518
|
+
author: tuple[str, str],
|
|
519
|
+
) -> str:
|
|
520
|
+
"""허용된 경로만 스테이징해 커밋하고 파이프라인 브랜치로 강제 푸시한다. 커밋 SHA를 돌려준다.
|
|
521
|
+
|
|
522
|
+
`git add -A`를 쓰지 않는다. `.pipeline-out/`이나 테스트 산출물이 섞이지 않게 한다 (F10).
|
|
523
|
+
"""
|
|
524
|
+
name, email = author
|
|
525
|
+
_tree_git(worktree, "add", "--", *paths)
|
|
526
|
+
_tree_git(worktree, *_COMMIT_SAFETY, "-c", f"user.name={name}", "-c", f"user.email={email}",
|
|
527
|
+
"commit", "-q", "-m", message) # fmt: skip
|
|
528
|
+
sha = _tree_git(worktree, "rev-parse", "HEAD").strip()
|
|
529
|
+
_tree_git(worktree, *_COMMIT_SAFETY, "push", "--quiet", "--force", "origin",
|
|
530
|
+
f"HEAD:refs/heads/{branch}", network=True) # fmt: skip
|
|
531
|
+
return sha
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
def write_changes_diff(worktree: Path, merge_base_sha: str, head_sha: str) -> Path:
|
|
535
|
+
"""PR이 바꾼 내용 (`git diff base...head`와 같다). 수정 후 다시 셀 때와 같은 기준을 쓴다."""
|
|
536
|
+
out = worktree / CHANGES_DIFF
|
|
537
|
+
out.parent.mkdir(exist_ok=True)
|
|
538
|
+
out.write_text(_tree_git(worktree, *_DIFF, merge_base_sha, head_sha))
|
|
539
|
+
return out
|
|
540
|
+
|
|
541
|
+
|
|
542
|
+
@contextmanager
|
|
543
|
+
def side_worktree(worktree: Path, sha: str) -> Iterator[Path]:
|
|
544
|
+
"""같은 저장소에서 다른 커밋의 worktree를 잠깐 만든다 (base 브랜치의 포맷 확인 등)."""
|
|
545
|
+
path = worktree.parent / f"{worktree.name}-{sha[:8]}"
|
|
546
|
+
_tree_git(worktree, "worktree", "add", "--quiet", "--detach", str(path), sha)
|
|
547
|
+
try:
|
|
548
|
+
record_git_dir(path)
|
|
549
|
+
yield path
|
|
550
|
+
finally:
|
|
551
|
+
_forget_git_dir(path)
|
|
552
|
+
try:
|
|
553
|
+
_tree_git(worktree, "worktree", "remove", "--force", str(path))
|
|
554
|
+
except GitError:
|
|
555
|
+
shutil.rmtree(path, ignore_errors=True)
|
|
556
|
+
_tree_git(worktree, "worktree", "prune")
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
@contextmanager
|
|
560
|
+
def checkout(
|
|
561
|
+
data_dir: Path,
|
|
562
|
+
repo: str,
|
|
563
|
+
pr_number: int,
|
|
564
|
+
head_sha: str,
|
|
565
|
+
base_sha: str,
|
|
566
|
+
*,
|
|
567
|
+
url: str | None = None,
|
|
568
|
+
) -> Iterator[Checkout]:
|
|
569
|
+
"""PR head로 worktree를 만들고 changes.diff를 남긴다. 블록을 나가면 worktree를 지운다."""
|
|
570
|
+
bare = ensure_bare(data_dir, repo, url)
|
|
571
|
+
fetch_pr(bare, pr_number, base_sha)
|
|
572
|
+
path = (
|
|
573
|
+
data_dir / "worktrees" / f"{repo.replace('/', '__')}-pr{pr_number}-{uuid.uuid4().hex[:8]}"
|
|
574
|
+
)
|
|
575
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
576
|
+
_git("worktree", "add", "--quiet", "--detach", str(path), head_sha, cwd=bare)
|
|
577
|
+
try:
|
|
578
|
+
record_git_dir(path)
|
|
579
|
+
fork_point = merge_base(path, base_sha, head_sha)
|
|
580
|
+
write_changes_diff(path, fork_point, head_sha)
|
|
581
|
+
yield Checkout(path=path, head_sha=head_sha, base_sha=base_sha, merge_base=fork_point)
|
|
582
|
+
finally:
|
|
583
|
+
_forget_git_dir(path)
|
|
584
|
+
try:
|
|
585
|
+
_git("worktree", "remove", "--force", str(path), cwd=bare)
|
|
586
|
+
except GitError:
|
|
587
|
+
shutil.rmtree(path, ignore_errors=True)
|
|
588
|
+
_git("worktree", "prune", cwd=bare)
|