pr-proof 0.0.0-stage → 0.1.1-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 +172 -0
  16. package/app/setup/__init__.py +4 -0
  17. package/app/setup/cli.py +90 -0
  18. package/app/setup/configure.py +735 -0
  19. package/app/setup/files.py +104 -0
  20. package/app/setup/github_setup.py +153 -0
  21. package/app/setup/install_hints.json +32 -0
  22. package/app/setup/setup_pure.py +344 -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,104 @@
1
+ """설정 폴더(`~/.config/pipeline`, `PIPELINE_CONFIG_DIR`)에 configure가 두는 파일과 실행 환경 폴더.
2
+
3
+ | 파일 | 내용 | 권한 |
4
+ | --- | --- | --- |
5
+ | `config.yaml` | 처리할 repo 목록과 설정 (서버가 읽는다) | |
6
+ | `webhook_secret` | 웹훅 비밀값 | 600 |
7
+ | `github_token` | 토큰 방식의 GitHub 토큰 (`app/shared/github_auth.py`) | 600 |
8
+ | `webhook_url` | 웹훅 받는 주소. smee 주소면 start가 smee-client를 띄운다 | 600 |
9
+ | `pr-proof.env` | `npx pr-proof start`의 실행 설정 (`API_PORT`). 비밀값은 넣지 않는다 | |
10
+
11
+ 실행 환경 폴더(`PR_PROOF_HOME`, 기본 `~/.cache/pipeline/runtime`)에는 start가 만드는 Procfile과,
12
+ npm 패키지로 깔았을 때의 venv가 있다(bin/pr-proof.js와 같은 규칙).
13
+ """
14
+
15
+ import os
16
+ import tempfile
17
+ from pathlib import Path
18
+ from typing import Final
19
+
20
+ from app.shared import config
21
+
22
+ PACKAGE_ROOT: Final = Path(__file__).resolve().parents[2]
23
+ CONFIG_FILE: Final = "config.yaml"
24
+ WEBHOOK_URL_FILE: Final = "webhook_url"
25
+ RUN_ENV_FILE: Final = "pr-proof.env"
26
+ PORT_KEY: Final = "API_PORT"
27
+ DEFAULT_PORT: Final = 8765
28
+ SMEE_PREFIX: Final = "https://smee.io/"
29
+ RUNTIME_HOME_ENV: Final = "PR_PROOF_HOME"
30
+
31
+
32
+ def config_dir() -> Path:
33
+ return config.config_dir()
34
+
35
+
36
+ def runtime_home(environ: dict[str, str] | None = None) -> Path:
37
+ source = os.environ if environ is None else environ
38
+ default = Path.home() / ".cache" / "pipeline" / "runtime"
39
+ return Path(source.get(RUNTIME_HOME_ENV) or default).expanduser()
40
+
41
+
42
+ def is_smee(url: str) -> bool:
43
+ return url.startswith(SMEE_PREFIX)
44
+
45
+
46
+ def write_private(path: Path, text: str, *, replace: bool = False) -> bool:
47
+ """600 파일로 쓴다. 이미 있으면 replace일 때만 바꾼다. 썼으면 참.
48
+
49
+ 임시 파일을 600으로 만들어 쓴 뒤 이름을 바꾼다(넓은 권한으로 잠깐이라도 보이지 않게).
50
+ """
51
+ if path.exists() and not replace:
52
+ return False
53
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
54
+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.")
55
+ try:
56
+ os.fchmod(fd, 0o600)
57
+ with os.fdopen(fd, "w") as f:
58
+ f.write(text.strip() + "\n")
59
+ os.replace(tmp, path)
60
+ except BaseException:
61
+ Path(tmp).unlink(missing_ok=True)
62
+ raise
63
+ return True
64
+
65
+
66
+ def read_private(name: str, directory: Path | None = None) -> str | None:
67
+ """설정 폴더의 600 파일. 없으면 None. 권한이 넓으면 `config.ConfigError`."""
68
+ if not ((directory or config_dir()) / name).exists():
69
+ return None
70
+ return config.read_secret(name, directory)
71
+
72
+
73
+ def saved_port(directory: Path | None = None) -> int | None:
74
+ """`pr-proof.env`에 적어 둔 API_PORT. 파일이 없거나 값이 없으면 None."""
75
+ path = (directory or config_dir()) / RUN_ENV_FILE
76
+ try:
77
+ lines = path.read_text().splitlines()
78
+ except OSError:
79
+ return None
80
+ for line in lines:
81
+ key, _, value = line.partition("=")
82
+ if key.strip() == PORT_KEY and value.strip().isdigit():
83
+ return int(value.strip())
84
+ return None
85
+
86
+
87
+ def read_port(directory: Path | None = None) -> int:
88
+ """`pr-proof.env`의 API_PORT. 없거나 읽지 못하면 기본값."""
89
+ return saved_port(directory) or DEFAULT_PORT
90
+
91
+
92
+ def in_clone() -> bool:
93
+ """저장소를 clone한 폴더에서 도는지(`npx . <명령>`). 아니면 npm으로 받은 패키지다
94
+ (`npx pr-proof <명령>`). 입구(bin/pr-proof.js)의 venv 위치와 같은 기준이다."""
95
+ return (PACKAGE_ROOT / ".git").exists()
96
+
97
+
98
+ def write_port(port: int, directory: Path | None = None) -> None:
99
+ path = (directory or config_dir()) / RUN_ENV_FILE
100
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
101
+ path.write_text(
102
+ "# npx pr-proof start가 honcho에 넘기는 실행 설정. 비밀값은 넣지 않는다.\n"
103
+ f"{PORT_KEY}={port}\n"
104
+ )
@@ -0,0 +1,153 @@
1
+ """configure·add·rm·list가 부르는 GitHub (gh CLI)와 smee.io.
2
+
3
+ GitHub 호출은 받는 runner(`Runner`)로 한다. 테스트는 runner를 바꿔 끼운다. 실제 runner는 서버와 같이
4
+ 최소 환경으로 gh를 부르고, 토큰은 gh에만 넘긴다(`app/shared/github_auth.py`). configure가 토큰을
5
+ 파일에 쓰기 전에 확인할 때는 그 토큰을 직접 받는다.
6
+ """
7
+
8
+ import json
9
+ import os
10
+ import subprocess
11
+ from collections.abc import Callable, Mapping
12
+ from typing import Final
13
+
14
+ from app.setup.setup_pure import Hook
15
+ from app.shared import config, github_auth
16
+
17
+ GH_TIMEOUT: Final = 60
18
+ _ENV_PASSTHROUGH: Final = ("PATH", "HOME", "GH_CONFIG_DIR")
19
+ # 권한이 없거나 저장소가 보이지 않을 때 gh가 내는 것
20
+ _DENIED: Final = ("HTTP 403", "HTTP 404", "Resource not accessible", "Must have admin rights")
21
+ SMEE_HOST: Final = "smee.io"
22
+ TOKEN_INPUT_ENV: Final = "PR_PROOF_GITHUB_TOKEN"
23
+
24
+ Runner = Callable[[list[str], str | None], str]
25
+
26
+
27
+ class SetupGitHubError(RuntimeError):
28
+ """gh 호출 실패."""
29
+
30
+
31
+ class NoPermission(SetupGitHubError):
32
+ """권한이 없거나 저장소가 보이지 않는다 (403, 404)."""
33
+
34
+
35
+ def make_runner(token: str | None = None) -> Runner:
36
+ """gh를 부르는 runner. token을 주면 그 토큰으로, 아니면 저장한 인증(토큰 파일 또는 gh
37
+ 로그인)으로."""
38
+
39
+ def run(args: list[str], stdin: str | None = None) -> str:
40
+ try:
41
+ env = github_auth.gh_env(_ENV_PASSTHROUGH)
42
+ except config.ConfigError as e:
43
+ raise SetupGitHubError(f"GitHub 토큰을 읽지 못함: {e}") from e
44
+ if token is not None:
45
+ env[github_auth.TOKEN_ENV] = token
46
+ try:
47
+ proc = subprocess.run(
48
+ ["gh", *args], input=stdin, capture_output=True, text=True, env=env,
49
+ timeout=GH_TIMEOUT, check=False,
50
+ ) # fmt: skip
51
+ except (OSError, subprocess.TimeoutExpired) as e:
52
+ raise SetupGitHubError(f"gh 실행 실패: {e}") from e
53
+ if proc.returncode != 0:
54
+ detail = github_auth.redact(proc.stderr.strip(), env)[-500:]
55
+ error = NoPermission if any(d in detail for d in _DENIED) else SetupGitHubError
56
+ raise error(f"gh {' '.join(args[:3])} 실패: {detail}")
57
+ return proc.stdout
58
+
59
+ return run
60
+
61
+
62
+ def auth_ok(run: Runner, token_mode: bool) -> bool:
63
+ """고른 인증이 되는지. 토큰 방식은 그 토큰 계정만 본다."""
64
+ try:
65
+ run(["auth", "status", *(["--active"] if token_mode else [])], None)
66
+ except SetupGitHubError:
67
+ return False
68
+ return True
69
+
70
+
71
+ def login(run: Runner) -> str:
72
+ return run(["api", "user", "--jq", ".login"], None).strip()
73
+
74
+
75
+ def repo_access(run: Runner, repo: str) -> tuple[bool, bool, str]:
76
+ """(읽기, 쓰기, GitHub이 적는 정식 이름). 저장소가 보이지 않으면 NoPermission.
77
+
78
+ 정식 이름(`full_name`)은 대소문자가 사용자가 적은 것과 다를 수 있다. GitHub은 웹훅 소식에 정식
79
+ 이름을 적어 보내므로 허용 목록에는 이 이름을 넣는다.
80
+
81
+ GitHub이 주는 것은 계정의 저장소 권한(`permissions.push`)이다. fine-grained 토큰에서 그 토큰에
82
+ 준 권한이 모자란지는 실제로 쓰기 전에는 알 수 없다(README의 권한 목록을 본다).
83
+ """
84
+ jq = "[.permissions.pull, .permissions.push, .full_name] | @tsv"
85
+ out = run(["api", f"repos/{repo}", "--jq", jq], None)
86
+ pull, push, name = [*out.strip().split("\t"), "", "", ""][:3]
87
+ # 이름을 바꾼 저장소는 옛 이름으로 물어도 새 이름이 온다. 그 이름이 웹훅 소식에 적힌다
88
+ return pull == "true", push == "true", name.strip() or repo
89
+
90
+
91
+ def list_hooks(run: Runner, repo: str) -> list[Hook]:
92
+ jq = (
93
+ '.[] | {id, active, events, url: (.config.url // ""), '
94
+ 'content_type: (.config.content_type // "")} | @json'
95
+ )
96
+ out = run(["api", "--paginate", f"repos/{repo}/hooks", "--jq", jq], None)
97
+ hooks = []
98
+ for line in out.splitlines():
99
+ if not line.strip():
100
+ continue
101
+ item = json.loads(line)
102
+ hooks.append(Hook(
103
+ id=int(item["id"]), url=str(item["url"]), events=tuple(item.get("events") or ()),
104
+ active=bool(item.get("active")), content_type=str(item.get("content_type") or ""),
105
+ )) # fmt: skip
106
+ return hooks
107
+
108
+
109
+ def create_hook(run: Runner, repo: str, payload: dict[str, object]) -> int:
110
+ out = run(["api", "-X", "POST", f"repos/{repo}/hooks", "--input", "-", "--jq", ".id"],
111
+ json.dumps(payload)) # fmt: skip
112
+ return int(out.strip())
113
+
114
+
115
+ def update_hook(run: Runner, repo: str, hook_id: int, payload: dict[str, object]) -> None:
116
+ run(["api", "-X", "PATCH", f"repos/{repo}/hooks/{hook_id}", "--input", "-", "--jq", ".id"],
117
+ json.dumps(payload)) # fmt: skip
118
+
119
+
120
+ def delete_hook(run: Runner, repo: str, hook_id: int) -> None:
121
+ run(["api", "-X", "DELETE", f"repos/{repo}/hooks/{hook_id}"], None)
122
+
123
+
124
+ # `https://smee.io/new`가 새 주소로 넘겨 주는 것(307의 Location)을 읽는다(smee-client의
125
+ # createChannel과 같다). node로 한다: python.org에서 받은 macOS의 Python은 인증서를 따로 깔기
126
+ # 전에는 HTTPS 확인이 실패한다. node는 입구의 전제이고 자기 인증서 묶음을 쓴다
127
+ _SMEE_NEW_JS: Final = (
128
+ f"fetch('https://{SMEE_HOST}/new', {{method: 'HEAD', redirect: 'manual'}})"
129
+ ".then((r) => console.log(r.headers.get('location') || ''))"
130
+ ".catch((e) => { console.error(String(e)); process.exit(1); })"
131
+ )
132
+
133
+
134
+ def new_smee_url(node: str | None, timeout: float = 20) -> str:
135
+ """smee.io에 새 채널을 만들어 그 주소를 돌려준다."""
136
+ if not node:
137
+ raise SetupGitHubError("smee 주소를 만들 node를 찾지 못함")
138
+ env = {k: os.environ[k] for k in ("PATH", "HOME") if k in os.environ}
139
+ try:
140
+ proc = subprocess.run([node, "-e", _SMEE_NEW_JS], capture_output=True, text=True,
141
+ env=env, timeout=timeout, check=False) # fmt: skip
142
+ except (OSError, subprocess.TimeoutExpired) as e:
143
+ raise SetupGitHubError(f"smee 주소를 만들지 못함: {e}") from e
144
+ location = proc.stdout.strip()
145
+ if proc.returncode != 0 or not location.startswith(f"https://{SMEE_HOST}/"):
146
+ raise SetupGitHubError(f"smee 주소를 만들지 못함: {proc.stderr.strip()[-300:]}")
147
+ return location
148
+
149
+
150
+ def token_from_env(environ: Mapping[str, str] | None = None) -> str | None:
151
+ """질문 없이 돌 때 토큰을 받는 환경 변수. 명령줄 인자로는 받지 않는다(셸 기록에 남는다)."""
152
+ source = os.environ if environ is None else environ
153
+ return (source.get(TOKEN_INPUT_ENV) or "").strip() or None
@@ -0,0 +1,32 @@
1
+ {
2
+ "python3": {
3
+ "label": "python 3.11 이상",
4
+ "darwin": "brew install python@3.12 (Homebrew가 없으면 https://www.python.org/downloads/)",
5
+ "linux": "sudo apt install python3 python3-venv (apt가 아니면 배포판의 패키지 관리자로 python 3.11 이상)",
6
+ "other": "https://www.python.org/downloads/ 에서 3.11 이상"
7
+ },
8
+ "docker": {
9
+ "label": "docker",
10
+ "darwin": "Docker Desktop 설치: https://docs.docker.com/desktop/setup/install/mac-install/",
11
+ "linux": "Docker Engine 설치: https://docs.docker.com/engine/install/",
12
+ "other": "https://docs.docker.com/get-docker/"
13
+ },
14
+ "git": {
15
+ "label": "git",
16
+ "darwin": "xcode-select --install (또는 brew install git)",
17
+ "linux": "sudo apt install git",
18
+ "other": "https://git-scm.com/downloads"
19
+ },
20
+ "gh": {
21
+ "label": "gh (GitHub CLI)",
22
+ "darwin": "brew install gh",
23
+ "linux": "https://github.com/cli/cli/blob/trunk/docs/install_linux.md",
24
+ "other": "https://cli.github.com/"
25
+ },
26
+ "claude": {
27
+ "label": "claude (Claude Code CLI)",
28
+ "darwin": "npm install -g @anthropic-ai/claude-code → 설치한 뒤 claude를 실행해 /login 까지 해야 한다",
29
+ "linux": "npm install -g @anthropic-ai/claude-code → 설치한 뒤 claude를 실행해 /login 까지 해야 한다",
30
+ "other": "npm install -g @anthropic-ai/claude-code → 설치한 뒤 claude를 실행해 /login 까지 해야 한다"
31
+ }
32
+ }
@@ -0,0 +1,344 @@
1
+ """configure·add·rm·list의 판정과 글 (외부 호출 없음).
2
+
3
+ - repo 이름 확인
4
+ - config.yaml 고치기: `repos`에 더하고 빼되 다른 설정과 주석을 지킨다(글을 줄 단위로 고치고, 고친 뒤
5
+ YAML로 읽어 바뀐 것이 `repos`뿐인지 확인한다)
6
+ - 웹훅: 만들지 고칠지, 이벤트, 손으로 등록할 값
7
+ - 빠진 프로그램 안내, 끝 확인 표, 토큰 권한 안내
8
+ """
9
+
10
+ import re
11
+ import unicodedata
12
+ from collections.abc import Mapping, Sequence
13
+ from dataclasses import dataclass
14
+ from typing import Any, Final, Literal
15
+
16
+ import yaml
17
+
18
+ REPO_EXAMPLE: Final = "octocat/hello-world"
19
+ _REPO: Final = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})/[A-Za-z0-9._-]{1,100}")
20
+
21
+ # 서버가 처리하는 이벤트 (app/api/webhook.py의 parse_event). tests/setup이 둘이 같은지 본다
22
+ HOOK_EVENTS: Final = (
23
+ "pull_request", "issue_comment", "pull_request_review", "pull_request_review_comment",
24
+ ) # fmt: skip
25
+ EVENT_LABELS: Final[Mapping[str, str]] = {
26
+ "pull_request": "Pull requests",
27
+ "issue_comment": "Issue comments",
28
+ "pull_request_review": "Pull request reviews",
29
+ "pull_request_review_comment": "Pull request review comments",
30
+ }
31
+ WEBHOOK_PATH: Final = "/webhook/github"
32
+
33
+ TOKEN_PERMISSIONS: Final = """토큰에 필요한 권한 (처리할 repo마다):
34
+ fine-grained 토큰의 Repository permissions
35
+ - Contents: Read and write (clone·fetch, 수정안 브랜치 push와 지우기)
36
+ - Pull requests: Read and write (PR 조회, 수정안 PR 열기·닫기, 리뷰·줄 코멘트, 스레드 해결)
37
+ - Issues: Read and write (PR의 일반 코멘트 읽기·달기·고치기)
38
+ - Metadata: Read-only (자동으로 붙는다)
39
+ - Webhooks: Read and write (configure·add·rm이 웹훅을 등록·지울 때만)
40
+ classic 토큰의 scope
41
+ - repo (공개 repo만 다루면 public_repo)
42
+ - admin:repo_hook (웹훅을 등록·지울 때만)"""
43
+
44
+
45
+ class ConfigEditError(ValueError):
46
+ """config.yaml의 repos를 줄 단위로 고칠 수 없다. 손으로 고쳐야 한다."""
47
+
48
+
49
+ # 브라우저나 git에서 복사한 GitHub 주소: https://github.com/a/b, github.com/a/b.git,
50
+ # git@github.com:a/b.git
51
+ _GITHUB_URL: Final = re.compile(
52
+ r"(?:(?:https?://)?(?:www\.)?github\.com/|git@github\.com:)([^/\s]+)/([^/\s?#]+)(?:[/?#].*)?",
53
+ re.IGNORECASE,
54
+ )
55
+
56
+
57
+ def repo_name(text: str) -> str:
58
+ """사용자가 적은 repo를 `계정/저장소이름`으로. GitHub 주소를 붙여 넣은 것도 받는다(끝의 `.git`과
59
+ 뒤의 경로는 뗀다). 주소가 아니면 앞뒤 공백만 뗀 그대로다(꼴은 `repo_problem`이 본다)."""
60
+ text = text.strip()
61
+ if found := _GITHUB_URL.fullmatch(text):
62
+ return f"{found.group(1)}/{found.group(2).removesuffix('.git')}"
63
+ return text
64
+
65
+
66
+ def repo_problem(text: str) -> str | None:
67
+ """repo가 `계정/저장소이름` 꼴도 GitHub 주소도 아니면 그 안내."""
68
+ name = repo_name(text)
69
+ if _REPO.fullmatch(name) and name.split("/")[1] not in (".", ".."):
70
+ return None
71
+ return (
72
+ f"repo는 `계정/저장소이름` 꼴이나 GitHub 주소로 적습니다 (예: {REPO_EXAMPLE}). "
73
+ f"받은 값: {text!r}"
74
+ )
75
+
76
+
77
+ def spelled_as(name: str, known: Sequence[str]) -> str | None:
78
+ """known 중 name과 대소문자만 다른(또는 같은) 것. GitHub의 계정과 저장소 이름은 대소문자를
79
+ 가리지 않는다."""
80
+ wanted = name.casefold()
81
+ return next((k for k in known if k.casefold() == wanted), None)
82
+
83
+
84
+ # --- config.yaml ---
85
+
86
+
87
+ def _load(text: str) -> dict[str, Any]:
88
+ try:
89
+ data = yaml.safe_load(text) if text.strip() else {}
90
+ except yaml.YAMLError as e:
91
+ raise ConfigEditError(f"config.yaml을 읽지 못함: {e}") from e
92
+ data = {} if data is None else data
93
+ if not isinstance(data, dict):
94
+ raise ConfigEditError("config.yaml의 맨 위가 키와 값의 묶음이 아님")
95
+ repos = data.get("repos")
96
+ if repos is not None and not (
97
+ isinstance(repos, list) and all(isinstance(r, str) for r in repos)
98
+ ):
99
+ raise ConfigEditError("config.yaml의 repos가 글자의 목록이 아님")
100
+ return data
101
+
102
+
103
+ def config_data(text: str) -> dict[str, Any]:
104
+ """config.yaml의 글을 읽은 값. 읽지 못하거나 repos가 글자의 목록이 아니면 ConfigEditError."""
105
+ return _load(text)
106
+
107
+
108
+ def config_repos(text: str) -> list[str]:
109
+ return list(_load(text).get("repos") or [])
110
+
111
+
112
+ _REPOS_KEY: Final = re.compile(r"^repos\s*:")
113
+ _FLOW: Final = re.compile(r"^(repos\s*:\s*)\[(.*)\](\s*(?:#.*)?)$")
114
+ _BLOCK_HEAD: Final = re.compile(r"^repos\s*:\s*(#.*)?$")
115
+ _ITEM: Final = re.compile(r"^(\s*)-\s+(.*?)\s*(#.*)?$")
116
+
117
+
118
+ def _flow_items(inner: str) -> list[str]:
119
+ return [item.strip() for item in inner.split(",") if item.strip()]
120
+
121
+
122
+ def _value(scalar: str) -> object:
123
+ try:
124
+ return yaml.safe_load(scalar)
125
+ except yaml.YAMLError:
126
+ return None
127
+
128
+
129
+ def _block_items(lines: list[str], head: int) -> list[int]:
130
+ """`repos:` 아래 목록 항목의 줄 번호들. 빈 줄과 주석은 건너뛰고, 들여쓰지 않은 다른 키에서
131
+ 멈춘다."""
132
+ found = []
133
+ for i in range(head + 1, len(lines)):
134
+ line = lines[i]
135
+ if not line.strip() or line.lstrip().startswith("#"):
136
+ continue
137
+ if _ITEM.match(line.rstrip("\n")):
138
+ found.append(i)
139
+ continue
140
+ if line[0] in " \t": # 항목이 여러 줄이면 아래 확인에서 걸러진다
141
+ continue
142
+ break
143
+ return found
144
+
145
+
146
+ def _check(before: dict[str, Any], text: str, repos: list[str]) -> str:
147
+ after = _load(text)
148
+ if after.get("repos") != repos or {k: v for k, v in after.items() if k != "repos"} != {
149
+ k: v for k, v in before.items() if k != "repos"
150
+ }:
151
+ raise ConfigEditError("config.yaml의 repos를 고치지 못함. 손으로 고친다")
152
+ return text
153
+
154
+
155
+ def add_repos(text: str, repos: Sequence[str]) -> tuple[str, list[str]]:
156
+ """repos 목록에 없는 것만 끝에 더한다. (새 글, 더한 것). 더할 것이 없으면 글을 그대로
157
+ 돌려준다."""
158
+ before = _load(text)
159
+ current = list(before.get("repos") or [])
160
+ new = []
161
+ for r in dict.fromkeys(repos): # 대소문자만 다른 것은 이미 있는 것이다
162
+ if spelled_as(r, [*current, *new]) is None:
163
+ new.append(r)
164
+ if not new:
165
+ return text, []
166
+ lines = text.splitlines(keepends=True)
167
+ head = next((i for i, line in enumerate(lines) if _REPOS_KEY.match(line)), None)
168
+ if head is None:
169
+ body = text if not text or text.endswith("\n") else text + "\n"
170
+ out = body + "repos:\n" + "".join(f" - {r}\n" for r in new)
171
+ return _check(before, out, current + new), new
172
+ line = lines[head].rstrip("\n")
173
+ if flow := _FLOW.match(line):
174
+ items = _flow_items(flow.group(2)) + new
175
+ lines[head] = f"{flow.group(1)}[{', '.join(items)}]{flow.group(3)}\n"
176
+ elif _BLOCK_HEAD.match(line):
177
+ items = _block_items(lines, head)
178
+ last = items[-1] if items else head
179
+ indent = _ITEM.match(lines[last].rstrip("\n")).group(1) if items else " " # type: ignore[union-attr]
180
+ if not lines[last].endswith("\n"):
181
+ lines[last] += "\n"
182
+ lines[last + 1 : last + 1] = [f"{indent}- {r}\n" for r in new]
183
+ else:
184
+ raise ConfigEditError(f"config.yaml의 repos 줄을 고칠 수 없음: {line!r}. 손으로 고친다")
185
+ return _check(before, "".join(lines), current + new), new
186
+
187
+
188
+ def remove_repos(text: str, repos: Sequence[str]) -> tuple[str, list[str]]:
189
+ """repos 목록에서 뺀다. (새 글, 뺀 것). 마지막 것을 빼면 `repos: []`로 둔다(빈 목록도 설정으로
190
+ 읽힌다. `repos:`만 남으면 null이라 서버가 시작하지 못한다)."""
191
+ before = _load(text)
192
+ current = list(before.get("repos") or [])
193
+ # 목록에 적힌 철자로 찾는다(대소문자만 다르게 적어도 뺀다)
194
+ gone = list(dict.fromkeys(s for r in repos if (s := spelled_as(r, current)) is not None))
195
+ if not gone:
196
+ return text, []
197
+ left = [r for r in current if r not in gone]
198
+ lines = text.splitlines(keepends=True)
199
+ head = next((i for i, line in enumerate(lines) if _REPOS_KEY.match(line)), None)
200
+ if head is None:
201
+ raise ConfigEditError("config.yaml에서 repos 줄을 찾지 못함")
202
+ line = lines[head].rstrip("\n")
203
+ if flow := _FLOW.match(line):
204
+ items = [item for item in _flow_items(flow.group(2)) if _value(item) not in gone]
205
+ lines[head] = f"{flow.group(1)}[{', '.join(items)}]{flow.group(3)}\n"
206
+ elif head_match := _BLOCK_HEAD.match(line):
207
+ drop = [
208
+ i for i in _block_items(lines, head)
209
+ if _value(_ITEM.match(lines[i].rstrip("\n")).group(2)) in gone # type: ignore[union-attr]
210
+ ] # fmt: skip
211
+ for i in reversed(drop):
212
+ del lines[i]
213
+ if not left:
214
+ comment = head_match.group(1)
215
+ lines[head] = "repos: []" + (f" {comment}" if comment else "") + "\n"
216
+ else:
217
+ raise ConfigEditError(f"config.yaml의 repos 줄을 고칠 수 없음: {line!r}. 손으로 고친다")
218
+ return _check(before, "".join(lines), left), gone
219
+
220
+
221
+ # --- 웹훅 ---
222
+
223
+
224
+ @dataclass(frozen=True)
225
+ class Hook:
226
+ id: int
227
+ url: str
228
+ events: tuple[str, ...]
229
+ active: bool
230
+ content_type: str
231
+
232
+
233
+ @dataclass(frozen=True)
234
+ class HookPlan:
235
+ """create: 새로 만든다. update: 같은 주소의 웹훅을 맞춘다. conflict: 같은 주소는 없고 pr-proof로
236
+ 보이는 다른 주소의 웹훅이 있다. 만들면 같은 소식이 두 번 오므로 만들지 않는다."""
237
+
238
+ action: Literal["create", "update", "conflict"]
239
+ hook_id: int | None
240
+ changes: tuple[str, ...]
241
+ others: tuple[str, ...] = ()
242
+
243
+
244
+ def _looks_like_pr_proof(url: str) -> bool:
245
+ return url.startswith("https://smee.io/") or url.rstrip("/").endswith(WEBHOOK_PATH)
246
+
247
+
248
+ def plan_hook(hooks: Sequence[Hook], url: str) -> HookPlan:
249
+ same = [h for h in hooks if h.url == url]
250
+ if not same:
251
+ others = tuple(h.url for h in hooks if _looks_like_pr_proof(h.url))
252
+ if others:
253
+ return HookPlan("conflict", None, (), others)
254
+ return HookPlan("create", None, ("새 웹훅을 만든다",))
255
+ hook = same[0]
256
+ changes = []
257
+ if set(hook.events) != set(HOOK_EVENTS):
258
+ missing = [EVENT_LABELS[e] for e in HOOK_EVENTS if e not in hook.events]
259
+ changes.append(
260
+ "이벤트를 넷으로 맞춘다" + (f" (빠짐: {', '.join(missing)})" if missing else "")
261
+ )
262
+ if not hook.active:
263
+ changes.append("꺼져 있던 웹훅을 켠다")
264
+ if hook.content_type != "json":
265
+ changes.append("Content type을 application/json으로")
266
+ # GitHub은 저장한 비밀값을 돌려주지 않아 같은지 알 수 없다. 늘 설정 폴더의 값으로 맞춘다
267
+ changes.append("비밀값을 설정 폴더의 webhook_secret으로 맞춘다")
268
+ return HookPlan("update", hook.id, tuple(changes))
269
+
270
+
271
+ def hook_payload(url: str, secret: str, *, create: bool) -> dict[str, Any]:
272
+ payload: dict[str, Any] = {
273
+ "active": True,
274
+ "events": list(HOOK_EVENTS),
275
+ "config": {"url": url, "content_type": "json", "secret": secret, "insecure_ssl": "0"},
276
+ }
277
+ return {"name": "web", **payload} if create else payload
278
+
279
+
280
+ def hooks_at(hooks: Sequence[Hook], url: str) -> list[Hook]:
281
+ """그 주소의 웹훅만 (rm이 지우는 것). 다른 주소의 웹훅은 건드리지 않는다."""
282
+ return [h for h in hooks if h.url == url]
283
+
284
+
285
+ def hook_status(hooks: Sequence[Hook], url: str | None) -> str:
286
+ if url is None:
287
+ return "웹훅 받는 주소가 저장되어 있지 않음"
288
+ same = hooks_at(hooks, url)
289
+ if not same:
290
+ return "웹훅 없음"
291
+ hook = same[0]
292
+ if not hook.active:
293
+ return "웹훅 있음, 꺼져 있음"
294
+ missing = [EVENT_LABELS[e] for e in HOOK_EVENTS if e not in hook.events]
295
+ if missing:
296
+ return f"웹훅 있음, 이벤트 빠짐: {', '.join(missing)}"
297
+ return "웹훅 있음, 이벤트 맞음"
298
+
299
+
300
+ def manual_hook_text(repo: str, url: str, secret_path: str) -> str:
301
+ events = ", ".join(EVENT_LABELS[e] for e in HOOK_EVENTS)
302
+ return "\n".join([
303
+ f"{repo}의 GitHub 설정 → Webhooks → Add webhook에서 손으로 등록하세요:",
304
+ f" Payload URL: {url}",
305
+ " Content type: application/json",
306
+ f" Secret: {secret_path} 파일의 값",
307
+ f" 이벤트(Let me select individual events): {events}",
308
+ ]) # fmt: skip
309
+
310
+
311
+ # --- 안내 글 ---
312
+
313
+
314
+ def platform_key(platform: str) -> str:
315
+ return platform if platform in ("darwin", "linux") else "other"
316
+
317
+
318
+ def missing_programs_text(
319
+ missing: Sequence[str], hints: Mapping[str, Mapping[str, str]], platform: str
320
+ ) -> str:
321
+ """빠진 프로그램을 한 번에 모두, 운영체제에 맞는 설치 방법과 함께 (bin/pr-proof.js와 같은
322
+ 표)."""
323
+ key = platform_key(platform)
324
+ lines = ["필요한 프로그램이 없습니다. 설치한 뒤 다시 실행하세요.", ""]
325
+ lines += [f"- {hints[name]['label']}: {hints[name][key]}" for name in missing]
326
+ return "\n".join(lines)
327
+
328
+
329
+ def _cells(text: str) -> int:
330
+ """터미널에서 차지하는 칸 수. 한글 같은 넓은 글자는 두 칸이다."""
331
+ return sum(2 if unicodedata.east_asian_width(c) in ("W", "F") else 1 for c in text)
332
+
333
+
334
+ def _pad(text: str, width: int) -> str:
335
+ return text + " " * (width - _cells(text))
336
+
337
+
338
+ def check_table(rows: Sequence[tuple[str, bool, str]]) -> str:
339
+ """끝 확인 표. (이름, 통과, 고치는 방법)."""
340
+ width = max(_cells(name) for name, _, _ in [("확인", True, ""), *rows]) + 2
341
+ lines = [f"{_pad('확인', width)}결과"]
342
+ for name, ok, hint in rows:
343
+ lines.append(_pad(name, width) + ("통과" if ok else f"실패 → {hint}"))
344
+ return "\n".join(lines)