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.
Files changed (137) hide show
  1. package/LICENSE +21 -0
  2. package/Procfile +2 -0
  3. package/README.md +300 -2
  4. package/app/__init__.py +1 -0
  5. package/app/api/__init__.py +1 -0
  6. package/app/api/cli.py +35 -0
  7. package/app/api/github.py +168 -0
  8. package/app/api/history.py +123 -0
  9. package/app/api/main.py +95 -0
  10. package/app/api/queue.py +45 -0
  11. package/app/api/responses.py +28 -0
  12. package/app/api/signature.py +19 -0
  13. package/app/api/sync.py +189 -0
  14. package/app/api/sync_rules_pure.py +71 -0
  15. package/app/api/webhook.py +166 -0
  16. package/app/setup/__init__.py +4 -0
  17. package/app/setup/cli.py +90 -0
  18. package/app/setup/configure.py +720 -0
  19. package/app/setup/files.py +93 -0
  20. package/app/setup/github_setup.py +149 -0
  21. package/app/setup/install_hints.json +32 -0
  22. package/app/setup/setup_pure.py +312 -0
  23. package/app/setup/start.py +113 -0
  24. package/app/shared/__init__.py +1 -0
  25. package/app/shared/comment_pure.py +29 -0
  26. package/app/shared/config.py +106 -0
  27. package/app/shared/db_pure.py +339 -0
  28. package/app/shared/embed_models_pure.py +55 -0
  29. package/app/shared/feedback_pure.py +84 -0
  30. package/app/shared/github_auth.py +74 -0
  31. package/app/shared/job_pure.py +43 -0
  32. package/app/shared/notify.py +97 -0
  33. package/app/shared/ops_alert_pure.py +38 -0
  34. package/app/shared/state_keys_pure.py +24 -0
  35. package/app/shared/version.py +27 -0
  36. package/app/worker/__init__.py +1 -0
  37. package/app/worker/access_pure.py +180 -0
  38. package/app/worker/ai/__init__.py +1 -0
  39. package/app/worker/ai/claude_cli.py +684 -0
  40. package/app/worker/ai/mcp_relay.py +42 -0
  41. package/app/worker/ai/path_hook.py +103 -0
  42. package/app/worker/ai/tool_server.py +139 -0
  43. package/app/worker/ai/workdir.py +333 -0
  44. package/app/worker/base_config.py +173 -0
  45. package/app/worker/budget.py +100 -0
  46. package/app/worker/cache_key_pure.py +34 -0
  47. package/app/worker/call_budget_pure.py +132 -0
  48. package/app/worker/checker_authoring_pure.py +599 -0
  49. package/app/worker/checker_pure.py +196 -0
  50. package/app/worker/cli.py +97 -0
  51. package/app/worker/command.py +191 -0
  52. package/app/worker/command_pure.py +38 -0
  53. package/app/worker/coverage.py +123 -0
  54. package/app/worker/coverage_pure.py +202 -0
  55. package/app/worker/deps.py +22 -0
  56. package/app/worker/diff_pure.py +419 -0
  57. package/app/worker/doc_rules_pure.py +201 -0
  58. package/app/worker/doc_rules_report.py +979 -0
  59. package/app/worker/eval_run_pure.py +241 -0
  60. package/app/worker/evaluation.py +151 -0
  61. package/app/worker/feedback.py +448 -0
  62. package/app/worker/feedback_pure.py +131 -0
  63. package/app/worker/feedback_report_pure.py +90 -0
  64. package/app/worker/feedback_triage.py +85 -0
  65. package/app/worker/feedback_triage_pure.py +363 -0
  66. package/app/worker/fix/__init__.py +1 -0
  67. package/app/worker/fix/decide.py +197 -0
  68. package/app/worker/fix/feedback_fix_pure.py +125 -0
  69. package/app/worker/fix/fix_decision_pure.py +386 -0
  70. package/app/worker/fix/fix_pure.py +70 -0
  71. package/app/worker/fix/mechanical_fix.py +214 -0
  72. package/app/worker/fix/model_fix.py +575 -0
  73. package/app/worker/fix/model_fix_pure.py +593 -0
  74. package/app/worker/fix/proposal.py +584 -0
  75. package/app/worker/fix/proposal_pure.py +103 -0
  76. package/app/worker/fix/scope.py +40 -0
  77. package/app/worker/fix/scope_pure.py +222 -0
  78. package/app/worker/generated_tests_pure.py +442 -0
  79. package/app/worker/github.py +471 -0
  80. package/app/worker/graph.py +963 -0
  81. package/app/worker/guard.py +91 -0
  82. package/app/worker/lang/__init__.py +0 -0
  83. package/app/worker/lang/install_pure.py +25 -0
  84. package/app/worker/lang/python.py +862 -0
  85. package/app/worker/loop.py +200 -0
  86. package/app/worker/main.py +76 -0
  87. package/app/worker/markdown_pure.py +29 -0
  88. package/app/worker/mcp_pure.py +150 -0
  89. package/app/worker/memory.py +503 -0
  90. package/app/worker/merged_fix_pure.py +236 -0
  91. package/app/worker/pr_check_report_pure.py +201 -0
  92. package/app/worker/pr_description_report_pure.py +112 -0
  93. package/app/worker/preflight.py +125 -0
  94. package/app/worker/rag_pure.py +285 -0
  95. package/app/worker/rag_switch_pure.py +203 -0
  96. package/app/worker/records.py +207 -0
  97. package/app/worker/records_pure.py +239 -0
  98. package/app/worker/repo.py +588 -0
  99. package/app/worker/repo_config_pure.py +269 -0
  100. package/app/worker/report.py +300 -0
  101. package/app/worker/retry.py +65 -0
  102. package/app/worker/rule_pure.py +223 -0
  103. package/app/worker/rule_reading_pure.py +503 -0
  104. package/app/worker/rules/__init__.py +1 -0
  105. package/app/worker/rules/checkers.py +615 -0
  106. package/app/worker/rules/detect.py +154 -0
  107. package/app/worker/rules/doc_rules.py +301 -0
  108. package/app/worker/rules/doc_sections_pure.py +168 -0
  109. package/app/worker/rules/judge.py +410 -0
  110. package/app/worker/rules/judge_pure.py +627 -0
  111. package/app/worker/rules/pr_check.py +404 -0
  112. package/app/worker/rules/pr_check_pure.py +922 -0
  113. package/app/worker/rules/pr_description.py +218 -0
  114. package/app/worker/rules/pr_description_pure.py +743 -0
  115. package/app/worker/rules/rules.py +314 -0
  116. package/app/worker/rules/run_check.py +95 -0
  117. package/app/worker/rules/run_check_pure.py +219 -0
  118. package/app/worker/rules/tool_choice_pure.py +135 -0
  119. package/app/worker/sandbox/__init__.py +1 -0
  120. package/app/worker/sandbox/checker_runner.py +412 -0
  121. package/app/worker/sandbox/container.py +130 -0
  122. package/app/worker/sandbox/docker_cli.py +170 -0
  123. package/app/worker/sandbox/safe_read.py +32 -0
  124. package/app/worker/sandbox/toolcache.py +425 -0
  125. package/app/worker/state.py +602 -0
  126. package/app/worker/test_lines.py +77 -0
  127. package/app/worker/test_run_pure.py +133 -0
  128. package/app/worker/text_edit_pure.py +66 -0
  129. package/app/worker/tools_pure.py +152 -0
  130. package/app/worker/update.py +305 -0
  131. package/app/worker/violation_pure.py +33 -0
  132. package/bin/pr-proof.js +173 -0
  133. package/docker/sandbox/Dockerfile +12 -0
  134. package/docker/sandbox/coveragerc +19 -0
  135. package/docker-compose.yml +5 -0
  136. package/package.json +31 -4
  137. package/pyproject.toml +60 -0
