master
ブランチ master
LittleBeast / src / Std / Lib / Git / Repository.php
16.1 KB、382行 生 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\Git;
39
40/**
41 * Gitのリポジトリ(純粋なPHP、zlibが必要)
42 *
43 * ベア(例:/var/www/git/user/repo.git)又は作業ディレクトリの.git。SHA-1とSHA-256のリポジトリに対応。
44 *
45 * $repo = Repository::init(ROOT.'/data/test.git');
46 * $blob = $repo->writeBlob("こんにちは\n");
47 * $tree = $repo->writeTree([[Tree::FILE, 'README.md', $blob]]);
48 * $me = Person::now('諏訪子', 'suwako@example.com');
49 * $commit = $repo->writeCommit(Commit::create($tree, [], $me, $me, "最初のコミット\n"));
50 * $repo->refs->update('refs/heads/main', $commit, $repo->zeroId());
51 * foreach ($repo->log('main') as $c) echo $c->subject(), "\n";
52 */
53final class Repository {
54 public readonly string $path;
55 /** sha1又はsha256 */
56 public readonly string $hashAlgo;
57 /** IDのバイト数(20又は32) */
58 public readonly int $hashLen;
59 /** 16進数のIDの長さ(40又は64) */
60 public readonly int $hexLen;
61 public readonly Config $config;
62 public readonly ObjectDb $objects;
63 public readonly Refs $refs;
64 private ?int $fileMode = null;
65 private ?int $dirMode = null;
66
67 private function __construct(string $path) {
68 $this->path = rtrim(str_replace('\\', '/', $path), '/');
69 $this->config = new Config($this->path.'/config');
70 $format = strtolower((string)$this->config->get('extensions.objectformat', 'sha1'));
71 if (!in_array($format, ['sha1', 'sha256'], true)) throw new GitException("未対応のオブジェクトの形式:{$format}");
72 $version = $this->config->getInt('core.repositoryformatversion', 0);
73 if ($version > 1) throw new GitException("未対応のリポジトリの形式:{$version}");
74 $this->hashAlgo = $format;
75 $this->hashLen = $format === 'sha1' ? 20 : 32;
76 $this->hexLen = $this->hashLen * 2;
77 // core.sharedRepository(group:グループも書ける、all:皆が読める、0xxx)
78 $shared = strtolower((string)$this->config->get('core.sharedrepository', ''));
79 if (in_array($shared, ['group', 'true', '1'], true)) [$this->fileMode, $this->dirMode] = [0664, 02775];
80 else if (in_array($shared, ['all', 'world', 'everybody', '2'], true)) [$this->fileMode, $this->dirMode] = [0664, 02775];
81 else if (preg_match('/^0[0-7]{3}$/', $shared)) [$this->fileMode, $this->dirMode] = [octdec($shared), octdec($shared) | 0111 | 02000];
82 $this->objects = new ObjectDb($this);
83 $this->refs = new Refs($this);
84 }
85
86 /**
87 * リポジトリを開く
88 *
89 * @param string $path ベアのリポジトリ、又は.gitの有るディレクトリ
90 */
91 public static function open(string $path): self {
92 if (is_dir($path.'/.git')) $path .= '/.git';
93 if (!is_dir($path.'/objects') || !is_file($path.'/HEAD')) throw new GitException("Gitのリポジトリではありません:{$path}");
94 return new self($path);
95 }
96
97 public static function isRepository(string $path): bool {
98 return is_dir($path.'/objects') && is_file($path.'/HEAD') && is_dir($path.'/refs');
99 }
100
101 /**
102 * ベアのリポジトリを作る
103 *
104 * @param string $path ディレクトリ(無ければ作る、空でなければならない)
105 * @param string $objectFormat sha1又はsha256
106 * @param string $branch 最初のブランチ(HEADの先)
107 * @param string|null $shared core.sharedRepository(例:group。SSHのgitユーザーとphp-fpmで共有する場合)
108 */
109 public static function init(string $path, string $objectFormat = 'sha1', string $branch = 'main', ?string $shared = null, string $description = ''): self {
110 if (!in_array($objectFormat, ['sha1', 'sha256'], true)) throw new GitException("未対応のオブジェクトの形式:{$objectFormat}");
111 if (!Refs::validName('refs/heads/'.$branch)) throw new GitException("不正なブランチの名前:{$branch}");
112 if (is_dir($path) && count(array_diff(scandir($path) ?: [], ['.', '..'])) > 0) throw new GitException("ディレクトリが空ではありません:{$path}");
113 $dirMode = $shared !== null ? 02775 : 0777;
114 if (!is_dir($path) && !@mkdir($path, $dirMode, true) && !is_dir($path)) throw new GitException("ディレクトリを作れません:{$path}");
115 if ($shared !== null) @chmod($path, 02775);
116 $c = Config::fromString('');
117 $c->set('core.repositoryformatversion', $objectFormat === 'sha256' ? '1' : '0');
118 $c->set('core.filemode', 'true');
119 $c->set('core.bare', 'true');
120 if ($shared !== null) $c->set('core.sharedrepository', $shared);
121 if ($objectFormat === 'sha256') $c->set('extensions.objectformat', 'sha256');
122 // receive-packでの確認
123 $c->set('receive.fsckobjects', 'true');
124 if (@file_put_contents($path.'/config', $c->toString()) === false) throw new GitException("リポジトリを作れません:{$path}");
125 $repo = new self($path);
126 foreach (['objects/info', 'objects/pack', 'refs/heads', 'refs/tags', 'info', 'hooks'] as $d) $repo->mkdir($repo->path.'/'.$d);
127 $repo->writeFile($repo->path.'/HEAD', "ref: refs/heads/{$branch}\n");
128 $repo->writeFile($repo->path.'/description', $description !== '' ? $description."\n" : "Unnamed repository; edit this file 'description' to name the repository.\n");
129 $repo->chmodFile($repo->path.'/config');
130 return $repo;
131 }
132
133 //////// ID
134
135 /** 0ばかりのID(「無い」) */
136 public function zeroId(): string {
137 return str_repeat('0', $this->hexLen);
138 }
139
140 public function isId(string $s): bool {
141 return strlen($s) === $this->hexLen && ctype_xdigit($s);
142 }
143
144 /** オブジェクトのID(16進数) */
145 public function hashObject(string $type, string $data): string {
146 return hash($this->hashAlgo, $type.' '.strlen($data)."\0".$data);
147 }
148
149 //////// 読む
150
151 public function commit(string $id): Commit {
152 return Commit::parse($this->objects->get($id, 'commit'), $id);
153 }
154
155 public function tree(string $id): Tree {
156 return Tree::parse($this->objects->get($id, 'tree'), $this->hashLen, $id);
157 }
158
159 public function tag(string $id): Tag {
160 return Tag::parse($this->objects->get($id, 'tag'), $id);
161 }
162
163 public function blob(string $id): string {
164 return $this->objects->get($id, 'blob');
165 }
166
167 /** 注釈付きタグを剥く(タグの先のオブジェクト) */
168 public function peel(string $id, ?string $want = null): ?string {
169 for ($i = 0; $i < 100; $i++) {
170 $o = $this->objects->info($id);
171 if ($o === null) return null;
172 if ($o[0] !== 'tag' || $want === 'tag') return $want === null || $o[0] === $want ? $id : null;
173 $id = $this->tag($id)->object;
174 }
175 return null;
176 }
177
178 /** コミットのツリー(ツリーならそのまま、IDでなければリビジョンとして解決) */
179 public function treeOf(string $id): ?string {
180 if (!$this->isId($id)) $id = $this->resolve($id) ?? '';
181 $id = $id === '' ? null : $this->peel($id);
182 if ($id === null) return null;
183 $t = $this->objects->info($id)[0] ?? null;
184 if ($t === 'tree') return $id;
185 return $t === 'commit' ? $this->commit($id)->tree : null;
186 }
187
188 /**
189 * ツリーの中のパスのエントリー
190 *
191 * @param string $treeish コミット又はツリー(IDかリビジョン)
192 * @param string $path 「src/a.php」(空ならルートのツリー)
193 * @return array|null [mode, name, id]
194 */
195 public function entry(string $treeish, string $path): ?array {
196 $tree = $this->treeOf($treeish);
197 if ($tree === null) return null;
198 $path = trim($path, '/');
199 if ($path === '') return [Tree::DIR, '', $tree];
200 $parts = explode('/', $path);
201 $entry = null;
202 foreach ($parts as $i => $part) {
203 $entry = $this->tree($tree)->find($part);
204 if ($entry === null) return null;
205 if ($i < count($parts) - 1) {
206 if ($entry[0] !== Tree::DIR) return null;
207 $tree = $entry[2];
208 }
209 }
210 return $entry;
211 }
212
213 /**
214 * リビジョンを解決する(git rev-parseの基本)
215 *
216 * 対応:完全・短いID、参照の名前(HEAD、main、v1.0、refs/...)、rev^、rev^2、rev~3、rev^{tree}、rev^{commit}、rev:パス
217 *
218 * @return string|null ID
219 */
220 public function resolve(string $rev): ?string {
221 $rev = trim($rev);
222 if ($rev === '') return null;
223 // rev:パス
224 if (preg_match('/^([^:]*):(.*)$/s', $rev, $m) && !preg_match('#^[A-Za-z]:[\\\\/]#', $rev)) {
225 $base = $this->resolve($m[1] === '' ? 'HEAD' : $m[1]);
226 if ($base === null) return null;
227 return $this->entry($base, $m[2])[2] ?? null;
228 }
229 if (!preg_match('/^(.*?)((?:\^\{[a-z]*\}|\^\d*|~\d*)*)$/s', $rev, $m)) return null;
230 $id = $this->resolveName($m[1]);
231 if ($id === null) return null;
232 preg_match_all('/\^\{([a-z]*)\}|\^(\d*)|~(\d*)/', $m[2], $ops, PREG_SET_ORDER);
233 foreach ($ops as $op) {
234 if (isset($op[1]) && $op[1] !== '' || str_starts_with($op[0], '^{')) {
235 $id = $op[1] === '' ? $this->peel($id) : ($op[1] === 'object' ? $id : $this->peelTo($id, $op[1]));
236 } else if (str_starts_with($op[0], '^')) {
237 $n = $op[2] === '' ? 1 : (int)$op[2];
238 $c = $this->peel($id, 'commit');
239 if ($c === null) return null;
240 $id = $n === 0 ? $c : ($this->commit($c)->parents[$n - 1] ?? null);
241 } else {
242 $n = ($op[3] ?? '') === '' ? 1 : (int)$op[3];
243 for ($i = 0; $i < $n && $id !== null; $i++) {
244 $c = $this->peel($id, 'commit');
245 $id = $c === null ? null : ($this->commit($c)->parents[0] ?? null);
246 }
247 }
248 if ($id === null) return null;
249 }
250 return $id;
251 }
252
253 private function peelTo(string $id, string $type): ?string {
254 $id = $type === 'tag' ? $id : $this->peel($id);
255 if ($id === null) return null;
256 if ($type === 'tree') return $this->treeOf($id);
257 return ($this->objects->info($id)[0] ?? null) === $type ? $id : null;
258 }
259
260 private function resolveName(string $name): ?string {
261 if ($name === '') $name = 'HEAD';
262 if ($name === '@') $name = 'HEAD';
263 $full = $this->refs->dwim($name);
264 if ($full !== null) return $this->refs->resolve($full);
265 if (preg_match('/^[0-9a-fA-F]{4,}$/', $name)) return $this->objects->resolvePrefix($name);
266 return null;
267 }
268
269 /** HEADの先のブランチ(例:refs/heads/main) */
270 public function headRef(): ?string {
271 return $this->refs->symbolic('HEAD');
272 }
273
274 /** 空のリポジトリか(コミットが1つも無い) */
275 public function isEmpty(): bool {
276 return empty($this->refs->all('refs/'));
277 }
278
279 //////// 書く
280
281 public function writeBlob(string $data): string {
282 return $this->objects->write('blob', $data);
283 }
284
285 /** @param array $entries [mode, name, id] */
286 public function writeTree(array $entries): string {
287 return $this->objects->write('tree', Tree::create($entries)->toString());
288 }
289
290 public function writeCommit(Commit $c): string {
291 if (!$this->isId($c->tree)) throw new GitException('不正なツリーのID');
292 return $c->id = $this->objects->write('commit', $c->toString());
293 }
294
295 public function writeTag(Tag $t): string {
296 return $t->id = $this->objects->write('tag', $t->toString());
297 }
298
299 /**
300 * ツリーのファイルを変えた新しいツリー(Webでの編集用)
301 *
302 * @param string|null $tree 元のツリー(nullなら空)
303 * @param array $changes パス => [mode, 内容(文字列)] 又はnull(削除)
304 * @return string 新しいツリーのID
305 */
306 public function updateTree(?string $tree, array $changes): string {
307 return $this->changeTree($tree, $changes) ?? $this->writeTree([]);
308 }
309
310 /** @return string|null 空になったらnull */
311 private function changeTree(?string $tree, array $changes): ?string {
312 $byDir = [];
313 foreach ($changes as $path => $change) {
314 $path = trim(str_replace('\\', '/', (string)$path), '/');
315 if ($path === '') throw new GitException('不正なパス');
316 $parts = explode('/', $path);
317 $name = array_shift($parts);
318 if (empty($parts)) $byDir[''][$name] = $change;
319 else $byDir[$name][implode('/', $parts)] = $change;
320 }
321 $entries = [];
322 foreach ($tree !== null ? $this->tree($tree)->entries : [] as $e) $entries[$e[1]] = $e;
323 foreach ($byDir[''] ?? [] as $name => $change) {
324 if ($change === null) unset($entries[$name]);
325 else $entries[$name] = [$change[0], $name, $this->writeBlob((string)$change[1])];
326 }
327 unset($byDir['']);
328 foreach ($byDir as $dir => $sub) {
329 $old = isset($entries[$dir]) && $entries[$dir][0] === Tree::DIR ? $entries[$dir][2] : null;
330 $new = $this->changeTree($old, $sub);
331 if ($new === null) unset($entries[$dir]);
332 else $entries[$dir] = [Tree::DIR, $dir, $new];
333 }
334 return empty($entries) ? null : $this->writeTree(array_values($entries));
335 }
336
337 //////// 履歴
338
339 /**
340 * コミットの履歴(新しい順)
341 *
342 * @param string|array $from リビジョン(複数可)
343 * @param array $opt path(そのパスを変えたコミットだけ)、limit、skip、not(除くリビジョン)、firstParent
344 * @return \Generator Commit
345 */
346 public function log(string|array $from, array $opt = []): \Generator {
347 yield from (new Walk($this))->log((array)$from, $opt);
348 }
349
350 //////// ファイル
351
352 public function mkdir(string $dir): void {
353 if (is_dir($dir)) return;
354 $this->mkdir(dirname($dir));
355 if (!@mkdir($dir, $this->dirMode ?? 0777) && !is_dir($dir)) throw new GitException("ディレクトリを作れません:{$dir}");
356 if ($this->dirMode !== null) @chmod($dir, $this->dirMode);
357 }
358
359 /** 一時ファイルに書いてから置き換える */
360 public function writeFile(string $file, string $data, bool $readOnly = false): void {
361 $tmp = $file.'.'.bin2hex(random_bytes(4)).'.tmp';
362 if (@file_put_contents($tmp, $data) === false) throw new GitException("ファイルに書けません:{$file}");
363 $this->chmodFile($tmp, $readOnly);
364 if (!@rename($tmp, $file)) {
365 // Windowsでは有るファイルに名前を変えられない場合が有る
366 if (!$readOnly || !is_file($file)) {
367 @unlink($file);
368 if (!@rename($tmp, $file)) {
369 @unlink($tmp);
370 throw new GitException("ファイルに書けません:{$file}");
371 }
372 } else {
373 @unlink($tmp);
374 }
375 }
376 }
377
378 public function chmodFile(string $file, bool $readOnly = false): void {
379 if ($this->fileMode !== null) @chmod($file, $readOnly ? $this->fileMode & 0444 : $this->fileMode);
380 else if ($readOnly) @chmod($file, 0444 & ~umask());
381 }
382}