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,202 @@
1
+ """위반 줄 커버리지 (docs/DESIGN.md 4.5, F8). 수정 판단은 보지 않고, 고친 위반의 표시(4.9)와 만든
2
+ 테스트의 판정(4.8의 6번)에 쓴다.
3
+
4
+ `coverage.xml`은 샌드박스에서 PR 코드가 도는 동안 만들어지므로 믿을 수 없는 입력으로 다룬다.
5
+ DTD·엔티티를 거부하는 파서(defusedxml)로 읽고 크기를 제한하며, 형식이 조금이라도 어긋나면
6
+ "모름"(None)으로 돌려준다. 파일 읽기는 호출하는 쪽(`app/worker/coverage.py`)이 한다.
7
+ """
8
+
9
+ import ast
10
+ from collections.abc import Iterable, Mapping
11
+ from dataclasses import dataclass, replace
12
+ from typing import Final
13
+ from xml.etree.ElementTree import Element, ParseError
14
+
15
+ from defusedxml import DefusedXmlException
16
+ from defusedxml.ElementTree import fromstring
17
+
18
+ from app.worker.violation_pure import Violation
19
+
20
+ # 이보다 큰 coverage.xml은 읽지 않는다 (모름으로 본다)
21
+ MAX_COVERAGE_XML_BYTES: Final = 20 * 1024 * 1024
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class FileCoverage:
26
+ """파일 하나의 줄 커버리지. measured는 coverage.py가 실행 단위로 센 줄(문장의 첫 줄)이다."""
27
+
28
+ measured: frozenset[int]
29
+ executed: frozenset[int]
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class CoverageData:
34
+ """리포 기준 경로별 줄 커버리지. 테스트가 import하지 않은 파일은 들어 있지 않다."""
35
+
36
+ files: Mapping[str, FileCoverage]
37
+
38
+
39
+ def _normalize(path: str) -> str:
40
+ return path.replace("\\", "/").removeprefix("./")
41
+
42
+
43
+ def parse_coverage_xml(
44
+ data: bytes, *, max_bytes: int = MAX_COVERAGE_XML_BYTES
45
+ ) -> CoverageData | None:
46
+ """Cobertura 형식 coverage.xml을 읽는다. 크거나 깨졌거나 DTD·엔티티가 있으면 None."""
47
+ if len(data) > max_bytes:
48
+ return None
49
+ try:
50
+ root = fromstring(data, forbid_dtd=True, forbid_entities=True, forbid_external=True)
51
+ except (ParseError, DefusedXmlException, ValueError):
52
+ return None
53
+ if root.tag != "coverage":
54
+ return None
55
+ measured: dict[str, set[int]] = {}
56
+ executed: dict[str, set[int]] = {}
57
+ for clazz in root.iter("class"):
58
+ filename = clazz.get("filename")
59
+ if not filename:
60
+ return None
61
+ path = _normalize(filename)
62
+ file_measured = measured.setdefault(path, set())
63
+ file_executed = executed.setdefault(path, set())
64
+ for line in _lines(clazz):
65
+ parsed = _parse_line(line)
66
+ if parsed is None:
67
+ return None
68
+ number, hits = parsed
69
+ file_measured.add(number)
70
+ if hits > 0:
71
+ file_executed.add(number)
72
+ return CoverageData(
73
+ files={
74
+ path: FileCoverage(frozenset(lines), frozenset(executed[path]))
75
+ for path, lines in measured.items()
76
+ }
77
+ )
78
+
79
+
80
+ def _lines(clazz: Element) -> list[Element]:
81
+ return clazz.findall("./lines/line")
82
+
83
+
84
+ def _parse_line(line: Element) -> tuple[int, int] | None:
85
+ try:
86
+ number = int(line.get("number", ""))
87
+ hits = int(line.get("hits", ""))
88
+ except ValueError:
89
+ return None
90
+ if number < 1 or hits < 0:
91
+ return None
92
+ return number, hits
93
+
94
+
95
+ @dataclass(frozen=True)
96
+ class _Stmt:
97
+ start: int # 데코레이터가 있으면 그 줄부터
98
+ end: int
99
+ depth: int
100
+ lines: tuple[int, ...] # coverage.py가 이 문장을 셀 수 있는 줄 (데코레이터 줄, 문장 첫 줄)
101
+ first_child: int | None # 안에 든 첫 문장의 시작 줄 (복합문의 머리 범위를 정한다)
102
+
103
+
104
+ def _statements(source: str) -> list[_Stmt] | None:
105
+ """소스의 모든 문장과 줄 범위. 파싱할 수 없으면 None. 코드를 실행하지 않는다."""
106
+ try:
107
+ tree = ast.parse(source)
108
+ except (SyntaxError, ValueError, RecursionError, MemoryError):
109
+ return None
110
+ result: list[_Stmt] = []
111
+
112
+ def visit(node: ast.AST, depth: int) -> int | None:
113
+ """node 아래 문장을 모으고, 그중 가장 먼저 시작하는 문장의 줄을 돌려준다."""
114
+ first: int | None = None
115
+ for child in ast.iter_child_nodes(node):
116
+ if isinstance(child, ast.stmt):
117
+ decorators = [d.lineno for d in getattr(child, "decorator_list", [])]
118
+ start = min([child.lineno, *decorators])
119
+ inner = visit(child, depth + 1)
120
+ result.append(
121
+ _Stmt(
122
+ start=start,
123
+ end=child.end_lineno or child.lineno,
124
+ depth=depth,
125
+ lines=(*decorators, child.lineno),
126
+ first_child=inner,
127
+ )
128
+ )
129
+ else:
130
+ start = visit(child, depth)
131
+ if start is not None and (first is None or start < first):
132
+ first = start
133
+ return first
134
+
135
+ try:
136
+ visit(tree, 0)
137
+ except RecursionError:
138
+ return None
139
+ return result
140
+
141
+
142
+ def statements(source: str) -> list[_Stmt] | None:
143
+ """`line_covered`에 넘기는 문장 범위. 파싱할 수 없으면 None."""
144
+ return _statements(source)
145
+
146
+
147
+ def line_covered(file_cov: FileCoverage, line: int, statements: list[_Stmt] | None) -> bool:
148
+ """줄 하나가 테스트로 실행됐는지.
149
+
150
+ 1. coverage.py가 센 줄이면 그 결과를 쓴다.
151
+ 2. 아니면 소스(statements)에서 그 줄을 감싸는 가장 안쪽 문장을 찾는다. 여러 줄 문장의
152
+ 이어지는 줄과 복합문의 머리(여러 줄 `if (...)`, 데코레이터와 `def` 사이)는 그 문장의
153
+ 첫 줄(데코레이터가 있으면 데코레이터 줄부터)의 결과를 쓴다.
154
+ 3. 그 밖(복합문 몸통 사이의 빈 줄·주석, `else:`·`except:` 줄, 소스 없음, 파싱 실패,
155
+ `# pragma: no cover`로 빠진 문장)은 실행되지 않은 것으로 본다. 확실하지 않으면 자동
156
+ 수정 대상에서 빼는 쪽을 고른다.
157
+ """
158
+ if line in file_cov.measured:
159
+ return line in file_cov.executed
160
+ if statements is None:
161
+ return False
162
+ containing = [s for s in statements if s.start <= line <= s.end]
163
+ if not containing:
164
+ return False
165
+ stmt = max(containing, key=lambda s: (s.depth, -s.start))
166
+ if stmt.first_child is not None and line >= stmt.first_child:
167
+ return False # 복합문 몸통 안이지만 어느 문장에도 속하지 않는 줄
168
+ for candidate in stmt.lines:
169
+ if candidate in file_cov.measured:
170
+ return candidate in file_cov.executed
171
+ return False
172
+
173
+
174
+ def mark_covered(
175
+ findings: Iterable[Violation],
176
+ coverage: CoverageData | None,
177
+ sources: Mapping[str, str] | None = None,
178
+ ) -> tuple[Violation, ...]:
179
+ """위반마다 covered를 채운다.
180
+
181
+ - coverage가 None(파일 없음·깨짐): 모두 None(모름)
182
+ - coverage.xml에 없는 파일: False (테스트가 import하지 않았다)
183
+ - 그 밖: `line_covered`의 규칙. sources는 리포 기준 경로별 소스이고,
184
+ 소스가 없는 파일은 2단계를 건너뛴다
185
+ """
186
+ findings = tuple(findings)
187
+ if coverage is None:
188
+ return tuple(replace(f, covered=None) for f in findings)
189
+ sources = sources or {}
190
+ parsed: dict[str, list[_Stmt] | None] = {}
191
+ result = []
192
+ for f in findings:
193
+ path = _normalize(f.file)
194
+ file_cov = coverage.files.get(path)
195
+ if file_cov is None:
196
+ result.append(replace(f, covered=False))
197
+ continue
198
+ if path not in parsed:
199
+ source = sources.get(f.file, sources.get(path))
200
+ parsed[path] = _statements(source) if source is not None else None
201
+ result.append(replace(f, covered=line_covered(file_cov, f.line, parsed[path])))
202
+ return tuple(result)
@@ -0,0 +1,22 @@
1
+ """워커 작업이 쓰는 의존 객체. 테스트에서는 가짜를 넣는다."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+ from redis import Redis
6
+
7
+ from app.shared import config
8
+ from app.worker.github import GitHub
9
+ from app.worker.state import Store
10
+
11
+
12
+ @dataclass
13
+ class Deps:
14
+ store: Store
15
+ github: GitHub
16
+ settings: config.PipelineConfig
17
+
18
+ @classmethod
19
+ def from_config(cls) -> "Deps":
20
+ settings = config.load_config()
21
+ redis = Redis.from_url(settings.redis_url)
22
+ return cls(Store(settings.db_path, redis), GitHub(), settings)
@@ -0,0 +1,419 @@
1
+ """changes.diff에서 PR이 추가·수정한 줄을 읽는다 (docs/DESIGN.md F6).
2
+
3
+ 위반은 PR이 바꾼 줄에 걸린 것만 다룬다. 기존 코드의 위반은 PR 작성자의 책임이 아니다.
4
+ """
5
+
6
+ import codecs
7
+ import re
8
+ from collections import Counter
9
+ from collections.abc import Iterator, Mapping
10
+ from dataclasses import dataclass
11
+ from typing import Final
12
+
13
+ _HUNK: Final = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
14
+ _NEW_FILE_HEADER: Final = "+++ "
15
+ _OLD_FILE_HEADER: Final = "--- "
16
+ _DELETED: Final = "+++ /dev/null"
17
+
18
+ ChangedLines = Mapping[str, frozenset[int]]
19
+
20
+
21
+ def _new_path(header: str) -> str | None:
22
+ """`+++ b/<경로>` 헤더의 경로. 형식이 다르면 None.
23
+
24
+ git은 공백이 든 경로 뒤에 탭을 붙이고, 특수 문자가 든 경로는 `"b/\\353..."`처럼 C 형식으로
25
+ 감싼다 (core.quotePath). 그대로 읽으면 그 파일의 바뀐 줄이 빠져 위반이 보이지 않는다.
26
+ """
27
+ raw = header[len(_NEW_FILE_HEADER) :].removesuffix("\t")
28
+ if raw.startswith('"') and raw.endswith('"') and len(raw) >= 2:
29
+ raw = codecs.escape_decode(raw[1:-1].encode())[0].decode("utf-8", "surrogateescape")
30
+ return raw.removeprefix("b/") if raw.startswith("b/") else None
31
+
32
+
33
+ def added_lines(diff: str) -> ChangedLines:
34
+ """파일(리포 기준 경로)별로 head에서 추가·수정된 줄 번호. 삭제된 파일은 들어가지 않는다.
35
+
36
+ hunk 안에서는 헤더의 줄 수만큼 내용 줄로 읽는다. 추가된 내용이 `++`로 시작하면
37
+ diff에는 `+++`로 보이므로, 줄 수를 세지 않으면 파일 헤더로 잘못 읽는다.
38
+ """
39
+ result: dict[str, set[int]] = {}
40
+ for path, tag, line_no, _ in _content_lines(diff):
41
+ if tag == "+":
42
+ result.setdefault(path, set()).add(line_no)
43
+ return {path: frozenset(lines) for path, lines in result.items()}
44
+
45
+
46
+ def added_texts(diff: str) -> Mapping[str, Counter[str]]:
47
+ """파일별로 추가·수정된 줄의 내용(같은 내용은 개수로)."""
48
+ result: dict[str, Counter[str]] = {}
49
+ for path, tag, _, text in _content_lines(diff):
50
+ if tag == "+":
51
+ result.setdefault(path, Counter())[text] += 1
52
+ return result
53
+
54
+
55
+ def added_lines_except_moved(diff: str, pr_added: Mapping[str, Counter[str]]) -> ChangedLines:
56
+ """`added_lines`에서, 수정이 자리만 옮긴 base의 줄을 뺀다.
57
+
58
+ 수정을 적용한 뒤 갈라진 커밋과 다시 비교하면, import 정렬처럼 줄의 자리만 바꾸는 수정이 옮긴
59
+ base의 줄도 추가된 줄로 보인다. 그 줄은 PR이 바꾼 줄이 아니다(같은 파일에서 같은 내용이 지워진
60
+ 줄로도 나온다). pr_added는 수정 전 PR이 추가한 줄의 내용이고(`added_texts`), 그 내용의 줄은 몇
61
+ 개까지 PR의 줄로 남긴다.
62
+ """
63
+ added: dict[str, list[tuple[int, str]]] = {}
64
+ removed: dict[str, Counter[str]] = {}
65
+ for path, tag, line_no, text in _content_lines(diff):
66
+ if tag == "+":
67
+ added.setdefault(path, []).append((line_no, text))
68
+ else:
69
+ removed.setdefault(path, Counter())[text] += 1
70
+ result: dict[str, frozenset[int]] = {}
71
+ for path, lines in added.items():
72
+ own = Counter(pr_added.get(path, {}))
73
+ gone = removed.get(path, Counter())
74
+ kept = set()
75
+ for line_no, text in lines:
76
+ if own[text] > 0:
77
+ own[text] -= 1
78
+ kept.add(line_no)
79
+ elif gone[text] > 0:
80
+ gone[text] -= 1
81
+ else:
82
+ kept.add(line_no)
83
+ if kept:
84
+ result[path] = frozenset(kept)
85
+ return result
86
+
87
+
88
+ def _content_lines(diff: str) -> Iterator[tuple[str, str, int, str]]:
89
+ """diff의 추가(`+`)·삭제(`-`) 줄: (경로, 표시, 새 파일의 줄 번호, 내용). 삭제 줄의 줄 번호는 그
90
+ 자리의 새 파일 줄 번호다. 지워진 파일의 줄은 내지 않는다."""
91
+ current: str | None = None
92
+ old_left = new_left = 0
93
+ line_no = 0
94
+ for raw in diff.splitlines():
95
+ if old_left > 0 or new_left > 0:
96
+ tag = raw[:1]
97
+ if tag == "+":
98
+ if current is not None:
99
+ yield current, "+", line_no, raw[1:]
100
+ line_no += 1
101
+ new_left -= 1
102
+ elif tag == "-":
103
+ if current is not None:
104
+ yield current, "-", line_no, raw[1:]
105
+ old_left -= 1
106
+ elif tag == "\\":
107
+ pass # ""
108
+ else: # 문맥 줄 (빈 줄은 공백이 지워진 문맥 줄로 본다)
109
+ line_no += 1
110
+ old_left -= 1
111
+ new_left -= 1
112
+ continue
113
+ if raw.startswith("diff --git "):
114
+ current = None
115
+ elif raw == _DELETED:
116
+ current = None
117
+ elif raw.startswith(_NEW_FILE_HEADER):
118
+ current = _new_path(raw)
119
+ elif match := _HUNK.match(raw):
120
+ _, old_count, new_start, new_count = match.groups()
121
+ old_left = int(old_count) if old_count is not None else 1
122
+ new_left = int(new_count) if new_count is not None else 1
123
+ line_no = int(new_start)
124
+
125
+
126
+ def new_files(diff: str) -> frozenset[str]:
127
+ """PR이 새로 만들거나 이름을 바꿔 생긴 파일(리포 기준 경로). 경로 규칙은 이 파일만 본다:
128
+ 원래 있던 파일의 이름은 PR 작성자의 책임이 아니다.
129
+
130
+ hunk 안의 줄은 건너뛴다 (내용이 헤더처럼 보일 수 있다). 빈 새 파일은 `+++` 줄이 없어
131
+ `diff --git` 줄에서 경로를 읽는다.
132
+ """
133
+ result: set[str] = set()
134
+ git_path: str | None = None
135
+ is_new = False
136
+ old_left = new_left = 0
137
+ for raw in diff.splitlines():
138
+ if old_left > 0 or new_left > 0:
139
+ tag = raw[:1]
140
+ if tag == "+":
141
+ new_left -= 1
142
+ elif tag == "-":
143
+ old_left -= 1
144
+ elif tag != "\\":
145
+ old_left -= 1
146
+ new_left -= 1
147
+ continue
148
+ if raw.startswith("diff --git "):
149
+ git_path, is_new = _same_path(raw[len("diff --git ") :]), False
150
+ elif raw.startswith("new file mode "):
151
+ is_new = True
152
+ if git_path is not None:
153
+ result.add(git_path)
154
+ elif raw.startswith("rename to "):
155
+ result.add(_unquoted(raw[len("rename to ") :]))
156
+ elif raw.startswith(_NEW_FILE_HEADER) and raw != _DELETED:
157
+ path = _new_path(raw)
158
+ if is_new and path is not None:
159
+ result.add(path)
160
+ elif match := _HUNK.match(raw):
161
+ _, old_count, _, new_count = match.groups()
162
+ old_left = int(old_count) if old_count is not None else 1
163
+ new_left = int(new_count) if new_count is not None else 1
164
+ return frozenset(result)
165
+
166
+
167
+ def _same_path(rest: str) -> str | None:
168
+ """`a/<경로> b/<경로>`에서 두 경로가 같으면 그 경로 (새 파일은 같다). 아니면 None."""
169
+ size = (len(rest) - 5) // 2
170
+ path = rest[2 : 2 + size]
171
+ return path if size > 0 and rest == f"a/{path} b/{path}" else None
172
+
173
+
174
+ def _unquoted(raw: str) -> str:
175
+ raw = raw.removesuffix("\t")
176
+ if raw.startswith('"') and raw.endswith('"') and len(raw) >= 2:
177
+ return codecs.escape_decode(raw[1:-1].encode())[0].decode("utf-8", "surrogateescape")
178
+ return raw
179
+
180
+
181
+ def hunk_around(diff: str, file: str, line: int, radius: int) -> str:
182
+ """file의 head 쪽 line을 담은 hunk에서 그 줄 앞뒤 radius줄과 hunk 헤더. 없으면 "".
183
+
184
+ 수정 판단(4.6)이 모델에 넘기는 자료다. 큰 새 파일은 hunk 하나가 파일 전체라 줄 수를 자른다.
185
+ """
186
+ current: str | None = None
187
+ old_left = new_left = 0
188
+ line_no = 0
189
+ header = ""
190
+ hunk: list[tuple[int | None, str]] = []
191
+ for raw in diff.splitlines():
192
+ if old_left > 0 or new_left > 0:
193
+ tag = raw[:1]
194
+ if tag == "-":
195
+ hunk.append((None, raw))
196
+ old_left -= 1
197
+ elif tag == "\\":
198
+ hunk.append((None, raw))
199
+ else:
200
+ hunk.append((line_no, raw))
201
+ line_no += 1
202
+ new_left -= 1
203
+ if tag != "+":
204
+ old_left -= 1
205
+ if old_left <= 0 and new_left <= 0 and current == file:
206
+ at = next((i for i, (n, _) in enumerate(hunk) if n == line), None)
207
+ if at is not None:
208
+ window = hunk[max(0, at - radius) : at + radius + 1]
209
+ return "\n".join([header, *(text for _, text in window)])
210
+ continue
211
+ if raw.startswith("diff --git ") or raw == _DELETED:
212
+ current = None
213
+ elif raw.startswith(_NEW_FILE_HEADER):
214
+ current = _new_path(raw)
215
+ elif match := _HUNK.match(raw):
216
+ _, old_count, new_start, new_count = match.groups()
217
+ old_left = int(old_count) if old_count is not None else 1
218
+ new_left = int(new_count) if new_count is not None else 1
219
+ line_no = int(new_start)
220
+ header, hunk = raw, []
221
+ return ""
222
+
223
+
224
+ @dataclass(frozen=True)
225
+ class ChangeBlock:
226
+ """연속으로 바뀐 줄 한 덩어리 (`-U0`의 hunk 하나와 같다).
227
+
228
+ lines는 이 덩어리를 가리킨다고 보는 diff 뒤쪽의 줄 번호다: 더한 줄, 지우기만 했으면 지운 자리의
229
+ 앞뒤 줄. old_lines는 diff 앞쪽에서 지우거나 바꾼 줄 번호이고, 더하기만 했으면 비어 있다. 수정
230
+ diff(PR head → 고친 파일)에서는 old_lines가 PR head의 줄 번호라 위반의 줄과 맞춰 볼 수 있다.
231
+ """
232
+
233
+ file: str
234
+ lines: frozenset[int]
235
+ old_lines: frozenset[int]
236
+
237
+ @property
238
+ def review_line(self) -> int:
239
+ """이 덩어리에 줄 리뷰 코멘트를 다는 줄. GitHub이 받는 diff 뒤쪽의 줄이다."""
240
+ return min(self.lines)
241
+
242
+
243
+ def change_blocks(diff: str) -> tuple[ChangeBlock, ...]:
244
+ """diff의 바뀐 덩어리들. 문맥 줄이 있는 diff도 문맥 줄에서 덩어리를 나눈다. 지운 파일은 뺀다.
245
+
246
+ 수정의 설명(DESIGN.md 7.5)에 줄을 채우고 확인하는 데 쓴다.
247
+ """
248
+ blocks: list[ChangeBlock] = []
249
+ current: str | None = None
250
+ old_left = new_left = 0
251
+ line_no = old_no = 0
252
+ added: set[int] | None = None # 지금 덩어리에서 더한 줄. 덩어리 밖이면 None
253
+ removed: set[int] = set()
254
+
255
+ def close() -> None:
256
+ nonlocal added, removed
257
+ if added is not None and current is not None:
258
+ lines = added or {n for n in (line_no - 1, line_no) if n >= 1}
259
+ blocks.append(ChangeBlock(current, frozenset(lines), frozenset(removed)))
260
+ added, removed = None, set()
261
+
262
+ for raw in diff.splitlines():
263
+ if old_left > 0 or new_left > 0:
264
+ tag = raw[:1]
265
+ if tag == "+":
266
+ added = set() if added is None else added
267
+ added.add(line_no)
268
+ line_no += 1
269
+ new_left -= 1
270
+ elif tag == "-":
271
+ added = set() if added is None else added
272
+ removed.add(old_no)
273
+ old_no += 1
274
+ old_left -= 1
275
+ elif tag != "\\":
276
+ close()
277
+ line_no += 1
278
+ old_no += 1
279
+ old_left -= 1
280
+ new_left -= 1
281
+ if old_left <= 0 and new_left <= 0:
282
+ close()
283
+ continue
284
+ if raw.startswith("diff --git ") or raw == _DELETED:
285
+ current = None
286
+ elif raw.startswith(_NEW_FILE_HEADER):
287
+ current = _new_path(raw)
288
+ elif match := _HUNK.match(raw):
289
+ old_start, old_count, new_start, new_count = match.groups()
290
+ old_left = int(old_count) if old_count is not None else 1
291
+ new_left = int(new_count) if new_count is not None else 1
292
+ old_no = int(old_start)
293
+ # 지우기만 한 hunk의 시작 줄은 지운 자리의 앞줄이다
294
+ line_no = int(new_start) + (1 if new_left == 0 else 0)
295
+ return tuple(blocks)
296
+
297
+
298
+ def hunk_removing(diff: str, file: str, line_text: str, max_lines: int) -> str:
299
+ """file의 hunk 중 앞뒤 공백을 뺀 내용이 line_text인 줄을 지운(바꾼) 것. 없으면 그 파일의 첫
300
+ hunk, 그 파일이 diff에 없으면 "". hunk 헤더를 포함해 max_lines줄까지 자른다.
301
+
302
+ 과거 기록(6.1)에 넣는 "관련 hunk"다. 위반 줄은 고친 쪽에서 지워진 줄로 보인다.
303
+ """
304
+ wanted = line_text.strip()
305
+ current: str | None = None
306
+ old_left = new_left = 0
307
+ first: list[str] | None = None
308
+ hunk: list[str] = []
309
+ hit = False
310
+ for raw in diff.splitlines():
311
+ if old_left > 0 or new_left > 0:
312
+ hunk.append(raw)
313
+ tag = raw[:1]
314
+ if tag == "-":
315
+ old_left -= 1
316
+ hit = hit or raw[1:].strip() == wanted
317
+ elif tag == "+":
318
+ new_left -= 1
319
+ elif tag != "\\":
320
+ old_left -= 1
321
+ new_left -= 1
322
+ if old_left <= 0 and new_left <= 0 and current == file:
323
+ if hit:
324
+ return "\n".join(hunk[:max_lines])
325
+ first = hunk if first is None else first
326
+ continue
327
+ if raw.startswith("diff --git ") or raw == _DELETED:
328
+ current = None
329
+ elif raw.startswith(_NEW_FILE_HEADER):
330
+ current = _new_path(raw)
331
+ elif match := _HUNK.match(raw):
332
+ _, old_count, _, new_count = match.groups()
333
+ old_left = int(old_count) if old_count is not None else 1
334
+ new_left = int(new_count) if new_count is not None else 1
335
+ hunk, hit = [raw], False
336
+ return "\n".join(first[:max_lines]) if first is not None else ""
337
+
338
+
339
+ def _old_path(header: str) -> str | None:
340
+ """`--- a/<경로>` 헤더의 경로. 새 파일(`/dev/null`)이나 형식이 다르면 None."""
341
+ raw = header[len(_OLD_FILE_HEADER) :].removesuffix("\t")
342
+ if raw.startswith('"') and raw.endswith('"') and len(raw) >= 2:
343
+ raw = codecs.escape_decode(raw[1:-1].encode())[0].decode("utf-8", "surrogateescape")
344
+ return raw.removeprefix("a/") if raw.startswith("a/") else None
345
+
346
+
347
+ def line_after(diff: str, file: str, line: int) -> int | None:
348
+ """diff 앞쪽(고치기 전) file의 line이 뒤쪽(고친 뒤)에서 몇 번째 줄인지. diff가 그 줄을 지우거나
349
+ 바꿨으면, 그 파일을 지우거나 이름을 바꿨거나 바이너리로 바꿨으면 None. diff에 없는 파일의 줄은
350
+ 그대로다.
351
+
352
+ 수정안을 머지한 커밋에 앞 커밋의 위반을 옮겨 적을 때 줄 번호를 맞춘다. 문맥 줄이 몇 줄이든
353
+ hunk 헤더의 줄 수만큼 내용 줄로 읽는다.
354
+ """
355
+ target = False # 지금 읽는 절이 file의 것이다
356
+ git_path: str | None = None
357
+ old_path: str | None = None
358
+ offset = 0 # 지난 hunk들이 더하고 뺀 줄 수
359
+ old_no = new_no = 0
360
+ old_left = new_left = 0
361
+ for raw in diff.splitlines():
362
+ if old_left > 0 or new_left > 0:
363
+ tag = raw[:1]
364
+ if tag == "+":
365
+ new_no += 1
366
+ new_left -= 1
367
+ elif tag == "-":
368
+ if target and old_no == line:
369
+ return None
370
+ old_no += 1
371
+ old_left -= 1
372
+ elif tag != "\\":
373
+ if target and old_no == line:
374
+ return new_no
375
+ old_no += 1
376
+ new_no += 1
377
+ old_left -= 1
378
+ new_left -= 1
379
+ if old_left <= 0 and new_left <= 0:
380
+ offset = new_no - old_no
381
+ continue
382
+ if raw.startswith("diff --git "):
383
+ if target:
384
+ return line + offset
385
+ git_path, old_path = _same_path(raw[len("diff --git ") :]), None
386
+ elif raw.startswith(("rename from ", "deleted file mode ")):
387
+ if git_path == file or _unquoted(raw.split(" ", 2)[-1]) == file:
388
+ return None
389
+ elif raw.startswith(("Binary files ", "GIT binary patch")):
390
+ if git_path == file or target:
391
+ return None
392
+ elif raw.startswith(_OLD_FILE_HEADER):
393
+ old_path = _old_path(raw)
394
+ elif raw.startswith(_NEW_FILE_HEADER):
395
+ if old_path == file:
396
+ if _new_path(raw) != file:
397
+ return None
398
+ target = True
399
+ elif match := _HUNK.match(raw):
400
+ old_start, old_count, new_start, new_count = match.groups()
401
+ old_left = int(old_count) if old_count is not None else 1
402
+ new_left = int(new_count) if new_count is not None else 1
403
+ # 더하기만 한 hunk의 시작 줄은 더한 자리의 앞줄, 지우기만 한 hunk는 뒤쪽이 그렇다
404
+ old_no = int(old_start) + (1 if old_left == 0 else 0)
405
+ new_no = int(new_start) + (1 if new_left == 0 else 0)
406
+ if target and line < old_no:
407
+ return line + offset
408
+ return line + offset if target else line
409
+
410
+
411
+ def touches(changed: ChangedLines, file: str, start: int, end: int) -> bool:
412
+ """file의 start–end 줄 범위가 PR이 바꾼 줄을 하나라도 포함하는지.
413
+
414
+ import 정렬처럼 여러 줄에 걸친 위반은 범위 안의 한 줄만 바뀌어도 PR의 위반으로 본다.
415
+ """
416
+ lines = changed.get(file)
417
+ if not lines:
418
+ return False
419
+ return any(n in lines for n in range(start, max(start, end) + 1))