master
ブランチ master
LittleBeast / src / Std / Lib / Git / Refs.php
10.8 KB、277行 生 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 * 参照(HEAD、refs/heads/、refs/tags/等):ルーズとpacked-refs
42 *
43 * 変更はロックファイル(.lock)で行い、古い値を確かめられる(他の更新と競合しない様に)。
44 */
45final class Refs {
46 private ?array $packed = null;
47 private ?array $peeled = null;
48
49 public function __construct(private Repository $repo) {}
50
51 /** 参照の名前が正しいか(git check-ref-format) */
52 public static function validName(string $name): bool {
53 if ($name === 'HEAD') return true;
54 if (!str_starts_with($name, 'refs/') || str_ends_with($name, '/') || str_ends_with($name, '.') || str_ends_with($name, '.lock')) return false;
55 if (preg_match('#[\x00-\x20\x7f~^:?*\[\\\\]|\.\.|//|@\{|/\.|^\.#', $name)) return false;
56 foreach (explode('/', $name) as $part) if ($part === '' || $part[0] === '.') return false;
57 return $name !== '@';
58 }
59
60 private function packed(): array {
61 if ($this->packed !== null) return $this->packed;
62 $this->packed = [];
63 $this->peeled = [];
64 $file = $this->repo->path.'/packed-refs';
65 if (!is_file($file)) return $this->packed;
66 $last = null;
67 foreach (preg_split('/\r?\n/', (string)file_get_contents($file)) as $line) {
68 if ($line === '' || $line[0] === '#') continue;
69 if ($line[0] === '^') {
70 if ($last !== null) $this->peeled[$last] = substr($line, 1);
71 continue;
72 }
73 $sp = strpos($line, ' ');
74 if ($sp === false) continue;
75 $last = substr($line, $sp + 1);
76 $this->packed[$last] = substr($line, 0, $sp);
77 }
78 return $this->packed;
79 }
80
81 /**
82 * 参照の中身(解決しない)
83 *
84 * @return string|null ID又は「ref: 名前」
85 */
86 public function readRaw(string $name): ?string {
87 if (!self::validName($name)) return null;
88 $file = $this->repo->path.'/'.$name;
89 if (is_file($file)) {
90 $v = trim((string)file_get_contents($file));
91 return $v === '' ? null : $v;
92 }
93 return $this->packed()[$name] ?? null;
94 }
95
96 /** シンボリック参照の先(HEAD → refs/heads/main)、シンボリックでなければnull */
97 public function symbolic(string $name): ?string {
98 $v = $this->readRaw($name);
99 return $v !== null && str_starts_with($v, 'ref: ') ? trim(substr($v, 5)) : null;
100 }
101
102 /**
103 * 参照をIDに解決する(シンボリック参照を辿る)
104 */
105 public function resolve(string $name): ?string {
106 for ($i = 0; $i < 10; $i++) {
107 $v = $this->readRaw($name);
108 if ($v === null) return null;
109 if (!str_starts_with($v, 'ref: ')) return $this->repo->isId($v) ? strtolower($v) : null;
110 $name = trim(substr($v, 5));
111 }
112 return null;
113 }
114
115 /**
116 * 短い名前(main、v1.0、origin/main)を完全な名前にする
117 */
118 public function dwim(string $short): ?string {
119 foreach ([$short, "refs/{$short}", "refs/tags/{$short}", "refs/heads/{$short}", "refs/remotes/{$short}", "refs/remotes/{$short}/HEAD"] as $n) {
120 if ($this->readRaw($n) !== null) return $n;
121 }
122 return null;
123 }
124
125 /**
126 * 全部の参照(HEADを除く、名前の順)
127 *
128 * @param string $prefix 名前の始まり(例:refs/heads/)
129 * @return array 名前 => ID
130 */
131 public function all(string $prefix = 'refs/'): array {
132 $out = [];
133 foreach ($this->packed() as $name => $id) if (str_starts_with($name, $prefix)) $out[$name] = $id;
134 $base = $this->repo->path.'/';
135 $dir = $base.rtrim(str_contains($prefix, '/') ? substr($prefix, 0, strrpos($prefix, '/')) : $prefix, '/');
136 if (is_dir($dir)) {
137 $it = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS));
138 foreach ($it as $f) {
139 if (!$f->isFile()) continue;
140 $name = str_replace('\\', '/', substr($f->getPathname(), strlen($base)));
141 if (!str_starts_with($name, $prefix) || !self::validName($name)) continue;
142 $v = trim((string)file_get_contents($f->getPathname()));
143 if (str_starts_with($v, 'ref: ')) {
144 $r = $this->resolve($name);
145 if ($r !== null) $out[$name] = $r;
146 } else if ($this->repo->isId($v)) {
147 $out[$name] = strtolower($v);
148 }
149 }
150 }
151 ksort($out, SORT_STRING);
152 return $out;
153 }
154
155 /** packed-refsの剥いた値(注釈付きタグの先)。無ければnull */
156 public function peeledFromPack(string $name): ?string {
157 $this->packed();
158 return $this->peeled[$name] ?? null;
159 }
160
161 /**
162 * 参照を更新する
163 *
164 * @param string $name 参照の名前
165 * @param string|null $new 新しいID(nullなら削除)
166 * @param string|null $old 今のID(確かめる。0ばかりのIDは「無い事」、nullなら確かめない)
167 * @throws GitException 競合した場合等
168 */
169 public function update(string $name, ?string $new, ?string $old = null): void {
170 $this->transaction([[$name, $new, $old]]);
171 }
172
173 /**
174 * 複数の参照を全部更新するか、全部しない
175 *
176 * @param array $updates [名前, 新しいID又はnull, 今のID又はnull]
177 */
178 public function transaction(array $updates): void {
179 $locks = [];
180 $zero = $this->repo->zeroId();
181 try {
182 // HEAD等のシンボリック参照は先を更新する
183 foreach ($updates as $i => [$name, $new, $old]) {
184 $target = $name;
185 for ($d = 0; $d < 10 && ($s = $this->symbolic($target)) !== null; $d++) $target = $s;
186 if (!self::validName($target) || $target === 'HEAD') throw new GitException("不正な参照の名前:{$name}");
187 if ($new !== null && !$this->repo->isId($new)) throw new GitException("不正なID:{$new}");
188 $updates[$i][0] = $target;
189 $lock = $this->repo->path.'/'.$target.'.lock';
190 $this->repo->mkdir(dirname($lock));
191 // ディレクトリと同じ名前の参照(refs/heads/aとrefs/heads/a/b)は作れない
192 if (is_dir($this->repo->path.'/'.$target)) throw new GitException("参照の名前が他の参照と重なります:{$target}");
193 $fh = @fopen($lock, 'x');
194 if ($fh === false) throw new GitException("参照がロックされています:{$target}");
195 $locks[$target] = [$fh, $lock];
196 }
197 $this->packed = null;
198 foreach ($updates as [$name, $new, $old]) {
199 if ($old === null) continue;
200 $cur = $this->resolve($name);
201 if ($old === $zero ? $cur !== null : $cur !== strtolower($old)) throw new GitException("参照が変わっています:{$name}");
202 }
203 $deletes = [];
204 foreach ($updates as [$name, $new]) {
205 [$fh, $lock] = $locks[$name];
206 if ($new === null) {
207 $deletes[] = $name;
208 continue;
209 }
210 fwrite($fh, strtolower($new)."\n");
211 }
212 if (!empty($deletes)) $this->removePacked($deletes);
213 foreach ($updates as [$name, $new]) {
214 [$fh, $lock] = $locks[$name];
215 fclose($fh);
216 $file = $this->repo->path.'/'.$name;
217 if ($new === null) {
218 @unlink($lock);
219 @unlink($file);
220 $this->pruneDirs(dirname($file));
221 } else {
222 if (!@rename($lock, $file)) throw new GitException("参照を書けません:{$name}");
223 $this->repo->chmodFile($file);
224 }
225 unset($locks[$name]);
226 }
227 } finally {
228 foreach ($locks as [$fh, $lock]) {
229 if (is_resource($fh)) fclose($fh);
230 @unlink($lock);
231 }
232 $this->packed = null;
233 }
234 }
235
236 /** packed-refsから消す */
237 private function removePacked(array $names): void {
238 $file = $this->repo->path.'/packed-refs';
239 if (!is_file($file)) return;
240 $lock = $file.'.lock';
241 $fh = @fopen($lock, 'x');
242 if ($fh === false) throw new GitException('packed-refsがロックされています');
243 $out = [];
244 $skip = false;
245 foreach (preg_split('/\r?\n/', (string)file_get_contents($file)) as $line) {
246 if ($line === '') continue;
247 if ($line[0] === '^') {
248 if (!$skip) $out[] = $line;
249 continue;
250 }
251 $sp = strpos($line, ' ');
252 $skip = $sp !== false && $line[0] !== '#' && in_array(substr($line, $sp + 1), $names, true);
253 if (!$skip) $out[] = $line;
254 }
255 fwrite($fh, implode("\n", $out)."\n");
256 fclose($fh);
257 if (!@rename($lock, $file)) {
258 @unlink($lock);
259 throw new GitException('packed-refsを書けません');
260 }
261 }
262
263 /** 空になった参照のディレクトリを消す(refs/heads等は残す) */
264 private function pruneDirs(string $dir): void {
265 $base = $this->repo->path.'/refs';
266 while (strlen($dir) > strlen($base) && !in_array(basename($dir), ['heads', 'tags'], true) && dirname($dir) !== $base) {
267 if (!@rmdir($dir)) break;
268 $dir = dirname($dir);
269 }
270 }
271
272 /** シンボリック参照を設定する(例:HEADをrefs/heads/mainに) */
273 public function setSymbolic(string $name, string $target): void {
274 if (!self::validName($name) || !self::validName($target)) throw new GitException("不正な参照の名前:{$target}");
275 $this->repo->writeFile($this->repo->path.'/'.$name, "ref: {$target}\n");
276 }
277}