@@ -0,0 +1,862 @@
1
+ """Python 언어 프로필 (docs/DESIGN.md 2.3, 7.7).
2
+
3
+ 언어마다 다른 것 중 Python의 것을 여기에 모은다: 의존성 설치와 캐시(.venv), 테스트 실행과 결과
4
+ 읽기(pytest, report.json), 커버리지 읽기(coverage.xml), 도구(ruff, ruff-format).
5
+ 3단계에서는 흩어져 있던 코드를 옮기기만 했다. 두 번째 언어를 붙일 때 그 차이를 보고 인터페이스를
6
+ 정한다. coverage.xml과 문장 범위 읽기, 테스트 파일의 정의, ruff 설정과 버전 읽기, 도구 목록은
7
+ 외부 호출이 없는 순수 모듈(`app/worker/coverage_pure.py`, `app/worker/fix/scope_pure.py`의
8
+ `is_test_file`, `app/worker/tools_pure.py`)에 남는다. 그것을 쓰는 판정(허용 범위, 도구 선택)도 순수
9
+ 모듈이고, 순수 모듈은 실행 코드인 이 모듈을 import하지 않기 때문이다.
10
+
11
+ .venv (4.5, 8.1): 의존성만 설치하고 대상 리포 자체는 설치하지 않는다. 설치는 네트워크가 열린
12
+ 별도 컨테이너에서 wheel만 받고(`--only-binary :all:`, 소스 배포본은 PR이 고를 수 있는 빌드 코드를
13
+ 실행한다), 호스트의 것은 마운트하지 않는다. 의존성 파일은 표준 입력으로 복사해 넣고, 붙이는 호스트
14
+ 경로는 그 설치만의 빈 출력 폴더 하나다. 테스트 컨테이너에는 읽기 전용으로 붙인다.
15
+
16
+ coverage.xml과 worktree의 소스는 샌드박스 안의 PR 코드가 바꿀 수 있다. 호스트에서 읽을 때 심볼릭
17
+ 링크·FIFO·장치 파일을 따라가지 않고, worktree 밖을 가리키는 경로와 큰 파일은 읽지 않는다.
18
+
19
+ ruff는 이미지에 없다. 도구 캐시(app/worker/sandbox/toolcache.py)에 받은 실행 파일을 읽기 전용으로
20
+ 붙인다. 컨테이너 하나에 명령 하나다: 네트워크 없음, 루트 파일 시스템 읽기 전용, 권한 없음, 자원
21
+ 제한, 호스트 UID. 검사할 폴더는 읽기 전용이고 고치는 `format_apply`만 쓰기를 연다. 설정은 base
22
+ 커밋에서 읽은 파일을 검사할 폴더 밖에 두고 `--config`로 넘긴다. PR이 넣은 설정 파일은 읽히지
23
+ 않고(`--config`는 설정 찾기를 끈다), PR 코드가 그 사본을 바꿀 수도 없다. 설정이 없으면
24
+ `--isolated`다. `--config`의 상대 경로(per-file-ignores, exclude)는 작업 폴더(/work) 기준으로
25
+ 풀린다. 파일 경로는 `--` 뒤에만 둔다 (T9). 출력은 믿지 않는 입력이다. 크기 상한 안의 JSON·diff만
26
+ 읽고, 넘긴 파일 밖을 가리키면 결과를 버린다.
27
+ """
28
+
29
+ import hashlib
30
+ import json
31
+ import os
32
+ import re
33
+ import shlex
34
+ import shutil
35
+ import subprocess
36
+ import tempfile
37
+ import tomllib
38
+ import uuid
39
+ from collections.abc import Callable, Iterable, Iterator, Sequence
40
+ from contextlib import contextmanager
41
+ from dataclasses import dataclass
42
+ from pathlib import Path
43
+ from typing import Final
44
+
45
+ from app.worker.coverage_pure import (
46
+ MAX_COVERAGE_XML_BYTES,
47
+ CoverageData,
48
+ mark_covered,
49
+ parse_coverage_xml,
50
+ )
51
+ from app.worker.generated_tests_pure import Suite, parse_contexts, parse_report
52
+ from app.worker.lang.install_pure import InstallFailureKind
53
+ from app.worker.sandbox import docker_cli, toolcache
54
+ from app.worker.sandbox.checker_runner import (
55
+ MAX_STDERR_CHARS,
56
+ CheckerRun,
57
+ Failed,
58
+ Match,
59
+ Ran,
60
+ RawRun,
61
+ check_paths,
62
+ run_bounded,
63
+ )
64
+ from app.worker.sandbox.container import (
65
+ DEFAULT_TIMEOUT,
66
+ OUT_DIR,
67
+ PIPELINE_DIR,
68
+ POLL_SECONDS,
69
+ ExecResult,
70
+ run_in_sandbox,
71
+ )
72
+ from app.worker.sandbox.docker_cli import Image
73
+ from app.worker.sandbox.safe_read import read_regular_file
74
+ from app.worker.test_run_pure import KILLED_EXIT, PYTEST_TESTS_FAILED, PytestRun, ReportSummary
75
+ from app.worker.text_edit_pure import TextEdit
76
+ from app.worker.tools_pure import RUFF_CODE, RuffConfig
77
+ from app.worker.violation_pure import Violation
78
+
79
+ # ---- 런타임 ----
80
+
81
+ # 런타임을 붙이는 컨테이너 안 경로. .venv의 인터프리터(`pyvenv.cfg`의 home, `bin/python`)가
82
+ # 이 경로에 묶이므로 설치 컨테이너와 테스트 컨테이너가 같아야 한다
83
+ RUNTIME_IN_CONTAINER: Final = "/opt/python"
84
+ PYTHON_IN_CONTAINER: Final = f"{RUNTIME_IN_CONTAINER}/{toolcache.TOOLS[toolcache.PYTHON].binary}"
85
+
86
+
87
+ @dataclass(frozen=True)
88
+ class Runtime:
89
+ """도구 캐시에 받은 Python 런타임. version이 .venv 캐시 키에 들어간다."""
90
+
91
+ version: str
92
+ dir: Path
93
+
94
+
95
+ def ensure_runtime(cache_dir: Path, image: str) -> Runtime:
96
+ """테스트가 쓸 Python 런타임을 도구 캐시에 받는다 (이미 있으면 받지 않는다). image는 빌드된
97
+ 샌드박스 이미지 태그다(받기 컨테이너).
98
+
99
+ 받지 못하면 SandboxError(환경 오류)다. 이 플랫폼의 배포본이 없거나 해시가 다른 것도 PR 탓이
100
+ 아니라 파이프라인 쪽 문제라서 테스트 결과를 만들지 않고 재시도와 운영 알림으로 보낸다.
101
+ """
102
+ version = toolcache.TOOLS[toolcache.PYTHON].default
103
+ try:
104
+ path = toolcache.ensure(
105
+ toolcache.PYTHON, version, cache_dir=cache_dir, download=toolcache.fetcher(image)
106
+ )
107
+ except toolcache.ToolUnavailable as e:
108
+ raise docker_cli.SandboxError(f"Python 런타임을 준비하지 못함: {e}") from e
109
+ return Runtime(version, path)
110
+
111
+
112
+ # ---- 의존성 설치와 캐시 (.venv) ----
113
+
114
+ VENV_CACHE: Final = Path.home() / ".cache" / "pipeline" / "venvs"
115
+ # 리포 의존성과 함께 설치하는 검사 도구. pytest 자체는 리포가 고정한 버전을 따른다.
116
+ TOOL_REQUIREMENTS: Final = ("pytest-cov==6.0.0", "pytest-json-report==1.5.0")
117
+ INSTALL_TIMEOUT: Final = 900
118
+ # 컨테이너 안 .venv 경로. 스크립트의 인터프리터 경로가 여기에 묶이므로 설치·실행이 같아야 한다.
119
+ VENV_IN_CONTAINER: Final = "/work/.venv"
120
+ DEPS_IN_CONTAINER: Final = "/tmp/deps"
121
+ # 설치 방법의 버전. 설치 명령을 바꾸면 올린다 (캐시 키에 들어간다)
122
+ INSTALL_VERSION: Final = "runtime-cache-1"
123
+ # 표준 입력의 {파일 이름: 내용}을 DEPS_IN_CONTAINER에 쓰고, wheel만 설치한다. pip의 자세한
124
+ # 기록(-vv)은 실패했을 때만 줄여서 내보낸다: 건너뛴 링크 줄을 뺀 끝부분과, 소스 배포본만 있어
125
+ # 건너뛴 패키지 이름
126
+ _INSTALL_SCRIPT: Final = """\
127
+ {python} -I -c 'import json, os, sys
128
+ files = json.load(sys.stdin)
129
+ os.makedirs(sys.argv[1])
130
+ for name, text in files.items():
131
+ with open(os.path.join(sys.argv[1], os.path.basename(name)), "w", encoding="utf-8") as f:
132
+ f.write(text)' {deps} || exit 3
133
+ {python} -m venv {venv} || exit 4
134
+ {venv}/bin/pip install -vv --no-cache-dir --only-binary :all: {args} > /tmp/pip.log 2>&1
135
+ rc=$?
136
+ if [ "$rc" -ne 0 ]; then
137
+ grep -v '^ *Skipping link' /tmp/pip.log | tail -c 4000
138
+ grep -o 'No sources permitted for [^:]*' /tmp/pip.log | sort -u
139
+ fi
140
+ exit "$rc"
141
+ """
142
+
143
+ # pip 출력으로 설치 실패의 원인을 나눈다. 네트워크 실패에서도 "Could not find a version"이
144
+ # 함께 나오므로 네트워크 표지를 먼저 본다.
145
+ NETWORK_MARKERS: Final = (
146
+ "NewConnectionError",
147
+ "Failed to establish a new connection",
148
+ "Temporary failure in name resolution",
149
+ "Name or service not known",
150
+ "ConnectTimeoutError",
151
+ "ReadTimeoutError",
152
+ "Connection reset by peer",
153
+ "ProxyError",
154
+ "SSLError",
155
+ )
156
+ RESOLUTION_MARKERS: Final = (
157
+ "No matching distribution found",
158
+ "ResolutionImpossible",
159
+ "Could not find a version that satisfies the requirement",
160
+ "conflicting dependencies",
161
+ "Invalid requirement",
162
+ )
163
+ MAX_DETAIL_CHARS: Final = 2000
164
+ _NO_MATCH: Final = re.compile(r"No matching distribution found for ([A-Za-z0-9][A-Za-z0-9._-]*)")
165
+ _SOURCES_ONLY: Final = re.compile(r"No sources permitted for ([A-Za-z0-9][A-Za-z0-9._-]*)")
166
+ # 의존성 파일에서 받는 옵션 줄: 같이 넘긴 다른 의존성 파일을 읽는 것뿐이다. `--no-binary`,
167
+ # 색인 주소, `-e` 같은 옵션은 wheel만 받는다는 제한을 풀거나 다른 곳에서 받게 하므로 설치하지 않는다
168
+ _INCLUDE: Final = re.compile(r"^(?:-r|-c|--requirement|--constraint)[\s=]+([^\s/\\]+)$")
169
+ # 이름과 버전 조건이 아니라 주소·경로로 고른 의존성 (소스를 받아 빌드한다)
170
+ _DIRECT: Final = re.compile(r"://|\s@\s|^[./~]|^file:", re.IGNORECASE)
171
+
172
+
173
+ class DependencyInstallError(Exception):
174
+ """pip이 의존성을 설치하지 못했다. 처리는 lang/install_pure.install_failure_outcome()이
175
+ 정한다."""
176
+
177
+ def __init__(
178
+ self, kind: InstallFailureKind, cache_key: str, detail: str, packages: tuple[str, ...] = ()
179
+ ) -> None:
180
+ super().__init__(f"의존성 설치 실패 ({kind}): {detail[-500:]}")
181
+ self.kind: InstallFailureKind = kind
182
+ self.cache_key = cache_key
183
+ self.detail = detail
184
+ self.packages = packages # source_only: 소스 배포본만 있는 패키지
185
+
186
+
187
+ def classify_pip_failure(output: str) -> InstallFailureKind:
188
+ """pip 출력으로 실패 원인을 나눈다."""
189
+ if any(marker in output for marker in NETWORK_MARKERS):
190
+ return "network"
191
+ if source_only_packages(output):
192
+ return "source_only"
193
+ if any(marker in output for marker in RESOLUTION_MARKERS):
194
+ return "resolution"
195
+ return "unknown"
196
+
197
+
198
+ def disallowed_lines(files: dict[str, str]) -> list[str]:
199
+ """설치하지 않는 의존성 줄 (8.1 바이너리만 설치). 비면 설치해도 된다."""
200
+ bad = []
201
+ for name, text in files.items():
202
+ for raw in text.splitlines():
203
+ line = raw.split(" #", 1)[0].strip()
204
+ if not line or line.startswith("#"):
205
+ continue
206
+ include = _INCLUDE.match(line)
207
+ if include is not None:
208
+ if include.group(1) not in files:
209
+ bad.append(f"{name}: {line}")
210
+ elif line.startswith("-") or _DIRECT.search(line.split(";", 1)[0]):
211
+ bad.append(f"{name}: {line}")
212
+ return bad
213
+
214
+
215
+ def source_only_packages(output: str) -> tuple[str, ...]:
216
+ """찾지 못한 패키지 중 소스 배포본은 있어 건너뛴 것 (`--only-binary :all:`의 -vv 기록).
217
+
218
+ pip은 wheel이 없는 패키지와 없는 패키지를 같은 오류("No matching distribution")로 알린다.
219
+ 건너뛴 링크 기록에 그 이름이 있으면 소스 배포본만 있는 패키지다.
220
+ """
221
+ missing = {_normalize(m) for m in _NO_MATCH.findall(output)}
222
+ skipped = {_normalize(m) for m in _SOURCES_ONLY.findall(output)}
223
+ return tuple(sorted(missing & skipped))
224
+
225
+
226
+ def _normalize(name: str) -> str:
227
+ return re.sub(r"[-_.]+", "-", name).lower()
228
+
229
+
230
+ def pyproject_requirements(text: str) -> list[str]:
231
+ """pyproject.toml의 의존성과 모든 optional-dependencies. 프로젝트 자신은 뺀다."""
232
+ project = tomllib.loads(text).get("project", {})
233
+ reqs = list(project.get("dependencies", []))
234
+ for group in project.get("optional-dependencies", {}).values():
235
+ reqs.extend(group)
236
+ own = _normalize(project.get("name", ""))
237
+ return [
238
+ r for r in reqs if _normalize(re.split(r"[\s\[<>=!~;@]", r.strip(), maxsplit=1)[0]) != own
239
+ ]
240
+
241
+
242
+ def dependency_files(worktree: Path) -> list[Path]:
243
+ """의존성 파일: 루트의 requirements*.txt와 pyproject.toml. lock 파일은 아직 쓰지 않는다."""
244
+ files = sorted(worktree.glob("requirements*.txt"))
245
+ if (worktree / "pyproject.toml").is_file():
246
+ files.append(worktree / "pyproject.toml")
247
+ return files
248
+
249
+
250
+ def cache_key(worktree: Path, image: Image, runtime_version: str) -> str:
251
+ """의존성 파일 내용 + 이미지 id + 런타임 버전 + 검사 도구 버전 + 설치 방법 버전."""
252
+ h = hashlib.sha256()
253
+ for part in (image.id, runtime_version, *TOOL_REQUIREMENTS, INSTALL_VERSION):
254
+ h.update(part.encode() + b"\0")
255
+ for path in dependency_files(worktree):
256
+ h.update(path.name.encode() + b"\0" + path.read_bytes() + b"\0")
257
+ return h.hexdigest()[:24]
258
+
259
+
260
+ def deps_input(worktree: Path) -> tuple[dict[str, str], list[str]]:
261
+ """설치 컨테이너에 표준 입력으로 넘길 의존성 파일 {이름: 내용}과 pip 인자."""
262
+ files: dict[str, str] = {}
263
+ args: list[str] = []
264
+ for path in dependency_files(worktree):
265
+ if path.name == "pyproject.toml":
266
+ reqs = pyproject_requirements(path.read_text())
267
+ name, text = "pyproject-deps.txt", "\n".join(reqs) + "\n"
268
+ else:
269
+ name, text = path.name, path.read_text(encoding="utf-8", errors="replace")
270
+ files[name] = text
271
+ args += ["-r", f"{DEPS_IN_CONTAINER}/{name}"]
272
+ return files, [*args, *TOOL_REQUIREMENTS]
273
+
274
+
275
+ def install_script(pip_args: list[str]) -> str:
276
+ return _INSTALL_SCRIPT.format(
277
+ python=PYTHON_IN_CONTAINER,
278
+ deps=DEPS_IN_CONTAINER,
279
+ venv=VENV_IN_CONTAINER,
280
+ args=shlex.join(pip_args),
281
+ )
282
+
283
+
284
+ def ensure_venv(
285
+ worktree: Path,
286
+ image: Image,
287
+ runtime: Runtime,
288
+ cache_dir: Path = VENV_CACHE,
289
+ tag: str = docker_cli.IMAGE,
290
+ *,
291
+ memory_gb: float = docker_cli.MEMORY_LIMIT_GB,
292
+ ) -> Path:
293
+ """캐시 키에 맞는 .venv 경로를 돌려준다. 없으면 설치 컨테이너에서 만든다.
294
+
295
+ 임시 폴더에 설치하고 완료 표시를 남긴 뒤 캐시 경로로 옮겨, 실패한 설치가 캐시에 남지 않게 한다.
296
+ docker 자체가 실패하면 SandboxError, pip이 실패하면 DependencyInstallError를 올린다.
297
+ """
298
+ key = cache_key(worktree, image, runtime.version)
299
+ target = cache_dir / key
300
+ if (target / ".complete").is_file():
301
+ return target
302
+
303
+ cache_dir.mkdir(parents=True, exist_ok=True)
304
+ build = cache_dir / f".{key}.{uuid.uuid4().hex[:8]}.tmp"
305
+ build.mkdir()
306
+ try:
307
+ files, pip_args = deps_input(worktree)
308
+ bad = disallowed_lines(files)
309
+ if bad:
310
+ detail = "wheel만 설치하므로 받지 않는 줄:\n" + "\n".join(bad[:20])
311
+ raise DependencyInstallError("disallowed", key, detail[:MAX_DETAIL_CHARS])
312
+ proc = _run_install(
313
+ build, runtime, tag, install_script(pip_args), json.dumps(files), memory_gb
314
+ )
315
+ if proc.returncode in docker_cli.DOCKER_FAILED:
316
+ raise docker_cli.SandboxError(
317
+ f"설치 컨테이너 실행 실패 ({proc.returncode}): {proc.stderr.strip()[-500:]}"
318
+ )
319
+ if proc.returncode != 0:
320
+ output = proc.stdout + proc.stderr
321
+ raise DependencyInstallError(
322
+ classify_pip_failure(output), key, output[-MAX_DETAIL_CHARS:],
323
+ packages=source_only_packages(output),
324
+ ) # fmt: skip
325
+ marker = build / ".complete"
326
+ marker.unlink(missing_ok=True) # 설치 컨테이너가 남긴 것(링크일 수 있음)을 따라가지 않는다
327
+ marker.touch(exist_ok=False)
328
+ try:
329
+ build.rename(target)
330
+ except OSError: # 다른 작업이 같은 키를 먼저 만들었다
331
+ if not (target / ".complete").is_file():
332
+ raise
333
+ finally:
334
+ if build.exists():
335
+ shutil.rmtree(build, ignore_errors=True)
336
+ return target
337
+
338
+
339
+ def _run_install(
340
+ build: Path, runtime: Runtime, tag: str, script: str, stdin: str, memory_gb: float
341
+ ) -> subprocess.CompletedProcess[str]:
342
+ """설치 컨테이너를 만들고 런타임을 복사해 넣은 뒤 설치 스크립트를 돌린다.
343
+
344
+ 런타임은 마운트하지 않고 복사한다. 네트워크가 열린 이 컨테이너에 붙는 호스트 경로는 빈 출력
345
+ 폴더(build) 하나뿐이다 (8.1: 다른 캐시 항목을 마운트하지 않는다).
346
+ """
347
+ name = f"pr-proof-install-{uuid.uuid4().hex[:12]}"
348
+ docker_cli.run(
349
+ "create", "-i", "--name", name, *docker_cli.limits(memory_gb),
350
+ "--user", docker_cli.user(), "-e", "HOME=/tmp", "-e", "PYTHONDONTWRITEBYTECODE=1",
351
+ "-e", "PIP_DISABLE_PIP_VERSION_CHECK=1", "-e", "PIP_NO_INPUT=1",
352
+ "-v", f"{build}:{VENV_IN_CONTAINER}",
353
+ tag, "sh", "-c", script,
354
+ ) # fmt: skip
355
+ try:
356
+ docker_cli.run("cp", str(runtime.dir.resolve()), f"{name}:{RUNTIME_IN_CONTAINER}")
357
+ return docker_cli.run(
358
+ "start", "-ai", name, timeout=INSTALL_TIMEOUT, check=False, input=stdin
359
+ )
360
+ finally:
361
+ docker_cli.remove_container(name)
362
+
363
+
364
+ # ---- 테스트 실행과 결과 읽기 (pytest, report.json) ----
365
+
366
+ REPORT_FILE: Final = f"{OUT_DIR}/report.json"
367
+ RERUN_REPORT_FILE: Final = f"{OUT_DIR}/rerun.json"
368
+ # 이보다 많이 실패하면 불안정이 아니라 실제 실패로 보고 다시 돌리지 않는다
369
+ MAX_RERUN_TESTS: Final = 20
370
+ MAX_REPORT_BYTES: Final = 50 * 1024 * 1024 # 큰 테스트 묶음의 report.json도 들어가게
371
+ COVERAGE_XML: Final = f"{OUT_DIR}/coverage.xml"
372
+ # 줄마다 실행한 테스트(문맥). 수정 작성의 도구와 출구 검사만 만든다 (contexts=True)
373
+ COVERAGE_JSON: Final = f"{OUT_DIR}/coverage.json"
374
+ MAX_COVERAGE_JSON_BYTES: Final = 50 * 1024 * 1024
375
+ # coverage.xml 경로를 리포 기준 상대 경로로 남기는 파이프라인 쪽 설정 (docker/sandbox/coveragerc)
376
+ COVERAGERC: Final = f"{PIPELINE_DIR}/coveragerc"
377
+ MAX_OUTPUT_CHARS: Final = 4000
378
+
379
+
380
+ def pythonpath_for(worktree: Path) -> str:
381
+ """리포를 설치하지 않으므로 PYTHONPATH로 import 경로를 준다. src 구조면 /work/src도 넣는다."""
382
+ return "/work/src:/work" if (worktree / "src").is_dir() else "/work"
383
+
384
+
385
+ def pytest_argv(*, contexts: bool = False) -> list[str]:
386
+ """contexts면 줄마다 실행한 테스트를 coverage.json에 남긴다(`--cov-context=test`)."""
387
+ extra = ["--cov-context=test", f"--cov-report=json:{COVERAGE_JSON}"] if contexts else []
388
+ return [
389
+ ".venv/bin/pytest",
390
+ "-p", "no:cacheprovider",
391
+ "--json-report", f"--json-report-file={REPORT_FILE}",
392
+ "--cov", f"--cov-config={COVERAGERC}",
393
+ f"--cov-report=xml:{COVERAGE_XML}",
394
+ *extra,
395
+ ] # fmt: skip
396
+
397
+
398
+ def rerun_argv(node_ids: list[str]) -> list[str]:
399
+ """실패한 테스트만 한 번 더. coverage는 처음 실행 것을 쓰므로 다시 만들지 않는다."""
400
+ return [
401
+ ".venv/bin/pytest", "-p", "no:cacheprovider",
402
+ "--json-report", f"--json-report-file={RERUN_REPORT_FILE}",
403
+ "--", *node_ids,
404
+ ] # fmt: skip
405
+
406
+
407
+ def _read_json(report: Path) -> object:
408
+ """PR 코드가 바꿀 수 있는 결과 파일. 일반 파일만 읽는다 (링크·FIFO면 없는 것으로 본다)."""
409
+ data = read_regular_file(report, max_bytes=MAX_REPORT_BYTES)
410
+ if data is None:
411
+ return None
412
+ return json.loads(data)
413
+
414
+
415
+ def passed_ids(report: Path) -> set[str]:
416
+ try:
417
+ data = _read_json(report)
418
+ return {t["nodeid"] for t in data.get("tests", []) if t.get("outcome") == "passed"}
419
+ except (ValueError, KeyError, TypeError, AttributeError):
420
+ return set()
421
+
422
+
423
+ def read_summary(report: Path) -> ReportSummary | None:
424
+ """report.json을 읽는다. 없거나(링크·FIFO 포함) 깨졌으면 None."""
425
+ try:
426
+ data = _read_json(report)
427
+ return None if data is None else ReportSummary.from_report(data)
428
+ except (ValueError, KeyError, TypeError, AttributeError):
429
+ return None
430
+
431
+
432
+ def run_tests(
433
+ container: str,
434
+ worktree: Path,
435
+ *,
436
+ timeout: int = DEFAULT_TIMEOUT,
437
+ is_stale: Callable[[], bool] | None = None,
438
+ poll_seconds: float = POLL_SECONDS,
439
+ contexts: bool = False,
440
+ ) -> PytestRun:
441
+ """컨테이너 안에서 pytest를 실행하고 결과를 PytestRun으로 돌려준다."""
442
+ report = worktree / REPORT_FILE
443
+ coverage_xml = worktree / COVERAGE_XML
444
+ for leftover in (report, coverage_xml, worktree / COVERAGE_JSON,
445
+ worktree / OUT_DIR / ".coverage"): # fmt: skip
446
+ leftover.unlink(missing_ok=True)
447
+
448
+ result = run_in_sandbox(
449
+ container,
450
+ pytest_argv(contexts=contexts),
451
+ env={"PYTHONPATH": pythonpath_for(worktree), "PYTHONDONTWRITEBYTECODE": "1"},
452
+ timeout=timeout,
453
+ is_stale=is_stale,
454
+ poll_seconds=poll_seconds,
455
+ )
456
+ summary = read_summary(report)
457
+ oom_killed = _check_environment(container, result, has_report=summary is not None)
458
+ flaky = _rerun_failed(container, worktree, result, summary, timeout, is_stale, poll_seconds)
459
+ return PytestRun(
460
+ flaky=flaky,
461
+ exit_code=result.returncode,
462
+ summary=summary,
463
+ report_path=report if summary is not None else None,
464
+ coverage_xml=coverage_xml if coverage_xml.is_file() else None,
465
+ timed_out=result.timed_out,
466
+ cancelled=result.cancelled,
467
+ oom_killed=oom_killed,
468
+ output=(result.stdout + result.stderr)[-MAX_OUTPUT_CHARS:],
469
+ )
470
+
471
+
472
+ def _rerun_failed(
473
+ container: str,
474
+ worktree: Path,
475
+ result: ExecResult,
476
+ summary: ReportSummary | None,
477
+ timeout: int,
478
+ is_stale: Callable[[], bool] | None,
479
+ poll_seconds: float,
480
+ ) -> tuple[str, ...]:
481
+ """실패한 테스트를 한 번 다시 돌려, 통과한 것(flaky)을 돌려준다 (DESIGN.md F8).
482
+
483
+ 테스트 실패(종료 코드 1)일 때만 한다. 수집 오류·테스트 오류는 다시 돌려도 같으므로 하지 않는다.
484
+ """
485
+ if result.returncode != PYTEST_TESTS_FAILED or summary is None or summary.errors:
486
+ return ()
487
+ failed = list(summary.failed_tests)
488
+ if not failed or len(failed) > MAX_RERUN_TESTS:
489
+ return ()
490
+ rerun_report = worktree / RERUN_REPORT_FILE
491
+ rerun_report.unlink(missing_ok=True)
492
+ rerun = run_in_sandbox(
493
+ container,
494
+ rerun_argv(failed),
495
+ env={"PYTHONPATH": pythonpath_for(worktree), "PYTHONDONTWRITEBYTECODE": "1"},
496
+ timeout=timeout,
497
+ is_stale=is_stale,
498
+ poll_seconds=poll_seconds,
499
+ )
500
+ if rerun.cancelled or rerun.timed_out or rerun.returncode in docker_cli.DOCKER_FAILED:
501
+ return () # 처음 결과(실패)를 그대로 쓴다
502
+ passed = passed_ids(rerun_report)
503
+ return tuple(t for t in failed if t in passed)
504
+
505
+
506
+ def _check_environment(container: str, result: ExecResult, *, has_report: bool) -> bool:
507
+ """PR 코드 탓이 아닌 실패를 SandboxError(환경 오류)로 올리고, OOM 종료 여부를 돌려준다.
508
+
509
+ 취소·시간 초과를 먼저 거른다 (그때는 파이프라인이 컨테이너를 지웠다).
510
+ docker exec 자체가 실패했거나, 결과 파일이 없는데 컨테이너가 OOM이 아닌 이유로 사라졌으면
511
+ 환경 오류다. 메모리 한도로 컨테이너가 죽은 것은 PR 코드 문제(unrunnable)다.
512
+ """
513
+ returncode = result.returncode
514
+ if result.cancelled or result.timed_out or returncode is None:
515
+ return False
516
+ if returncode in docker_cli.DOCKER_FAILED:
517
+ raise docker_cli.SandboxError(
518
+ f"docker exec 실패 ({returncode}): {result.stderr.strip()[-500:]}"
519
+ )
520
+ if has_report or returncode == 0:
521
+ return False
522
+ state = docker_cli.container_state(container)
523
+ if state is not None and state.oom_killed:
524
+ return True
525
+ if state is None or not state.running:
526
+ raise docker_cli.SandboxError(f"컨테이너 {container}가 실행 중이 아니다 ({returncode})")
527
+ return False
528
+
529
+
530
+ # ---- 커버리지 읽기와 줄 대응 (coverage.xml) ----
531
+
532
+ MAX_SOURCE_BYTES: Final = 2 * 1024 * 1024
533
+
534
+
535
+ def read_coverage(
536
+ coverage_xml: Path | None, *, max_bytes: int = MAX_COVERAGE_XML_BYTES
537
+ ) -> CoverageData | None:
538
+ """샌드박스가 남긴 coverage.xml을 읽는다. 없거나 깨졌으면 None (모름)."""
539
+ if coverage_xml is None:
540
+ return None
541
+ data = read_regular_file(coverage_xml, max_bytes=max_bytes)
542
+ if data is None:
543
+ return None
544
+ return parse_coverage_xml(data, max_bytes=max_bytes)
545
+
546
+
547
+ def _path_inside(worktree: Path, rel: str) -> Path | None:
548
+ """worktree 안의 실제 경로. 절대 경로이거나 중간 링크가 worktree 밖을 가리키면 None."""
549
+ if os.path.isabs(rel):
550
+ return None
551
+ root = worktree.resolve()
552
+ path = (root / rel).resolve()
553
+ return path if path.is_relative_to(root) else None
554
+
555
+
556
+ def read_sources(
557
+ worktree: Path, files: Iterable[str], *, max_bytes: int = MAX_SOURCE_BYTES
558
+ ) -> dict[str, str]:
559
+ """위반이 있는 파일의 소스를 {리포 기준 경로: 내용}으로 읽는다. 못 읽은 파일은 빠진다."""
560
+ sources: dict[str, str] = {}
561
+ for rel in dict.fromkeys(files):
562
+ path = _path_inside(worktree, rel)
563
+ if path is None:
564
+ continue
565
+ data = read_regular_file(path, max_bytes=max_bytes)
566
+ if data is None:
567
+ continue
568
+ try:
569
+ sources[rel] = data.decode("utf-8")
570
+ except UnicodeDecodeError:
571
+ continue
572
+ return sources
573
+
574
+
575
+ def read_suite(run: PytestRun, worktree: Path, files: Iterable[str]) -> Suite:
576
+ """테스트 한 번의 결과에서 판단에 쓰는 것: 테스트 파일마다 결과와 수, files의 줄마다 실행한
577
+ 테스트 파일 (`generated_tests_pure.Suite`). 결과 파일은 PR 코드가 바꿀 수 있어 일반 파일만
578
+ 읽고, 없거나 깨졌으면 빈 값이다."""
579
+ try:
580
+ report = _read_json(run.report_path) if run.report_path is not None else None
581
+ except (ValueError, UnicodeDecodeError, RecursionError):
582
+ report = None
583
+ outcomes, counts = parse_report(report)
584
+ data = read_regular_file(worktree / COVERAGE_JSON, max_bytes=MAX_COVERAGE_JSON_BYTES)
585
+ lines = (parse_contexts(data, files) if data is not None else None) or {}
586
+ return Suite(run=run, outcomes=outcomes, counts=counts, lines=lines)
587
+
588
+
589
+ def annotate_coverage(
590
+ findings: Iterable[Violation], coverage_xml: Path | None, worktree: Path
591
+ ) -> tuple[Violation, ...]:
592
+ """위반에 covered를 채운다. coverage.xml은 `PytestRun.coverage_xml`(수정 전 실행)이다."""
593
+ findings = tuple(findings)
594
+ coverage = read_coverage(coverage_xml)
595
+ if coverage is None:
596
+ return mark_covered(findings, None)
597
+ return mark_covered(findings, coverage, read_sources(worktree, (f.file for f in findings)))
598
+
599
+
600
+ # ---- 도구 ruff, ruff-format ----
601
+
602
+ RUFF_WORK: Final = "/work"
603
+ RUFF_MOUNT: Final = "/tools/ruff"
604
+ CONFIG_MOUNT: Final = "/config"
605
+ RUFF_TIMEOUT: Final = 120
606
+ SYNTAX_ERROR_CODE: Final = "syntax-error"
607
+ SAFE_FIX: Final = "safe" # 동작을 바꾸지 않는 수정. unsafe·display-only는 적용하지 않는다
608
+ FORMAT_MESSAGE: Final = "ruff format이 이 줄을 바꾼다"
609
+ # ruff-format이 찾은 위반의 코드. ruff의 규칙 코드가 아니다
610
+ FORMAT_CODE: Final = "format"
611
+ # ruff 종료 코드: 0 위반 없음(포맷 그대로), 1 위반 있음(포맷이 바뀜), 2 설정·인자 오류 등
612
+ _RUFF_OK: Final = frozenset({0, 1})
613
+
614
+ # (포맷돼 있음 또는 적용함) True, (포맷돼 있지 않음) False, 오류는 그 이유
615
+ FormatResult = bool | str
616
+
617
+
618
+ @contextmanager
619
+ def _ruff_container(
620
+ root: Path,
621
+ *,
622
+ tool_dir: Path,
623
+ image: str,
624
+ config: RuffConfig | None,
625
+ writable: bool = False,
626
+ memory_gb: float = docker_cli.MEMORY_LIMIT_GB,
627
+ ) -> Iterator[tuple[list[str], list[str]]]:
628
+ """(docker 인자, ruff 설정 인자). 설정 사본은 검사할 폴더 밖의 임시 폴더에 둔다."""
629
+ with tempfile.TemporaryDirectory(prefix="pipeline-ruff-") as tmp:
630
+ mounts = ["-v", f"{root.resolve()}:{RUFF_WORK}{'' if writable else ':ro'}",
631
+ "-v", f"{tool_dir.resolve()}:{RUFF_MOUNT}:ro"] # fmt: skip
632
+ if config is not None:
633
+ (Path(tmp) / config.name).write_text(config.text)
634
+ mounts += ["-v", f"{tmp}:{CONFIG_MOUNT}:ro"]
635
+ config_args = ["--config", f"{CONFIG_MOUNT}/{config.name}"]
636
+ else:
637
+ config_args = ["--isolated"]
638
+ docker = [
639
+ "run", "--rm", "-i", "--network", "none", "--read-only", *docker_cli.limits(memory_gb),
640
+ "--user", docker_cli.user(), "-e", "HOME=/tmp", *mounts, "-w", RUFF_WORK,
641
+ image, f"{RUFF_MOUNT}/ruff",
642
+ ] # fmt: skip
643
+ yield docker, config_args
644
+
645
+
646
+ def _ruff_failure(result: RawRun, timeout: int, what: str) -> CheckerRun | None:
647
+ """결과를 쓸 수 없으면 그 이유. docker 자체가 실패했으면 SandboxError (환경 오류)."""
648
+ stderr = result.stderr.strip()[-MAX_STDERR_CHARS:]
649
+ if result.too_large:
650
+ return Failed(f"{what} 출력이 크기 상한을 넘음")
651
+ if result.timed_out:
652
+ return Failed(f"{what}이 {timeout}초 안에 끝나지 않음")
653
+ if result.returncode in docker_cli.DOCKER_FAILED:
654
+ raise docker_cli.SandboxError(f"docker run 실패 ({result.returncode}): {stderr}")
655
+ if result.returncode == KILLED_EXIT:
656
+ return Failed(f"{what}이 메모리 한도를 넘었거나 강제로 끝남")
657
+ if result.returncode not in _RUFF_OK:
658
+ return Failed(f"{what} 실행 오류: {stderr or f'종료 코드 {result.returncode}'}")
659
+ return None
660
+
661
+
662
+ def ruff_check(
663
+ root: Path,
664
+ files: Sequence[str],
665
+ *,
666
+ tool_dir: Path,
667
+ image: str,
668
+ config: RuffConfig | None,
669
+ codes: Sequence[str] = (),
670
+ timeout: int = RUFF_TIMEOUT,
671
+ ) -> CheckerRun:
672
+ """root 아래 files에 `ruff check`를 돌린다. codes가 있으면 그 규칙만(`--select`), 없으면 설정의
673
+ 규칙이다. 명시한 파일도 설정의 exclude를 따르게 `--force-exclude`를 쓴다."""
674
+ check_paths(files)
675
+ if not files:
676
+ return Ran(())
677
+ select = ["--select", ",".join(codes)] if codes else []
678
+ with _ruff_container(root, tool_dir=tool_dir, image=image, config=config) as (
679
+ docker,
680
+ config_args,
681
+ ):
682
+ argv = [*docker, "check", "--no-cache", "--output-format", "json", "--force-exclude",
683
+ *config_args, *select, "--", *files] # fmt: skip
684
+ result = run_bounded(argv, b"", timeout=timeout)
685
+ failed = _ruff_failure(result, timeout, "ruff")
686
+ if failed is not None:
687
+ return failed
688
+ try:
689
+ matches = parse_ruff_check(result.stdout.decode(errors="replace"))
690
+ except (ValueError, KeyError, TypeError) as e:
691
+ return Failed(f"ruff 출력을 읽지 못함 ({e})")
692
+ return _only_given_files(matches, files)
693
+
694
+
695
+ def _only_given_files(matches: tuple[Match, ...], files: Sequence[str]) -> CheckerRun:
696
+ outside = sorted({m.file for m in matches} - set(files))
697
+ if outside:
698
+ return Failed(f"출력이 넘기지 않은 파일을 가리킴: {', '.join(outside[:5])}")
699
+ return Ran(matches)
700
+
701
+
702
+ def _repo_path(filename: str) -> str:
703
+ prefix = RUFF_WORK + "/"
704
+ return filename[len(prefix) :] if filename.startswith(prefix) else filename
705
+
706
+
707
+ def parse_ruff_check(stdout: str) -> tuple[Match, ...]:
708
+ """ruff JSON 출력을 읽는다. 파일 경로는 /work/ 기준이라 저장소 기준으로 바꾼다."""
709
+ items = json.loads(stdout or "[]")
710
+ if not isinstance(items, list):
711
+ raise TypeError("최상위가 목록이 아님")
712
+ out = []
713
+ for item in items:
714
+ start = item["location"]["row"]
715
+ end = (item.get("end_location") or {}).get("row", start)
716
+ if not (isinstance(start, int) and isinstance(end, int)) or start < 1 or end < start:
717
+ raise ValueError(f"줄 범위가 틀림: {start!r}–{end!r}")
718
+ out.append(
719
+ Match(
720
+ file=_repo_path(item["filename"]),
721
+ line=start,
722
+ end_line=end,
723
+ message=str(item["message"]),
724
+ code=item.get("code") or SYNTAX_ERROR_CODE,
725
+ edits=_safe_edits(item.get("fix")),
726
+ )
727
+ )
728
+ return tuple(out)
729
+
730
+
731
+ def _safe_edits(fix: dict | None) -> tuple[TextEdit, ...]:
732
+ """안전한 수정의 편집 목록. 위치는 1부터 세는 줄·열(문자 단위)이다."""
733
+ if not fix or fix.get("applicability") != SAFE_FIX:
734
+ return ()
735
+ return tuple(
736
+ TextEdit(
737
+ row=e["location"]["row"],
738
+ column=e["location"]["column"],
739
+ end_row=e["end_location"]["row"],
740
+ end_column=e["end_location"]["column"],
741
+ content=e.get("content") or "",
742
+ )
743
+ for e in fix.get("edits") or ()
744
+ )
745
+
746
+
747
+ def format_diff(
748
+ root: Path,
749
+ files: Sequence[str],
750
+ *,
751
+ tool_dir: Path,
752
+ image: str,
753
+ config: RuffConfig | None,
754
+ timeout: int = RUFF_TIMEOUT,
755
+ ) -> CheckerRun:
756
+ """`ruff format --diff`가 바꿀 줄. 바꿀 덩어리마다 Match 하나다 (원래 파일의 줄 번호)."""
757
+ check_paths(files)
758
+ if not files:
759
+ return Ran(())
760
+ with _ruff_container(root, tool_dir=tool_dir, image=image, config=config) as (
761
+ docker,
762
+ config_args,
763
+ ):
764
+ argv = [*docker, "format", "--no-cache", "--force-exclude", "--diff", *config_args, "--",
765
+ *files] # fmt: skip
766
+ result = run_bounded(argv, b"", timeout=timeout)
767
+ failed = _ruff_failure(result, timeout, "ruff format")
768
+ if failed is not None:
769
+ return failed
770
+ return _only_given_files(parse_format_diff(result.stdout.decode(errors="replace")), files)
771
+
772
+
773
+ def parse_format_diff(diff: str) -> tuple[Match, ...]:
774
+ """unified diff에서 원래 파일의 바뀌는 줄 범위. 줄을 더하기만 하는 덩어리는 그 앞줄이다."""
775
+ out: list[Match] = []
776
+ file = ""
777
+ old = 0
778
+ changed: list[int] = []
779
+
780
+ def close() -> None:
781
+ if file and changed:
782
+ out.append(Match(file, min(changed), max(changed), FORMAT_MESSAGE, FORMAT_CODE))
783
+ changed.clear()
784
+
785
+ for line in diff.splitlines():
786
+ if line.startswith("--- "):
787
+ close()
788
+ file = _repo_path(line[4:].split("\t")[0].strip())
789
+ elif line.startswith("+++ "):
790
+ continue
791
+ elif line.startswith("@@"):
792
+ close()
793
+ old = int(line.split()[1].lstrip("-").split(",")[0])
794
+ elif line.startswith("-"):
795
+ changed.append(old)
796
+ old += 1
797
+ elif line.startswith("+"):
798
+ changed.append(max(1, old - 1))
799
+ elif line.startswith(" "):
800
+ close()
801
+ old += 1
802
+ close()
803
+ return tuple(out)
804
+
805
+
806
+ def format_check(
807
+ root: Path,
808
+ *,
809
+ tool_dir: Path,
810
+ image: str,
811
+ config: RuffConfig | None,
812
+ timeout: int = RUFF_TIMEOUT,
813
+ ) -> FormatResult:
814
+ """root 전체가 `ruff format --check`를 통과하는지 (4.7: base가 포맷돼 있을 때만 포맷한다)."""
815
+ with _ruff_container(root, tool_dir=tool_dir, image=image, config=config) as (
816
+ docker,
817
+ config_args,
818
+ ):
819
+ argv = [*docker, "format", "--no-cache", "--force-exclude", "--check", *config_args, "--",
820
+ "."] # fmt: skip
821
+ result = run_bounded(argv, b"", timeout=timeout)
822
+ failed = _ruff_failure(result, timeout, "ruff format")
823
+ if isinstance(failed, Failed):
824
+ return failed.reason
825
+ return result.returncode == 0
826
+
827
+
828
+ def format_apply(
829
+ root: Path,
830
+ files: Sequence[str],
831
+ *,
832
+ tool_dir: Path,
833
+ image: str,
834
+ config: RuffConfig | None,
835
+ timeout: int = RUFF_TIMEOUT,
836
+ ) -> FormatResult:
837
+ """files를 `ruff format`으로 고친다. root를 쓰기로 붙이는 유일한 실행이다."""
838
+ check_paths(files)
839
+ if not files:
840
+ return True
841
+ with _ruff_container(root, tool_dir=tool_dir, image=image, config=config, writable=True) as (
842
+ docker,
843
+ args,
844
+ ):
845
+ argv = [*docker, "format", "--no-cache", "--force-exclude", *args, "--", *files]
846
+ result = run_bounded(argv, b"", timeout=timeout)
847
+ failed = _ruff_failure(result, timeout, "ruff format")
848
+ if isinstance(failed, Failed):
849
+ return failed.reason
850
+ return result.returncode == 0 or f"ruff format 종료 코드 {result.returncode}"
851
+
852
+
853
+ def ruff_rule_exists(code: str, *, tool_dir: Path, image: str, timeout: int = 30) -> bool:
854
+ """`ruff rule <코드>`가 그 규칙을 아는지 (4.4: 모델이 고른 코드가 실재하는지)."""
855
+ if not RUFF_CODE.match(code): # 형식이 맞는 코드만 인자로 넘긴다 (`-`로 시작하는 옵션이 아님)
856
+ return False
857
+ with tempfile.TemporaryDirectory(prefix="pipeline-ruff-") as tmp:
858
+ with _ruff_container(Path(tmp), tool_dir=tool_dir, image=image, config=None) as (docker, _):
859
+ result = run_bounded([*docker, "rule", code], b"", timeout=timeout)
860
+ if result.returncode in docker_cli.DOCKER_FAILED:
861
+ raise docker_cli.SandboxError(f"docker run 실패 ({result.returncode}): {result.stderr}")
862
+ return result.returncode == 0 and not result.timed_out