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,93 @@
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 read_port(directory: Path | None = None) -> int:
74
+ """`pr-proof.env`의 API_PORT. 없거나 읽지 못하면 기본값."""
75
+ path = (directory or config_dir()) / RUN_ENV_FILE
76
+ try:
77
+ lines = path.read_text().splitlines()
78
+ except OSError:
79
+ return DEFAULT_PORT
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 DEFAULT_PORT
85
+
86
+
87
+ def write_port(port: int, directory: Path | None = None) -> None:
88
+ path = (directory or config_dir()) / RUN_ENV_FILE
89
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
90
+ path.write_text(
91
+ "# npx pr-proof start가 honcho에 넘기는 실행 설정. 비밀값은 넣지 않는다.\n"
92
+ f"{PORT_KEY}={port}\n"
93
+ )
@@ -0,0 +1,149 @@
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]:
76
+ """(읽기, 쓰기). 저장소가 보이지 않으면 NoPermission.
77
+
78
+ GitHub이 주는 것은 계정의 저장소 권한(`permissions.push`)이다. fine-grained 토큰에서 그 토큰에
79
+ 준 권한이 모자란지는 실제로 쓰기 전에는 알 수 없다(README의 권한 목록을 본다).
80
+ """
81
+ out = run(["api", f"repos/{repo}", "--jq", "[.permissions.pull, .permissions.push] | @tsv"],
82
+ None) # fmt: skip
83
+ pull, _, push = out.strip().partition("\t")
84
+ return pull == "true", push == "true"
85
+
86
+
87
+ def list_hooks(run: Runner, repo: str) -> list[Hook]:
88
+ jq = (
89
+ '.[] | {id, active, events, url: (.config.url // ""), '
90
+ 'content_type: (.config.content_type // "")} | @json'
91
+ )
92
+ out = run(["api", "--paginate", f"repos/{repo}/hooks", "--jq", jq], None)
93
+ hooks = []
94
+ for line in out.splitlines():
95
+ if not line.strip():
96
+ continue
97
+ item = json.loads(line)
98
+ hooks.append(Hook(
99
+ id=int(item["id"]), url=str(item["url"]), events=tuple(item.get("events") or ()),
100
+ active=bool(item.get("active")), content_type=str(item.get("content_type") or ""),
101
+ )) # fmt: skip
102
+ return hooks
103
+
104
+
105
+ def create_hook(run: Runner, repo: str, payload: dict[str, object]) -> int:
106
+ out = run(["api", "-X", "POST", f"repos/{repo}/hooks", "--input", "-", "--jq", ".id"],
107
+ json.dumps(payload)) # fmt: skip
108
+ return int(out.strip())
109
+
110
+
111
+ def update_hook(run: Runner, repo: str, hook_id: int, payload: dict[str, object]) -> None:
112
+ run(["api", "-X", "PATCH", f"repos/{repo}/hooks/{hook_id}", "--input", "-", "--jq", ".id"],
113
+ json.dumps(payload)) # fmt: skip
114
+
115
+
116
+ def delete_hook(run: Runner, repo: str, hook_id: int) -> None:
117
+ run(["api", "-X", "DELETE", f"repos/{repo}/hooks/{hook_id}"], None)
118
+
119
+
120
+ # `https://smee.io/new`가 새 주소로 넘겨 주는 것(307의 Location)을 읽는다(smee-client의
121
+ # createChannel과 같다). node로 한다: python.org에서 받은 macOS의 Python은 인증서를 따로 깔기
122
+ # 전에는 HTTPS 확인이 실패한다. node는 입구의 전제이고 자기 인증서 묶음을 쓴다
123
+ _SMEE_NEW_JS: Final = (
124
+ f"fetch('https://{SMEE_HOST}/new', {{method: 'HEAD', redirect: 'manual'}})"
125
+ ".then((r) => console.log(r.headers.get('location') || ''))"
126
+ ".catch((e) => { console.error(String(e)); process.exit(1); })"
127
+ )
128
+
129
+
130
+ def new_smee_url(node: str | None, timeout: float = 20) -> str:
131
+ """smee.io에 새 채널을 만들어 그 주소를 돌려준다."""
132
+ if not node:
133
+ raise SetupGitHubError("smee 주소를 만들 node를 찾지 못함")
134
+ env = {k: os.environ[k] for k in ("PATH", "HOME") if k in os.environ}
135
+ try:
136
+ proc = subprocess.run([node, "-e", _SMEE_NEW_JS], capture_output=True, text=True,
137
+ env=env, timeout=timeout, check=False) # fmt: skip
138
+ except (OSError, subprocess.TimeoutExpired) as e:
139
+ raise SetupGitHubError(f"smee 주소를 만들지 못함: {e}") from e
140
+ location = proc.stdout.strip()
141
+ if proc.returncode != 0 or not location.startswith(f"https://{SMEE_HOST}/"):
142
+ raise SetupGitHubError(f"smee 주소를 만들지 못함: {proc.stderr.strip()[-300:]}")
143
+ return location
144
+
145
+
146
+ def token_from_env(environ: Mapping[str, str] | None = None) -> str | None:
147
+ """질문 없이 돌 때 토큰을 받는 환경 변수. 명령줄 인자로는 받지 않는다(셸 기록에 남는다)."""
148
+ source = os.environ if environ is None else environ
149
+ 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,312 @@
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
+ def repo_problem(text: str) -> str | None:
50
+ """repo 이름이 `계정/저장소이름` 꼴이 아니면 그 안내."""
51
+ if _REPO.fullmatch(text) and text.split("/")[1] not in (".", ".."):
52
+ return None
53
+ return f"repo는 `계정/저장소이름` 꼴로 적습니다 (예: {REPO_EXAMPLE}): {text!r}"
54
+
55
+
56
+ # --- config.yaml ---
57
+
58
+
59
+ def _load(text: str) -> dict[str, Any]:
60
+ try:
61
+ data = yaml.safe_load(text) if text.strip() else {}
62
+ except yaml.YAMLError as e:
63
+ raise ConfigEditError(f"config.yaml을 읽지 못함: {e}") from e
64
+ data = {} if data is None else data
65
+ if not isinstance(data, dict):
66
+ raise ConfigEditError("config.yaml의 맨 위가 키와 값의 묶음이 아님")
67
+ repos = data.get("repos")
68
+ if repos is not None and not (
69
+ isinstance(repos, list) and all(isinstance(r, str) for r in repos)
70
+ ):
71
+ raise ConfigEditError("config.yaml의 repos가 글자의 목록이 아님")
72
+ return data
73
+
74
+
75
+ def config_data(text: str) -> dict[str, Any]:
76
+ """config.yaml의 글을 읽은 값. 읽지 못하거나 repos가 글자의 목록이 아니면 ConfigEditError."""
77
+ return _load(text)
78
+
79
+
80
+ def config_repos(text: str) -> list[str]:
81
+ return list(_load(text).get("repos") or [])
82
+
83
+
84
+ _REPOS_KEY: Final = re.compile(r"^repos\s*:")
85
+ _FLOW: Final = re.compile(r"^(repos\s*:\s*)\[(.*)\](\s*(?:#.*)?)$")
86
+ _BLOCK_HEAD: Final = re.compile(r"^repos\s*:\s*(#.*)?$")
87
+ _ITEM: Final = re.compile(r"^(\s*)-\s+(.*?)\s*(#.*)?$")
88
+
89
+
90
+ def _flow_items(inner: str) -> list[str]:
91
+ return [item.strip() for item in inner.split(",") if item.strip()]
92
+
93
+
94
+ def _value(scalar: str) -> object:
95
+ try:
96
+ return yaml.safe_load(scalar)
97
+ except yaml.YAMLError:
98
+ return None
99
+
100
+
101
+ def _block_items(lines: list[str], head: int) -> list[int]:
102
+ """`repos:` 아래 목록 항목의 줄 번호들. 빈 줄과 주석은 건너뛰고, 들여쓰지 않은 다른 키에서
103
+ 멈춘다."""
104
+ found = []
105
+ for i in range(head + 1, len(lines)):
106
+ line = lines[i]
107
+ if not line.strip() or line.lstrip().startswith("#"):
108
+ continue
109
+ if _ITEM.match(line.rstrip("\n")):
110
+ found.append(i)
111
+ continue
112
+ if line[0] in " \t": # 항목이 여러 줄이면 아래 확인에서 걸러진다
113
+ continue
114
+ break
115
+ return found
116
+
117
+
118
+ def _check(before: dict[str, Any], text: str, repos: list[str]) -> str:
119
+ after = _load(text)
120
+ if after.get("repos") != repos or {k: v for k, v in after.items() if k != "repos"} != {
121
+ k: v for k, v in before.items() if k != "repos"
122
+ }:
123
+ raise ConfigEditError("config.yaml의 repos를 고치지 못함. 손으로 고친다")
124
+ return text
125
+
126
+
127
+ def add_repos(text: str, repos: Sequence[str]) -> tuple[str, list[str]]:
128
+ """repos 목록에 없는 것만 끝에 더한다. (새 글, 더한 것). 더할 것이 없으면 글을 그대로
129
+ 돌려준다."""
130
+ before = _load(text)
131
+ current = list(before.get("repos") or [])
132
+ new = [r for r in dict.fromkeys(repos) if r not in current]
133
+ if not new:
134
+ return text, []
135
+ lines = text.splitlines(keepends=True)
136
+ head = next((i for i, line in enumerate(lines) if _REPOS_KEY.match(line)), None)
137
+ if head is None:
138
+ body = text if not text or text.endswith("\n") else text + "\n"
139
+ out = body + "repos:\n" + "".join(f" - {r}\n" for r in new)
140
+ return _check(before, out, current + new), new
141
+ line = lines[head].rstrip("\n")
142
+ if flow := _FLOW.match(line):
143
+ items = _flow_items(flow.group(2)) + new
144
+ lines[head] = f"{flow.group(1)}[{', '.join(items)}]{flow.group(3)}\n"
145
+ elif _BLOCK_HEAD.match(line):
146
+ items = _block_items(lines, head)
147
+ last = items[-1] if items else head
148
+ indent = _ITEM.match(lines[last].rstrip("\n")).group(1) if items else " " # type: ignore[union-attr]
149
+ if not lines[last].endswith("\n"):
150
+ lines[last] += "\n"
151
+ lines[last + 1 : last + 1] = [f"{indent}- {r}\n" for r in new]
152
+ else:
153
+ raise ConfigEditError(f"config.yaml의 repos 줄을 고칠 수 없음: {line!r}. 손으로 고친다")
154
+ return _check(before, "".join(lines), current + new), new
155
+
156
+
157
+ def remove_repos(text: str, repos: Sequence[str]) -> tuple[str, list[str]]:
158
+ """repos 목록에서 뺀다. (새 글, 뺀 것). 마지막 것을 빼면 `repos: []`로 둔다(빈 목록도 설정으로
159
+ 읽힌다. `repos:`만 남으면 null이라 서버가 시작하지 못한다)."""
160
+ before = _load(text)
161
+ current = list(before.get("repos") or [])
162
+ gone = [r for r in dict.fromkeys(repos) if r in current]
163
+ if not gone:
164
+ return text, []
165
+ left = [r for r in current if r not in gone]
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
+ raise ConfigEditError("config.yaml에서 repos 줄을 찾지 못함")
170
+ line = lines[head].rstrip("\n")
171
+ if flow := _FLOW.match(line):
172
+ items = [item for item in _flow_items(flow.group(2)) if _value(item) not in gone]
173
+ lines[head] = f"{flow.group(1)}[{', '.join(items)}]{flow.group(3)}\n"
174
+ elif head_match := _BLOCK_HEAD.match(line):
175
+ drop = [
176
+ i for i in _block_items(lines, head)
177
+ if _value(_ITEM.match(lines[i].rstrip("\n")).group(2)) in gone # type: ignore[union-attr]
178
+ ] # fmt: skip
179
+ for i in reversed(drop):
180
+ del lines[i]
181
+ if not left:
182
+ comment = head_match.group(1)
183
+ lines[head] = "repos: []" + (f" {comment}" if comment else "") + "\n"
184
+ else:
185
+ raise ConfigEditError(f"config.yaml의 repos 줄을 고칠 수 없음: {line!r}. 손으로 고친다")
186
+ return _check(before, "".join(lines), left), gone
187
+
188
+
189
+ # --- 웹훅 ---
190
+
191
+
192
+ @dataclass(frozen=True)
193
+ class Hook:
194
+ id: int
195
+ url: str
196
+ events: tuple[str, ...]
197
+ active: bool
198
+ content_type: str
199
+
200
+
201
+ @dataclass(frozen=True)
202
+ class HookPlan:
203
+ """create: 새로 만든다. update: 같은 주소의 웹훅을 맞춘다. conflict: 같은 주소는 없고 pr-proof로
204
+ 보이는 다른 주소의 웹훅이 있다. 만들면 같은 소식이 두 번 오므로 만들지 않는다."""
205
+
206
+ action: Literal["create", "update", "conflict"]
207
+ hook_id: int | None
208
+ changes: tuple[str, ...]
209
+ others: tuple[str, ...] = ()
210
+
211
+
212
+ def _looks_like_pr_proof(url: str) -> bool:
213
+ return url.startswith("https://smee.io/") or url.rstrip("/").endswith(WEBHOOK_PATH)
214
+
215
+
216
+ def plan_hook(hooks: Sequence[Hook], url: str) -> HookPlan:
217
+ same = [h for h in hooks if h.url == url]
218
+ if not same:
219
+ others = tuple(h.url for h in hooks if _looks_like_pr_proof(h.url))
220
+ if others:
221
+ return HookPlan("conflict", None, (), others)
222
+ return HookPlan("create", None, ("새 웹훅을 만든다",))
223
+ hook = same[0]
224
+ changes = []
225
+ if set(hook.events) != set(HOOK_EVENTS):
226
+ missing = [EVENT_LABELS[e] for e in HOOK_EVENTS if e not in hook.events]
227
+ changes.append(
228
+ "이벤트를 넷으로 맞춘다" + (f" (빠짐: {', '.join(missing)})" if missing else "")
229
+ )
230
+ if not hook.active:
231
+ changes.append("꺼져 있던 웹훅을 켠다")
232
+ if hook.content_type != "json":
233
+ changes.append("Content type을 application/json으로")
234
+ # GitHub은 저장한 비밀값을 돌려주지 않아 같은지 알 수 없다. 늘 설정 폴더의 값으로 맞춘다
235
+ changes.append("비밀값을 설정 폴더의 webhook_secret으로 맞춘다")
236
+ return HookPlan("update", hook.id, tuple(changes))
237
+
238
+
239
+ def hook_payload(url: str, secret: str, *, create: bool) -> dict[str, Any]:
240
+ payload: dict[str, Any] = {
241
+ "active": True,
242
+ "events": list(HOOK_EVENTS),
243
+ "config": {"url": url, "content_type": "json", "secret": secret, "insecure_ssl": "0"},
244
+ }
245
+ return {"name": "web", **payload} if create else payload
246
+
247
+
248
+ def hooks_at(hooks: Sequence[Hook], url: str) -> list[Hook]:
249
+ """그 주소의 웹훅만 (rm이 지우는 것). 다른 주소의 웹훅은 건드리지 않는다."""
250
+ return [h for h in hooks if h.url == url]
251
+
252
+
253
+ def hook_status(hooks: Sequence[Hook], url: str | None) -> str:
254
+ if url is None:
255
+ return "웹훅 받는 주소가 저장되어 있지 않음"
256
+ same = hooks_at(hooks, url)
257
+ if not same:
258
+ return "웹훅 없음"
259
+ hook = same[0]
260
+ if not hook.active:
261
+ return "웹훅 있음, 꺼져 있음"
262
+ missing = [EVENT_LABELS[e] for e in HOOK_EVENTS if e not in hook.events]
263
+ if missing:
264
+ return f"웹훅 있음, 이벤트 빠짐: {', '.join(missing)}"
265
+ return "웹훅 있음, 이벤트 맞음"
266
+
267
+
268
+ def manual_hook_text(repo: str, url: str, secret_path: str) -> str:
269
+ events = ", ".join(EVENT_LABELS[e] for e in HOOK_EVENTS)
270
+ return "\n".join([
271
+ f"{repo}의 GitHub 설정 → Webhooks → Add webhook에서 손으로 등록하세요:",
272
+ f" Payload URL: {url}",
273
+ " Content type: application/json",
274
+ f" Secret: {secret_path} 파일의 값",
275
+ f" 이벤트(Let me select individual events): {events}",
276
+ ]) # fmt: skip
277
+
278
+
279
+ # --- 안내 글 ---
280
+
281
+
282
+ def platform_key(platform: str) -> str:
283
+ return platform if platform in ("darwin", "linux") else "other"
284
+
285
+
286
+ def missing_programs_text(
287
+ missing: Sequence[str], hints: Mapping[str, Mapping[str, str]], platform: str
288
+ ) -> str:
289
+ """빠진 프로그램을 한 번에 모두, 운영체제에 맞는 설치 방법과 함께 (bin/pr-proof.js와 같은
290
+ 표)."""
291
+ key = platform_key(platform)
292
+ lines = ["필요한 프로그램이 없습니다. 설치한 뒤 다시 실행하세요.", ""]
293
+ lines += [f"- {hints[name]['label']}: {hints[name][key]}" for name in missing]
294
+ return "\n".join(lines)
295
+
296
+
297
+ def _cells(text: str) -> int:
298
+ """터미널에서 차지하는 칸 수. 한글 같은 넓은 글자는 두 칸이다."""
299
+ return sum(2 if unicodedata.east_asian_width(c) in ("W", "F") else 1 for c in text)
300
+
301
+
302
+ def _pad(text: str, width: int) -> str:
303
+ return text + " " * (width - _cells(text))
304
+
305
+
306
+ def check_table(rows: Sequence[tuple[str, bool, str]]) -> str:
307
+ """끝 확인 표. (이름, 통과, 고치는 방법)."""
308
+ width = max(_cells(name) for name, _, _ in [("확인", True, ""), *rows]) + 2
309
+ lines = [f"{_pad('확인', width)}결과"]
310
+ for name, ok, hint in rows:
311
+ lines.append(_pad(name, width) + ("통과" if ok else f"실패 → {hint}"))
312
+ return "\n".join(lines)