master
ブランチ master
LittleBeast / src / Std / Lib / Gitler / Pulls.php
21.2 KB、403行 生 Blame 履歴
1<?php
2/*************************************************************
3# 076 License
4
5Copyright (c) テクニカル諏訪子
6
7Permission is hereby granted to any person obtaining a copy of the software
8Little Beast (the "Software") to use, modify, merge, copy, publish, distribute,
9sublicense, and/or sell copies of the Software, subject to the following conditions:
10
11 1. **Origin Attribution**:
12 - You must not misrepresent the origin of the Software; you must not claim
13 you created the original Software.
14 - If the Software is used in a product, you must either:
15 a. Provide clear attribution in the product's documentation, user interface,
16 or other visible areas, **OR**
17 b. Pay the original developers a fee they specify in writing.
18 2. **Usage Restriction**:
19 - The Software, or any derivative works, dependencies, or libraries
20 incorporating it, must not be used for censorship or to suppress freedom of
21 speech, expression, or creativity. Prohibited uses include, but are not
22 limited to:
23 - Censorship of so-called "hate speech", visuals, non-mainstream opinions,
24 ideas, or objective reality.
25 - Tools or systems designed to restrict access to information or
26 artistic works.
27 3. **Notice Preservation**:
28 - This license and the above copyright notice must remain intact in all copies
29 of the source code.
30
31THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
32INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
33PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
34HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
35CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
36OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37 */
38namespace Std\Lib\Gitler;
39
40use Std\Lib\Fedi\Fedi;
41use Std\Lib\Git\Commit;
42use Std\Lib\Git\GitException;
43use Std\Lib\Git\Merge;
44use Std\Lib\Git\PackIndexer;
45use Std\Lib\Git\PackWriter;
46use Std\Lib\Git\Person;
47use Std\Lib\Git\Repository;
48use Std\Lib\Git\Walk;
49use Result;
50
51/**
52 * Gitlerのプルリクエスト(イシューのpull)
53 *
54 * pull:kind(branch:同じリポジトリのブランチ、fork:フォークのブランチ、agit:refs/for/へのプッシュ)、base(マージ先のブランチ)、
55 * head(branch・fork:owner、name、branch。agit:user、topic)、headId、baseId(作った時)、merged(by、at、commit、method)
56 * 変更はリポジトリのrefs/pull/{番号}/head(フォークからはオブジェクトをコピーする)。
57 *
58 * AGit:git push origin HEAD:refs/for/master/topic で作り、同じトピックにもう一度プッシュすると更新する。
59 */
60final class Pulls {
61 /** 比べるコミットの最大数 */
62 public const MAX_COMMITS = 250;
63 /** トピックの名前 */
64 private const TOPIC_RE = '#^[A-Za-z0-9][A-Za-z0-9._/-]{0,99}$#';
65
66 public static function ref(int $n): string {
67 return "refs/pull/{$n}/head";
68 }
69
70 /**
71 * プルリクエストのコミットの範囲([マージ先, head]、マージ後はマージする前のマージ先)
72 *
73 * @return array|null マージ先のブランチが無ければnull
74 */
75 public static function range(Repository $repo, array $issue): ?array {
76 $p = $issue['pull'];
77 $base = $p['merged']['before'] ?? $repo->refs->resolve('refs/heads/'.$p['base']) ?? $p['baseId'];
78 return $repo->objects->exists($base) && $repo->objects->exists($p['headId']) ? [$base, $p['headId']] : null;
79 }
80
81 /**
82 * 比べる(headにだけ有るコミット)
83 *
84 * @return array mergeBase、commits(古い順のID)、truncated
85 */
86 public static function compare(Repository $repo, string $base, string $head): array {
87 $walk = new Walk($repo);
88 [$ids] = $walk->commitsBetween([$head], [$base]);
89 return ['mergeBase' => $walk->mergeBase($base, $head), 'commits' => array_reverse(array_slice($ids, 0, self::MAX_COMMITS)), 'truncated' => count($ids) > self::MAX_COMMITS];
90 }
91
92 /**
93 * プルリクエストを作る
94 *
95 * @param array $head branch・fork:owner、name、branch。agit:user、topic
96 * @param array $opt labels、assignees、milestone
97 */
98 public static function open(string $owner, string $name, array $author, string $title, string $body, string $base, string $kind, array $head, string $headId, array $opt = []): Result {
99 $meta = Gitler::meta($owner, $name);
100 if (!$meta['pulls']) return Result::Error('このリポジトリではプルリクエストは使えません。');
101 if ($meta['archived']) return Result::Error('アーカイブされたリポジトリです(読むだけ)。');
102 $repo = Gitler::open($owner, $name);
103 $baseId = $repo->refs->resolve('refs/heads/'.$base);
104 if ($baseId === null) return Result::Error("ブランチ「{$base}」が有りません。");
105 if (!$repo->objects->exists($headId)) return Result::Error('コミットが有りません。');
106 if (empty(self::compare($repo, $baseId, $headId)['commits'])) return Result::Error("「{$base}」に無いコミットが有りません。");
107 $issues = new Issues($repo);
108 foreach ($issues->search(['pull' => true]) as $s) {
109 $p = $issues->get($s['number'])['pull'] ?? null;
110 if ($p !== null && $p['kind'] === $kind && $p['head'] === $head && $p['base'] === $base) return Result::Error("同じプルリクエスト#{$s['number']}が有ります。", ['number' => $s['number']]);
111 }
112 $res = $issues->create($author, $title, $body, $opt + ['pull' => ['kind' => $kind, 'base' => $base, 'head' => $head, 'headId' => $headId, 'baseId' => $baseId, 'merged' => null]]);
113 if (!$res->isSuccess) return $res;
114 $repo->refs->update(self::ref($res->data['number']), $headId);
115 Federation::issueOpened($owner, $name, $meta, $res->data['issue']);
116 Notify::issueOpened($owner, $name, $meta, $issues, $res->data['issue']);
117 return $res;
118 }
119
120 /** 新しいコミット(refs/pull/N/headと出来事) */
121 public static function setHead(Repository $repo, Issues $issues, int $n, string $new, array $by): ?array {
122 $issue = $issues->get($n);
123 if ($issue === null || !isset($issue['pull']) || $issue['pull']['headId'] === $new) return null;
124 $old = $issue['pull']['headId'];
125 $count = count((new Walk($repo))->commitsBetween([$new], [$old])[0]);
126 $repo->refs->update(self::ref($n), $new);
127 return $issues->update($n, function(array $i) use ($old, $new, $count, $by): array {
128 $i['pull']['headId'] = $new;
129 $i['events'][] = ['type' => 'pushed', 'by' => $by, 'at' => time(), 'from' => $old, 'to' => $new, 'count' => $count];
130 return $i;
131 });
132 }
133
134 /** フォーク等の他のリポジトリからコミット(と必要なオブジェクト)を持って来る */
135 public static function fetch(Repository $from, Repository $to, string $id): void {
136 if ($to->objects->exists($id)) return;
137 $haves = [];
138 foreach (array_merge($to->refs->all('refs/heads/'), $to->refs->all('refs/tags/')) as $h) {
139 // 注釈付きタグはコミットにする
140 $c = $from->objects->exists($h) ? $from->peel($h, 'commit') : null;
141 if ($c !== null) $haves[$c] = true;
142 }
143 $haves = array_keys($haves);
144 $objects = (new Walk($from))->objects([$id], $haves);
145 $tmp = fopen('php://temp', 'w+b');
146 try {
147 (new PackWriter($from))->write($objects, function(string $b) use ($tmp): void {
148 fwrite($tmp, $b);
149 });
150 rewind($tmp);
151 (new PackIndexer($to))->receive($tmp);
152 } finally {
153 fclose($tmp);
154 }
155 }
156
157 //////// マージ
158
159 /**
160 * マージ出来るか
161 *
162 * @return array state(merged、closed、uptodate(既に入っている)、ff、clean、conflict、nobase)、conflicts、baseId
163 */
164 public static function mergeability(Repository $repo, array $issue): array {
165 $p = $issue['pull'];
166 if (!empty($p['merged'])) return ['state' => 'merged', 'conflicts' => [], 'baseId' => null];
167 if ($issue['state'] === 'closed') return ['state' => 'closed', 'conflicts' => [], 'baseId' => null];
168 $baseId = $repo->refs->resolve('refs/heads/'.$p['base']);
169 if ($baseId === null) return ['state' => 'nobase', 'conflicts' => [], 'baseId' => null];
170 $walk = new Walk($repo);
171 if ($walk->isAncestor($p['headId'], $baseId)) return ['state' => 'uptodate', 'conflicts' => [], 'baseId' => $baseId];
172 if ($walk->isAncestor($baseId, $p['headId'])) return ['state' => 'ff', 'conflicts' => [], 'baseId' => $baseId];
173 $mb = $walk->mergeBase($baseId, $p['headId']);
174 $r = Merge::trees($repo, $mb !== null ? $repo->commit($mb)->tree : null, $repo->commit($baseId)->tree, $repo->commit($p['headId'])->tree);
175 return ['state' => $r['tree'] !== null ? 'clean' : 'conflict', 'conflicts' => $r['conflicts'], 'baseId' => $baseId];
176 }
177
178 /**
179 * マージする
180 *
181 * @param string $method merge(マージコミット)、squash、rebase(出来ればfast-forward)
182 * @param \stdClass $user マージする人(コミッター)
183 */
184 public static function merge(string $owner, string $name, int $n, \stdClass $user, string $method, string $message): Result {
185 $repo = Gitler::open($owner, $name);
186 $issues = new Issues($repo);
187 $issue = $issues->get($n);
188 if ($issue === null || !isset($issue['pull'])) return Result::Error('プルリクエストが有りません。');
189 $m = self::mergeability($repo, $issue);
190 if (in_array($m['state'], ['merged', 'closed', 'nobase', 'uptodate'], true)) return Result::Error('マージ出来ません。');
191 if (!in_array($method, ['merge', 'squash', 'rebase'], true)) return Result::Error('マージの方法が不正です。');
192 $p = $issue['pull'];
193 $baseId = $m['baseId'];
194 $head = $p['headId'];
195 $me = self::person($user);
196 $message = trim(str_replace("\r\n", "\n", $message));
197 $walk = new Walk($repo);
198 $mb = $walk->mergeBase($baseId, $head);
199 if ($method === 'rebase') {
200 if ($m['state'] === 'ff') {
201 $new = $head;
202 } else {
203 $new = $baseId;
204 foreach (self::compare($repo, $baseId, $head)['commits'] as $id) {
205 $c = $repo->commit($id);
206 if (count($c->parents) > 1) return Result::Error('マージコミットが有るのでリベース出来ません。');
207 $tree = Merge::pick($repo, $id, $new);
208 if ($tree === null) return Result::Error('コンフリクトが有るのでリベース出来ません。');
209 $new = $repo->writeCommit(Commit::create($tree, [$new], $c->author ?? $me, $me, $c->message));
210 }
211 }
212 } else {
213 if ($m['state'] === 'conflict') return Result::Error('コンフリクトが有ります。');
214 $tree = Merge::trees($repo, $mb !== null ? $repo->commit($mb)->tree : null, $repo->commit($baseId)->tree, $repo->commit($head)->tree)['tree'];
215 if ($tree === null) return Result::Error('コンフリクトが有ります。');
216 if ($method === 'merge') {
217 $msg = $message !== '' ? $message : "Merge pull request #{$n}\n\n{$issue['title']}";
218 $new = $repo->writeCommit(Commit::create($tree, [$baseId, $head], $me, $me, $msg."\n"));
219 } else {
220 $subjects = array_map(fn($id) => '* '.$repo->commit($id)->subject(), self::compare($repo, $baseId, $head)['commits']);
221 $msg = $message !== '' ? $message : "{$issue['title']} (#{$n})\n\n".implode("\n", $subjects);
222 $author = isset($issue['author']['user']) && ($u = Gitler::user((string)$issue['author']['user'])) !== null ? self::person($u) : $me;
223 $new = $repo->writeCommit(Commit::create($tree, [$baseId], $author, $me, $msg."\n"));
224 }
225 }
226 try {
227 $repo->refs->update('refs/heads/'.$p['base'], $new, $baseId);
228 } catch (GitException) {
229 return Result::Error('ブランチが変わりました。もう一度お試し下さい。');
230 }
231 $by = ['user' => (string)$user->username];
232 $merged = self::markMerged($owner, $name, $issues, $n, $by, $new, $method, $baseId);
233 // マージで入ったコミットとプルリクエストの本文の「fixes #3」でイシューを閉じる
234 self::afterBaseUpdate($owner, $name, $repo, $issues, 'refs/heads/'.$p['base'], $baseId, $new, $by);
235 $meta = Gitler::meta($owner, $name);
236 foreach ($issues->processPush([['refs/heads/'.$p['base'], $baseId, $new]], $repo->headRef() ?? '') as $x) {
237 $closed = $issues->get($x);
238 if ($closed === null) continue;
239 Federation::stateChanged($owner, $name, $meta, $closed);
240 Notify::stateChanged($owner, $name, $meta, $closed, end($closed['events'])['by'] ?? $by);
241 }
242 if (preg_match_all('/\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s*:?\s+#(\d+)\b/i', $issue['body'], $cm) && 'refs/heads/'.$p['base'] === ($repo->headRef() ?? '')) {
243 foreach (array_unique(array_map('intval', $cm[1])) as $x) {
244 $target = $issues->get($x);
245 if ($target === null || isset($target['pull'])) continue;
246 $closed = $issues->setState($x, false, $by, ['pull' => $n]);
247 if ($closed !== null) {
248 Federation::stateChanged($owner, $name, Gitler::meta($owner, $name), $closed);
249 Notify::stateChanged($owner, $name, Gitler::meta($owner, $name), $closed, $by);
250 }
251 }
252 }
253 return Result::Success('マージしました。', ['commit' => $new, 'issue' => $merged]);
254 }
255
256 /**
257 * マージした事にする(閉じて、出来事を記録して、通知する)
258 *
259 * @param string $before マージする前のマージ先(コミットと変更の表示に使う)
260 */
261 public static function markMerged(string $owner, string $name, Issues $issues, int $n, array $by, string $commit, string $method, string $before): ?array {
262 $issue = $issues->update($n, function(array $i) use ($by, $commit, $method, $before): ?array {
263 if (!isset($i['pull']) || !empty($i['pull']['merged'])) return null;
264 $i['pull']['merged'] = ['by' => $by, 'at' => time(), 'commit' => $commit, 'method' => $method, 'before' => $before];
265 $i['state'] = 'closed';
266 $i['closed'] = time();
267 $i['events'][] = ['type' => 'merged', 'by' => $by, 'at' => time(), 'commit' => $commit, 'base' => $i['pull']['base'], 'method' => $method];
268 return $i;
269 });
270 if ($issue !== null) {
271 $meta = Gitler::meta($owner, $name);
272 Federation::stateChanged($owner, $name, $meta, $issue);
273 Notify::merged($owner, $name, $meta, $issue, $by);
274 }
275 return $issue;
276 }
277
278 /** ブランチが進んだ:入ったプルリクエストをマージ済みにする */
279 private static function afterBaseUpdate(string $owner, string $name, Repository $repo, Issues $issues, string $ref, string $old, string $new, array $by): void {
280 $walk = new Walk($repo);
281 foreach ($issues->search(['pull' => true]) as $s) {
282 $i = $issues->get($s['number']);
283 if ($i === null || 'refs/heads/'.$i['pull']['base'] !== $ref || !$repo->objects->exists($i['pull']['headId'])) continue;
284 if ($walk->isAncestor($i['pull']['headId'], $new)) self::markMerged($owner, $name, $issues, $s['number'], $by, $new, 'manual', $old);
285 }
286 }
287
288 //////// プッシュ
289
290 /**
291 * refs/for/ へのプッシュを受け付けるか(ReceivePackのupdate)
292 *
293 * @return string|null エラー
294 */
295 public static function checkAgit(string $owner, string $name, ?\stdClass $user, string $ref, string $new, string $zero): ?string {
296 $meta = Gitler::meta($owner, $name);
297 if (!$meta['pulls'] || $meta['archived'] || $user === null || !Gitler::userCan($user, 'pulls') || Gitler::access($user, $owner, $name) < Gitler::READ) {
298 return 'pull requests are not allowed';
299 }
300 if ($new === $zero) return 'cannot delete';
301 return self::parseAgit(Gitler::open($owner, $name), $ref) === null ? 'use refs/for/<branch>/<topic>' : null;
302 }
303
304 /**
305 * プッシュの後(ReceivePackのprocess):AGitのプルリクエスト、ブランチのプルリクエストの更新、マージの検出
306 *
307 * @param array $updates [参照, 前, 後]
308 * @return array クライアントに表示する行
309 */
310 public static function afterPush(string $owner, string $name, ?\stdClass $user, array $updates): array {
311 $repo = Gitler::open($owner, $name);
312 $meta = Gitler::meta($owner, $name);
313 $zero = $repo->zeroId();
314 $issues = new Issues($repo);
315 $by = $user !== null ? ['user' => (string)$user->username] : [];
316 $base = rtrim((string)(SITEINFO['url'] ?? ''), '/') ?: Fedi::base();
317 $out = [];
318 foreach ($updates as [$ref, $old, $new]) {
319 try {
320 if (str_starts_with($ref, 'refs/for/')) {
321 $out = array_merge($out, self::agit($owner, $name, $repo, $issues, $user, $ref, $new, $base));
322 continue;
323 }
324 if (!str_starts_with($ref, 'refs/heads/') || $new === $zero) continue;
325 $branch = substr($ref, 11);
326 // このリポジトリのブランチからのプルリクエスト
327 foreach ($issues->search(['pull' => true]) as $s) {
328 $p = $issues->get($s['number'])['pull'] ?? null;
329 if ($p !== null && $p['kind'] === 'branch' && $p['head']['branch'] === $branch) self::setHead($repo, $issues, $s['number'], $new, $by);
330 }
331 // フォーク元へのプルリクエスト
332 if ($meta['forkOf'] !== '') {
333 [$po, $pn] = explode('/', $meta['forkOf'], 2);
334 if (Gitler::exists($po, $pn)) {
335 $parent = Gitler::open($po, $pn);
336 $pi = new Issues($parent);
337 foreach ($pi->search(['pull' => true]) as $s) {
338 $p = $pi->get($s['number'])['pull'] ?? null;
339 if ($p === null || $p['kind'] !== 'fork' || $p['head'] !== ['owner' => $owner, 'name' => $name, 'branch' => $branch]) continue;
340 self::fetch($repo, $parent, $new);
341 self::setHead($parent, $pi, $s['number'], $new, $by);
342 }
343 }
344 }
345 // マージ先が進んだ
346 self::afterBaseUpdate($owner, $name, $repo, $issues, $ref, $old, $new, $by);
347 // 新しいブランチ:プルリクエストを作るURL(フォークならフォーク元に)
348 if ($old === $zero && $ref !== $repo->headRef() && $user !== null && Gitler::userCan($user, 'pulls')) {
349 [$po, $pn] = $meta['forkOf'] !== '' ? explode('/', $meta['forkOf'], 2) : ['', ''];
350 if ($po !== '' && Gitler::exists($po, $pn) && Gitler::meta($po, $pn)['pulls']) {
351 $out[] = 'プルリクエストを作る:'.$base.'/gitler/'.$po.'/'.rawurlencode($pn).'/compare?head='.rawurlencode("{$owner}/{$name}:{$branch}");
352 } else if ($meta['pulls'] && !$meta['archived']) {
353 $out[] = 'プルリクエストを作る:'.$base.'/gitler/'.$owner.'/'.rawurlencode($name).'/compare?head='.rawurlencode($branch);
354 }
355 }
356 } catch (\Throwable $e) {
357 @error_log('Gitler: '.$e->getMessage());
358 }
359 }
360 return $out;
361 }
362
363 /** refs/for/<ブランチ>/<トピック>(ブランチは一番長い有る物) */
364 public static function parseAgit(Repository $repo, string $ref): ?array {
365 $rest = substr($ref, 9);
366 $parts = explode('/', $rest);
367 for ($k = count($parts) - 1; $k >= 1; $k--) {
368 $branch = implode('/', array_slice($parts, 0, $k));
369 $topic = implode('/', array_slice($parts, $k));
370 if ($repo->refs->resolve('refs/heads/'.$branch) !== null && preg_match(self::TOPIC_RE, $topic)) return [$branch, $topic];
371 }
372 return null;
373 }
374
375 private static function agit(string $owner, string $name, Repository $repo, Issues $issues, ?\stdClass $user, string $ref, string $new, string $site): array {
376 $parsed = self::parseAgit($repo, $ref);
377 if ($parsed === null || $user === null) return [];
378 [$branch, $topic] = $parsed;
379 $head = ['user' => (string)$user->username, 'topic' => $topic];
380 $by = ['user' => (string)$user->username];
381 $url = fn(int $n) => $site.'/gitler/'.$owner.'/'.rawurlencode($name).'/pulls/'.$n;
382 foreach ($issues->search(['pull' => true]) as $s) {
383 $p = $issues->get($s['number'])['pull'] ?? null;
384 if ($p === null || $p['kind'] !== 'agit' || $p['head'] !== $head || $p['base'] !== $branch) continue;
385 self::setHead($repo, $issues, $s['number'], $new, $by);
386 return ["プルリクエスト#{$s['number']}を更新しました:".$url($s['number'])];
387 }
388 // 題名と本文は最初のコミットから
389 $baseId = $repo->refs->resolve('refs/heads/'.$branch);
390 $commits = $baseId !== null ? self::compare($repo, $baseId, $new)['commits'] : [];
391 if (empty($commits)) return ["「{$branch}」に無いコミットが有りません。"];
392 $first = $repo->commit($commits[0]);
393 $body = count($commits) === 1 ? trim(substr($first->message, strlen($first->subject()))) : implode("\n", array_map(fn($id) => '* '.$repo->commit($id)->subject(), $commits));
394 $res = self::open($owner, $name, $by, $first->subject(), $body, $branch, 'agit', $head, $new);
395 return $res->isSuccess ? ["プルリクエスト#{$res->data['number']}を作りました:".$url($res->data['number'])] : [(string)$res->message];
396 }
397
398 /** コミットの名前とメールアドレス(メールアドレスは公開しない) */
399 public static function person(\stdClass $u): Person {
400 $host = (string)parse_url(rtrim((string)(SITEINFO['url'] ?? ''), '/') ?: Fedi::base(), PHP_URL_HOST) ?: 'localhost';
401 return Person::now(($u->displayname ?? '') !== '' ? (string)$u->displayname : (string)$u->username, $u->username.'@users.noreply.'.$host);
402 }
403}