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,207 @@
|
|
|
1
|
+
"""과거 기록 저장 (docs/DESIGN.md 4.10, 6.5). 무엇을 기록할지는 app/worker/records_pure.py가 정한다.
|
|
2
|
+
|
|
3
|
+
- 수정안 PR이 머지·닫힘: 수정안 PR 상태를 확인하는 곳(`proposal.refresh`)에서 남긴다.
|
|
4
|
+
- 작성자가 자기 커밋으로 고침, 이번 검사의 위반: 새 커밋의 위반 찾기 뒤에 남긴다.
|
|
5
|
+
- 수정이 검증에 실패함: 수정 단계(`fix_model`)가 끝난 뒤에 남긴다.
|
|
6
|
+
|
|
7
|
+
저장 전에 비밀값 검사를 하고 걸리면 그 기록은 저장하지 않는다. 기록 실패는 PR 결과에 영향을 주지
|
|
8
|
+
않는다. 로그만 남기고, 같은 기록은 고유 키(repo, kind, source_id)로 거르므로 다음 기회에 다시 한다.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import logging
|
|
12
|
+
from collections.abc import Callable, Iterable, Mapping, Sequence
|
|
13
|
+
from dataclasses import replace
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Final
|
|
16
|
+
|
|
17
|
+
from sqlalchemy.exc import SQLAlchemyError
|
|
18
|
+
|
|
19
|
+
from app.shared.db_pure import SeenViolation
|
|
20
|
+
from app.shared.job_pure import PRJob
|
|
21
|
+
from app.worker import records_pure, repo
|
|
22
|
+
from app.worker.doc_rules_pure import Found, RuleChecked
|
|
23
|
+
from app.worker.fix.feedback_fix_pure import FEEDBACK_BUNDLE
|
|
24
|
+
from app.worker.fix.fix_pure import MechanicalFix
|
|
25
|
+
from app.worker.fix.model_fix_pure import ModelFix
|
|
26
|
+
from app.worker.fix.proposal_pure import find_secret_in_text
|
|
27
|
+
from app.worker.repo import GitError
|
|
28
|
+
from app.worker.sandbox.safe_read import read_regular_file
|
|
29
|
+
from app.worker.state import Store
|
|
30
|
+
from app.worker.tools_pure import CONFIG_RULE_ID, RUFF_CODE
|
|
31
|
+
from app.worker.violation_pure import Violation
|
|
32
|
+
|
|
33
|
+
log = logging.getLogger(__name__)
|
|
34
|
+
|
|
35
|
+
MAX_FILE_BYTES: Final = 5 * 1024 * 1024
|
|
36
|
+
|
|
37
|
+
# 기록을 만들다 날 수 있는 오류. 그 밖의 예외는 파이프라인 버그라 그대로 올린다
|
|
38
|
+
_RECORD_ERRORS: Final = (SQLAlchemyError, GitError, OSError, ValueError)
|
|
39
|
+
# 실패로 기록하는 수정 결과. 호출 상한, 실행하지 않음, 고칠 것이 없음은 실패가 아니다
|
|
40
|
+
_FAILED_STATUSES: Final = frozenset({
|
|
41
|
+
"failed", "dropped", "new_violations", "out_of_scope", "secret", "tests_changed",
|
|
42
|
+
"unchecked", "too_big",
|
|
43
|
+
}) # fmt: skip
|
|
44
|
+
# 머지·닫힘을 기록하는 수정안 상태
|
|
45
|
+
_FINISHED_STATES: Final[Mapping[str, str]] = {"merged": "adopted", "rejected": "rejected"}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def save(store: Store, new: Iterable[records_pure.NewRecord], secrets: Sequence[str]) -> int:
|
|
49
|
+
"""비밀값 검사를 거친 기록만 저장한다. 새로 저장한 수."""
|
|
50
|
+
saved = 0
|
|
51
|
+
for record in new:
|
|
52
|
+
kind = find_secret_in_text(records_pure.text_of(record), secrets)
|
|
53
|
+
if kind is not None:
|
|
54
|
+
log.warning(
|
|
55
|
+
"기록을 저장하지 않음 %s %s: 비밀값 (%s)", record.repo, record.source_id, kind
|
|
56
|
+
)
|
|
57
|
+
continue
|
|
58
|
+
saved += store.add_record(record)
|
|
59
|
+
return saved
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def after_proposals(store: Store, repo_name: str, pr_number: int, secrets: Sequence[str]) -> None:
|
|
63
|
+
"""이 PR에서 머지됐거나 사람이 닫은 문서 규칙 수정안마다 채택·거절 기록을 남긴다.
|
|
64
|
+
|
|
65
|
+
이미 남긴 기록은 고유 키로 걸러지므로, 앞에서 실패했던 것도 여기서 다시 남는다."""
|
|
66
|
+
try:
|
|
67
|
+
for p in store.proposals(repo_name, pr_number):
|
|
68
|
+
kind = _FINISHED_STATES.get(p.state)
|
|
69
|
+
if p.skill == FEEDBACK_BUNDLE: # 코멘트 수정안은 문서 규칙의 기록을 만들지 않는다
|
|
70
|
+
continue
|
|
71
|
+
attempt = store.fix_attempt(p.attempt_id) if p.attempt_id is not None else None
|
|
72
|
+
if kind is None or attempt is None or attempt.patch is None:
|
|
73
|
+
continue
|
|
74
|
+
new = records_pure.fix_pr_records(
|
|
75
|
+
kind, repo=repo_name, pr_number=pr_number, fix_pr_number=p.number,
|
|
76
|
+
commit_sha=p.merge_commit if kind == "adopted" else p.head_sha,
|
|
77
|
+
targets=records_pure.targets_from_json(attempt.targets_json), patch=attempt.patch,
|
|
78
|
+
) # fmt: skip
|
|
79
|
+
save(store, new, secrets)
|
|
80
|
+
except _RECORD_ERRORS:
|
|
81
|
+
log.exception("수정안의 기록을 남기지 못함 %s#%s", repo_name, pr_number)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def after_failed_fix(
|
|
85
|
+
store: Store,
|
|
86
|
+
job: PRJob,
|
|
87
|
+
fix: ModelFix | MechanicalFix,
|
|
88
|
+
notes: Sequence[records_pure.Target],
|
|
89
|
+
worktree: Path,
|
|
90
|
+
secrets: Sequence[str],
|
|
91
|
+
) -> None:
|
|
92
|
+
"""검증에 실패한 수정(모델: 회차 소진·재시도 없이 버림, 기계적 수정: 검증의 어느 단계에서
|
|
93
|
+
떨어짐)의 실패 기록 (4.10). diff는 마지막 회차의 것이다."""
|
|
94
|
+
if fix.status not in _FAILED_STATUSES or fix.attempt_id is None:
|
|
95
|
+
return
|
|
96
|
+
try:
|
|
97
|
+
new = records_pure.failure_records(
|
|
98
|
+
repo=job.repo, pr_number=job.pr_number, head_sha=job.head_sha,
|
|
99
|
+
attempt_id=fix.attempt_id, targets=notes, patch=repo.head_diff(worktree),
|
|
100
|
+
detail=fix.detail,
|
|
101
|
+
) # fmt: skip
|
|
102
|
+
save(store, new, secrets)
|
|
103
|
+
except _RECORD_ERRORS:
|
|
104
|
+
log.exception("수정 실패 기록을 남기지 못함 %s#%s", job.repo, job.pr_number)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def mark_rejected(store: Store, job: PRJob, found: Found) -> Found:
|
|
108
|
+
"""이 PR에서 사람이 닫은 수정안이 고친 것과 같은 줄의 위반에 그 PR 번호를 적는다. 수정 판단의
|
|
109
|
+
표 첫 줄이 이것으로 `skip`(이전에 거절됨)을 정한다 (4.6)."""
|
|
110
|
+
if not found.violations:
|
|
111
|
+
return found
|
|
112
|
+
rejected = records_pure.rejected_lines(store.records(job.repo, job.pr_number))
|
|
113
|
+
if not rejected:
|
|
114
|
+
return found
|
|
115
|
+
return replace(found, violations=records_pure.mark_rejected(found.violations, rejected))
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def after_detect(
|
|
119
|
+
store: Store,
|
|
120
|
+
job: PRJob,
|
|
121
|
+
found: Found,
|
|
122
|
+
worktree: Path,
|
|
123
|
+
secrets: Sequence[str],
|
|
124
|
+
*,
|
|
125
|
+
merged_fix: bool,
|
|
126
|
+
) -> None:
|
|
127
|
+
"""이전 커밋의 위반 중 작성자가 고친 것을 채택 기록으로 남기고, 이번 커밋의 위반을 기록한다.
|
|
128
|
+
|
|
129
|
+
merged_fix는 이 커밋이 파이프라인의 수정안을 머지한 결과인지다. 그때 사라진 위반은 작성자가
|
|
130
|
+
아니라 수정안이 고친 것이다(그 채택 기록은 수정안 쪽에서 남는다).
|
|
131
|
+
"""
|
|
132
|
+
try:
|
|
133
|
+
lines_of = _reader(worktree)
|
|
134
|
+
if not merged_fix:
|
|
135
|
+
previous = store.previous_violations(job.repo, job.pr_number, job.head_sha)
|
|
136
|
+
checked = set(o.rule.id for o in found.outcomes if isinstance(o, RuleChecked))
|
|
137
|
+
if CONFIG_RULE_ID in checked: # 도구 설정 규칙의 위반은 ruff 코드가 규칙 id다 (4.3)
|
|
138
|
+
checked |= {p.rule_id for p in previous if RUFF_CODE.match(p.rule_id)}
|
|
139
|
+
fixed = records_pure.author_fixed(
|
|
140
|
+
previous, frozenset(v.id for v in found.violations), frozenset(checked), lines_of
|
|
141
|
+
)
|
|
142
|
+
if fixed:
|
|
143
|
+
config = next((o.rule for o in found.outcomes if o.rule.id == CONFIG_RULE_ID), None)
|
|
144
|
+
texts = {o.rule.id: o.rule.text for o in found.outcomes}
|
|
145
|
+
if config is not None:
|
|
146
|
+
texts |= {v.rule_id: config.text for v in fixed if RUFF_CODE.match(v.rule_id)}
|
|
147
|
+
new = records_pure.author_records(
|
|
148
|
+
fixed, rule_texts=texts, head_sha=job.head_sha,
|
|
149
|
+
diff_of=_commit_diff(worktree, fixed[0].head_sha, job.head_sha),
|
|
150
|
+
) # fmt: skip
|
|
151
|
+
save(store, new, secrets)
|
|
152
|
+
rows = [
|
|
153
|
+
SeenViolation(
|
|
154
|
+
repo=job.repo,
|
|
155
|
+
pr_number=job.pr_number,
|
|
156
|
+
head_sha=job.head_sha,
|
|
157
|
+
violation_id=v.id,
|
|
158
|
+
rule_id=v.rule_id,
|
|
159
|
+
file=v.file,
|
|
160
|
+
line=v.line,
|
|
161
|
+
line_text=v.line_text,
|
|
162
|
+
message=v.message,
|
|
163
|
+
unit=v.unit,
|
|
164
|
+
context=records_pure.context_around(lines_of(v.file) or [], v.line),
|
|
165
|
+
) # fmt: skip
|
|
166
|
+
for v in found.violations
|
|
167
|
+
]
|
|
168
|
+
store.replace_violations(job.repo, job.pr_number, job.head_sha, rows)
|
|
169
|
+
except _RECORD_ERRORS:
|
|
170
|
+
log.exception("위반 기록을 남기지 못함 %s#%s", job.repo, job.pr_number)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def context_of(worktree: Path) -> Callable[[Violation], str]:
|
|
174
|
+
"""위반 줄과 앞뒤 5줄 (6.1). 검색의 질의 글(6.6의 4번)이 저장한 기록과 같은 틀이 되게 기록을
|
|
175
|
+
만들 때와 같은 방법으로 읽는다. 파일을 읽지 못하면 ""."""
|
|
176
|
+
lines_of = _reader(worktree)
|
|
177
|
+
|
|
178
|
+
def context(v: Violation) -> str:
|
|
179
|
+
return records_pure.context_around(lines_of(v.file) or [], v.line)
|
|
180
|
+
|
|
181
|
+
return context
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _reader(worktree: Path) -> Callable[[str], list[str] | None]:
|
|
185
|
+
cache: dict[str, list[str] | None] = {}
|
|
186
|
+
|
|
187
|
+
def lines_of(rel: str) -> list[str] | None:
|
|
188
|
+
if rel not in cache:
|
|
189
|
+
path = repo.worktree_file(worktree, rel)
|
|
190
|
+
data = read_regular_file(path, max_bytes=MAX_FILE_BYTES) if path is not None else None
|
|
191
|
+
cache[rel] = data.decode("utf-8", errors="replace").split("\n") if data else None
|
|
192
|
+
return cache[rel]
|
|
193
|
+
|
|
194
|
+
return lines_of
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _commit_diff(worktree: Path, old: str, new: str) -> Callable[[str], str]:
|
|
198
|
+
"""old와 new 커밋 사이의 파일 하나의 diff. old가 bare 저장소에 없으면 ""."""
|
|
199
|
+
|
|
200
|
+
def diff_of(rel: str) -> str:
|
|
201
|
+
try:
|
|
202
|
+
return repo.commit_diff(worktree, old, new, rel)
|
|
203
|
+
except GitError as e:
|
|
204
|
+
log.info("이전 커밋과의 diff를 읽지 못함 (%s): %s", rel, e)
|
|
205
|
+
return ""
|
|
206
|
+
|
|
207
|
+
return diff_of
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
"""팀의 과거 기록 (docs/DESIGN.md 4.10, 6.1, 7.6). 기록 만들기와 읽은 기록으로 판단하기만 한다.
|
|
2
|
+
|
|
3
|
+
기록은 세 가지다: 채택(수정안 PR 머지, 작성자가 자기 커밋으로 고침), 거절(사람이 수정안 PR을
|
|
4
|
+
닫음), 실패(수정이 검증에 실패함). 검색과 임베딩은 5단계다(D5). 그 전에 기록을 쓰는 곳은 정확히
|
|
5
|
+
같은 줄의 거절을 찾는 것(4.6 표의 첫 줄, 6.4의 SQL)뿐이다.
|
|
6
|
+
|
|
7
|
+
기록의 글은 저장소에서 온 것이라 믿지 않는다. 저장 전에 비밀값 검사를 하고(`text_of`), 보이거나
|
|
8
|
+
모델에 넘길 때는 자료로만 다룬다.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
from collections.abc import Callable, Iterable, Mapping, Sequence
|
|
13
|
+
from dataclasses import asdict, dataclass, replace
|
|
14
|
+
from typing import Final, Literal
|
|
15
|
+
|
|
16
|
+
from app.shared.db_pure import Record, SeenViolation
|
|
17
|
+
from app.worker.diff_pure import hunk_removing
|
|
18
|
+
from app.worker.violation_pure import Violation
|
|
19
|
+
|
|
20
|
+
RecordKind = Literal["adopted", "rejected", "failed", "checker"]
|
|
21
|
+
RecordOrigin = Literal["fix_pr", "author_commit", "verification", "ruleset"]
|
|
22
|
+
MAX_CHECKER_CHARS: Final = 8000 # 검사기 기록에 넣는 본문과 예시의 글자 수
|
|
23
|
+
CONTEXT_RADIUS: Final = 5 # 위반 줄 앞뒤 줄 수 (6.1)
|
|
24
|
+
MAX_DIFF_LINES: Final = 60 # 기록에 넣는 관련 hunk의 줄 수 (6.1)
|
|
25
|
+
MAX_DETAIL_CHARS: Final = 2000
|
|
26
|
+
|
|
27
|
+
# (파일, 규칙 id, 앞뒤 공백을 뺀 줄 내용) → 그 줄을 고친 수정안 PR 번호
|
|
28
|
+
RejectedLines = Mapping[tuple[str, str, str], int]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class Target:
|
|
33
|
+
"""수정 시도가 고친 위반 하나와 그 자료. `fix_attempts.targets_json`에 들어가고, 그 수정안이
|
|
34
|
+
머지·닫히거나 검증에 실패하면 이것으로 기록을 만든다."""
|
|
35
|
+
|
|
36
|
+
violation_id: str
|
|
37
|
+
rule_id: str
|
|
38
|
+
rule_text: str
|
|
39
|
+
file: str
|
|
40
|
+
line: int
|
|
41
|
+
line_text: str
|
|
42
|
+
context: str # 고치기 전 위반 줄과 앞뒤 5줄
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True)
|
|
46
|
+
class NewRecord:
|
|
47
|
+
"""저장할 기록 하나. id와 시각은 저장할 때 붙는다."""
|
|
48
|
+
|
|
49
|
+
repo: str
|
|
50
|
+
kind: RecordKind
|
|
51
|
+
origin: RecordOrigin
|
|
52
|
+
source_id: str
|
|
53
|
+
rule_id: str
|
|
54
|
+
rule_text: str
|
|
55
|
+
file: str
|
|
56
|
+
line_text: str
|
|
57
|
+
context: str
|
|
58
|
+
diff: str
|
|
59
|
+
detail: str = ""
|
|
60
|
+
pr_number: int | None = None
|
|
61
|
+
fix_pr_number: int | None = None
|
|
62
|
+
commit_sha: str | None = None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def context_around(lines: Sequence[str], line: int, radius: int = CONTEXT_RADIUS) -> str:
|
|
66
|
+
"""line(1부터)과 앞뒤 radius줄. 없는 줄이면 ""."""
|
|
67
|
+
if not 0 < line <= len(lines):
|
|
68
|
+
return ""
|
|
69
|
+
return "\n".join(lines[max(0, line - 1 - radius) : line + radius])
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def targets_to_json(targets: Sequence[Target]) -> str:
|
|
73
|
+
return json.dumps([asdict(t) for t in targets], ensure_ascii=False)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def targets_from_json(text: str) -> tuple[Target, ...]:
|
|
77
|
+
return tuple(Target(**item) for item in json.loads(text))
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _from_target(
|
|
81
|
+
t: Target, kind: RecordKind, origin: RecordOrigin, source_id: str, patch: str, **more
|
|
82
|
+
) -> NewRecord:
|
|
83
|
+
return NewRecord(
|
|
84
|
+
kind=kind, origin=origin, source_id=source_id, rule_id=t.rule_id, rule_text=t.rule_text,
|
|
85
|
+
file=t.file, line_text=t.line_text, context=t.context,
|
|
86
|
+
diff=hunk_removing(patch, t.file, t.line_text, MAX_DIFF_LINES), **more,
|
|
87
|
+
) # fmt: skip
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def fix_pr_records(
|
|
91
|
+
kind: Literal["adopted", "rejected"],
|
|
92
|
+
*,
|
|
93
|
+
repo: str,
|
|
94
|
+
pr_number: int,
|
|
95
|
+
fix_pr_number: int,
|
|
96
|
+
commit_sha: str | None,
|
|
97
|
+
targets: Sequence[Target],
|
|
98
|
+
patch: str,
|
|
99
|
+
) -> list[NewRecord]:
|
|
100
|
+
"""수정안 PR이 머지(adopted)되거나 사람이 닫았을(rejected) 때, 그 수정안이 고친 위반마다
|
|
101
|
+
하나."""
|
|
102
|
+
return [
|
|
103
|
+
_from_target(
|
|
104
|
+
t,
|
|
105
|
+
kind,
|
|
106
|
+
"fix_pr",
|
|
107
|
+
f"fix_pr:{fix_pr_number}:{t.violation_id}",
|
|
108
|
+
patch,
|
|
109
|
+
repo=repo,
|
|
110
|
+
pr_number=pr_number,
|
|
111
|
+
fix_pr_number=fix_pr_number,
|
|
112
|
+
commit_sha=commit_sha,
|
|
113
|
+
) # fmt: skip
|
|
114
|
+
for t in targets
|
|
115
|
+
]
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def failure_records(
|
|
119
|
+
*,
|
|
120
|
+
repo: str,
|
|
121
|
+
pr_number: int,
|
|
122
|
+
head_sha: str,
|
|
123
|
+
attempt_id: int,
|
|
124
|
+
targets: Sequence[Target],
|
|
125
|
+
patch: str,
|
|
126
|
+
detail: str,
|
|
127
|
+
) -> list[NewRecord]:
|
|
128
|
+
"""수정이 검증에 실패했을 때 대상 위반마다 하나. patch는 마지막 회차가 남긴 diff다."""
|
|
129
|
+
return [
|
|
130
|
+
_from_target(
|
|
131
|
+
t,
|
|
132
|
+
"failed",
|
|
133
|
+
"verification",
|
|
134
|
+
f"attempt:{attempt_id}:{t.violation_id}",
|
|
135
|
+
patch,
|
|
136
|
+
repo=repo,
|
|
137
|
+
pr_number=pr_number,
|
|
138
|
+
commit_sha=head_sha,
|
|
139
|
+
detail=detail[:MAX_DETAIL_CHARS],
|
|
140
|
+
) # fmt: skip
|
|
141
|
+
for t in targets
|
|
142
|
+
]
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def author_fixed(
|
|
146
|
+
previous: Iterable[SeenViolation],
|
|
147
|
+
current_ids: frozenset[str],
|
|
148
|
+
checked_rules: frozenset[str],
|
|
149
|
+
lines_of: Callable[[str], Sequence[str] | None],
|
|
150
|
+
) -> list[SeenViolation]:
|
|
151
|
+
"""이전 커밋의 위반 중 작성자가 자기 커밋으로 고친 것 (4.10): 이번 검사에 없고, 그 규칙을
|
|
152
|
+
이번에도 검사기로 확인했고, 그 파일이 있고, 그 줄 내용이 파일에서 사라졌다.
|
|
153
|
+
|
|
154
|
+
규칙이 바뀌었거나 검사하지 못했으면 위반이 없어져도 고친 것으로 보지 않는다. 파일을 지운 것도
|
|
155
|
+
고친 것으로 보지 않는다. 파일 단위 위반은 줄 내용이 없어 보지 않는다.
|
|
156
|
+
"""
|
|
157
|
+
out = []
|
|
158
|
+
for v in previous:
|
|
159
|
+
if v.unit != "line" or not v.line_text or v.violation_id in current_ids:
|
|
160
|
+
continue
|
|
161
|
+
if v.rule_id not in checked_rules:
|
|
162
|
+
continue
|
|
163
|
+
lines = lines_of(v.file)
|
|
164
|
+
if lines is None or v.line_text in {line.strip() for line in lines}:
|
|
165
|
+
continue
|
|
166
|
+
out.append(v)
|
|
167
|
+
return out
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def author_records(
|
|
171
|
+
fixed: Iterable[SeenViolation],
|
|
172
|
+
*,
|
|
173
|
+
rule_texts: Mapping[str, str],
|
|
174
|
+
head_sha: str,
|
|
175
|
+
diff_of: Callable[[str], str],
|
|
176
|
+
) -> list[NewRecord]:
|
|
177
|
+
"""작성자가 고친 위반의 채택 기록. diff_of(파일)은 이전 커밋과 이번 커밋 사이의 그 파일
|
|
178
|
+
diff다. 원천 id는 그 위반을 본 커밋과 위반 id다. 그 뒤의 커밋이 같은 이전 기록과 다시 비교해도
|
|
179
|
+
같은 고침을 두 번 남기지 않는다."""
|
|
180
|
+
return [
|
|
181
|
+
NewRecord(
|
|
182
|
+
repo=v.repo, kind="adopted", origin="author_commit",
|
|
183
|
+
source_id=f"seen:{v.head_sha}:{v.violation_id}", rule_id=v.rule_id,
|
|
184
|
+
rule_text=rule_texts.get(v.rule_id, ""), file=v.file, line_text=v.line_text or "",
|
|
185
|
+
context=v.context, diff=hunk_removing(diff_of(v.file), v.file, v.line_text or "",
|
|
186
|
+
MAX_DIFF_LINES),
|
|
187
|
+
pr_number=v.pr_number, commit_sha=head_sha,
|
|
188
|
+
)
|
|
189
|
+
for v in fixed
|
|
190
|
+
] # fmt: skip
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def checker_record(
|
|
194
|
+
*, repo: str, rule_id: str, rule_text: str, checker_id: str, kind: str, body: str,
|
|
195
|
+
examples: Sequence[tuple[str, Sequence[int]]],
|
|
196
|
+
) -> NewRecord: # fmt: skip
|
|
197
|
+
"""예시 확인을 통과해 채택한 검사기의 기록 (4.10 표의 마지막 줄, 6.1). 검색 키는 규칙 원문이고
|
|
198
|
+
꺼내 쓰는 것은 검사기 본문과 예시다. 원천 id는 규칙과 검사기 본문의 해시라 같은 검사기를 두 번
|
|
199
|
+
남기지 않는다."""
|
|
200
|
+
shown = [f"# 형식: {kind}", body.rstrip()]
|
|
201
|
+
for code, lines in examples:
|
|
202
|
+
label = f"위반 예시, 어긴 줄 {list(lines)}" if lines else "정상 예시"
|
|
203
|
+
shown += ["", f"# {label}", code.rstrip()]
|
|
204
|
+
return NewRecord(
|
|
205
|
+
repo=repo, kind="checker", origin="ruleset", source_id=f"checker:{rule_id}:{checker_id}",
|
|
206
|
+
rule_id=rule_id, rule_text=rule_text, file="", line_text="", context="",
|
|
207
|
+
diff="\n".join(shown)[:MAX_CHECKER_CHARS],
|
|
208
|
+
) # fmt: skip
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def text_of(record: NewRecord) -> str:
|
|
212
|
+
"""비밀값 검사(6.5, 4.8의 3번과 같은 검사)를 할 글 전체."""
|
|
213
|
+
return "\n".join(
|
|
214
|
+
(record.rule_text, record.file, record.line_text, record.context, record.diff,
|
|
215
|
+
record.detail)
|
|
216
|
+
) # fmt: skip
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def rejected_lines(records: Iterable[Record]) -> dict[tuple[str, str, str], int]:
|
|
220
|
+
"""사람이 닫은 수정안 PR의 거절 기록 → 같은 줄을 판단할 표 (4.6 표의 첫 줄). 같은 줄이 여러 번
|
|
221
|
+
거절됐으면 나중 기록의 PR 번호를 쓴다."""
|
|
222
|
+
out = {}
|
|
223
|
+
for r in sorted(records, key=lambda r: r.id or 0):
|
|
224
|
+
if r.kind == "rejected" and r.origin == "fix_pr" and r.fix_pr_number is not None:
|
|
225
|
+
out[(r.file, r.rule_id, r.line_text.strip())] = r.fix_pr_number
|
|
226
|
+
return out
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def mark_rejected(
|
|
230
|
+
violations: Iterable[Violation], rejected: RejectedLines
|
|
231
|
+
) -> tuple[Violation, ...]:
|
|
232
|
+
"""거절된 수정안이 고친 것과 같은 (파일, 규칙, 줄 내용)의 위반에 그 PR 번호를 적는다. 줄을
|
|
233
|
+
고치면 내용이 달라져 다시 대상이 된다. 줄 내용이 없거나 빈 위반은 표시하지 않는다."""
|
|
234
|
+
out = []
|
|
235
|
+
for v in violations:
|
|
236
|
+
text = (v.line_text or "").strip()
|
|
237
|
+
number = rejected.get((v.file, v.rule_id, text)) if text else None
|
|
238
|
+
out.append(replace(v, rejected_in=number) if number is not None else v)
|
|
239
|
+
return tuple(out)
|