1 | <?php declare(strict_types=1); |
||||||
2 | |||||||
3 | /* |
||||||
4 | * This file is part of Biurad opensource projects. |
||||||
5 | * |
||||||
6 | * @copyright 2022 Biurad Group (https://biurad.com/) |
||||||
7 | * @license https://opensource.org/licenses/BSD-3-Clause License |
||||||
8 | * |
||||||
9 | * For the full copyright and license information, please view the LICENSE |
||||||
10 | * file that was distributed with this source code. |
||||||
11 | */ |
||||||
12 | |||||||
13 | namespace Biurad\Git; |
||||||
14 | |||||||
15 | use Psr\Log\LoggerInterface; |
||||||
16 | use Symfony\Component\Process\Exception\ExceptionInterface; |
||||||
17 | use Symfony\Component\Process\Exception\ProcessFailedException; |
||||||
18 | use Symfony\Component\Process\Process; |
||||||
19 | |||||||
20 | /** |
||||||
21 | * The Git Repository. |
||||||
22 | * |
||||||
23 | * @author Divine Niiquaye Ibok <[email protected]> |
||||||
24 | */ |
||||||
25 | class Repository |
||||||
26 | { |
||||||
27 | private float $timeout = 600.0; |
||||||
28 | private string $command = 'git'; |
||||||
29 | private int $exitCode = 0; |
||||||
30 | private int $concurrency = 0; |
||||||
31 | private string $gitDir; |
||||||
32 | private array $cache = []; |
||||||
33 | |||||||
34 | public function __construct( |
||||||
35 | private string $path, |
||||||
36 | private array $envVars = [], |
||||||
37 | private bool $debug = true, |
||||||
38 | private ?LoggerInterface $logger = null, |
||||||
39 | ) { |
||||||
40 | $this->gitDir = $this->path.'/.git'; |
||||||
41 | |||||||
42 | if (\defined('PHP_WINDOWS_VERSION_BUILD') && isset($_SERVER['PATH']) && !isset($envVars['PATH'])) { |
||||||
43 | $this->envVars['PATH'] = $_SERVER['PATH']; |
||||||
44 | } |
||||||
45 | } |
||||||
46 | |||||||
47 | /** |
||||||
48 | * Create a local clone of a remote repository. |
||||||
49 | * |
||||||
50 | * @param string $path The path to clone the repository to |
||||||
51 | * @param array<int,string> $envVars |
||||||
52 | * @param array<int,string> $args Additional arguments to pass to the clone command |
||||||
53 | */ |
||||||
54 | public static function fromRemote( |
||||||
55 | string $remoteRepo, |
||||||
56 | string $path, |
||||||
57 | array $envVars = [], |
||||||
58 | array $args = [], |
||||||
59 | bool $debug = true, |
||||||
60 | LoggerInterface $logger = null, |
||||||
61 | ): self { |
||||||
62 | if (!\file_exists($path)) { |
||||||
63 | \mkdir($path, 0777, true); |
||||||
64 | } |
||||||
65 | |||||||
66 | $repo = new self($path, $envVars, $debug, $logger); |
||||||
67 | $repo->run('clone', [$remoteRepo, '.', ...$args], null, $path); |
||||||
68 | |||||||
69 | return $repo; |
||||||
70 | } |
||||||
71 | |||||||
72 | /** |
||||||
73 | * Set how long to wait for a command to finish. |
||||||
74 | */ |
||||||
75 | public function setTimeOut(float $timeout): void |
||||||
76 | { |
||||||
77 | $this->timeout = $timeout; |
||||||
78 | } |
||||||
79 | |||||||
80 | /** |
||||||
81 | * Set the git command to use (e.g. 'git' or '/usr/bin/git'). |
||||||
82 | */ |
||||||
83 | public function setCommand(string $command): void |
||||||
84 | { |
||||||
85 | $this->command = $command; |
||||||
86 | } |
||||||
87 | |||||||
88 | /** |
||||||
89 | * Set the git environment variables. |
||||||
90 | */ |
||||||
91 | public function setEnvVars(array $envVars): void |
||||||
92 | { |
||||||
93 | $this->envVars = $envVars; |
||||||
94 | } |
||||||
95 | |||||||
96 | /** |
||||||
97 | * Remove the git environment variable(s). |
||||||
98 | */ |
||||||
99 | public function removeEnvVars(string ...$envVars): void |
||||||
100 | { |
||||||
101 | foreach ($envVars as $envVar) { |
||||||
102 | unset($this->envVars[$envVar]); |
||||||
103 | } |
||||||
104 | } |
||||||
105 | |||||||
106 | /** |
||||||
107 | * Get the git environment variables. |
||||||
108 | * |
||||||
109 | * @return array<string,string> |
||||||
110 | */ |
||||||
111 | public function getEnvVars(): array |
||||||
112 | { |
||||||
113 | return $this->envVars; |
||||||
114 | } |
||||||
115 | |||||||
116 | /** |
||||||
117 | * Returns the url or path to the repository. |
||||||
118 | */ |
||||||
119 | public function getPath(): string |
||||||
120 | { |
||||||
121 | return $this->path; |
||||||
122 | } |
||||||
123 | |||||||
124 | /** |
||||||
125 | * Returns the path to the .git directory. |
||||||
126 | */ |
||||||
127 | public function getGitPath(): string |
||||||
128 | { |
||||||
129 | return $this->isBare() ? $this->path : $this->gitDir; |
||||||
130 | } |
||||||
131 | |||||||
132 | /** |
||||||
133 | * Returns true if the repository is bare. |
||||||
134 | */ |
||||||
135 | public function isBare(): bool |
||||||
136 | { |
||||||
137 | if (!\file_exists($this->path)) { |
||||||
138 | return false; |
||||||
139 | } |
||||||
140 | |||||||
141 | return 'true' === \trim($this->run('rev-parse', ['--is-bare-repository'])); |
||||||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||||||
142 | } |
||||||
143 | |||||||
144 | /** |
||||||
145 | * @return int the size of repository in kilobytes, -1 if command failed |
||||||
146 | */ |
||||||
147 | public function getSize(bool $real = false): int |
||||||
148 | { |
||||||
149 | if ($real) { |
||||||
150 | if (0 === ($totalBytes = &$this->cache['size'] ?? 0)) { |
||||||
151 | $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->getGitPath(), \FilesystemIterator::SKIP_DOTS)); |
||||||
152 | |||||||
153 | foreach ($iterator as $object) { |
||||||
154 | $totalBytes += $object->getSize(); |
||||||
155 | } |
||||||
156 | } |
||||||
157 | |||||||
158 | return (int) ($totalBytes / 1000 + 0.5); |
||||||
159 | } |
||||||
160 | |||||||
161 | if (empty($o = $this->run('count-objects')) || 0 !== $this->exitCode) { |
||||||
162 | return -1; |
||||||
163 | } |
||||||
164 | |||||||
165 | return (int) \substr($o, \strpos($o, ',') + 2, -10); |
||||||
166 | } |
||||||
167 | |||||||
168 | /** |
||||||
169 | * Get the git repository configuration(s). |
||||||
170 | */ |
||||||
171 | public function getConfig(string $key = null, string|int|float|bool $default = null): mixed |
||||||
172 | { |
||||||
173 | $resolve = fn (string $v) => 'true' === $v ? true : ('false' === $v ? false : (\is_numeric($v) ? (int) $v : $v)); |
||||||
174 | |||||||
175 | if (null === $key) { |
||||||
176 | $o = $this->run('config', ['--list']); |
||||||
177 | |||||||
178 | if (empty($o) || 0 !== $this->exitCode) { |
||||||
179 | return null; |
||||||
180 | } |
||||||
181 | |||||||
182 | if (!isset($this->cache[$i = \md5($o)])) { |
||||||
183 | foreach (\explode("\n", $o) as $line) { |
||||||
184 | if (!empty($line)) { |
||||||
185 | [$k, $v] = \explode('=', $line, 2); |
||||||
186 | $this->cache[$i][$k] = $resolve($v); |
||||||
187 | } |
||||||
188 | } |
||||||
189 | } |
||||||
190 | |||||||
191 | return $this->cache[$i]; |
||||||
192 | } |
||||||
193 | |||||||
194 | try { |
||||||
195 | $o = $this->run('config', ['--get', $key]); |
||||||
196 | } catch (ExceptionInterface) { |
||||||
0 ignored issues
–
show
Coding Style
Comprehensibility
introduced
by
|
|||||||
197 | } |
||||||
198 | |||||||
199 | return (empty($o) || 0 !== $this->exitCode) ? $default : $resolve(\trim($o)); |
||||||
200 | } |
||||||
201 | |||||||
202 | /** |
||||||
203 | * Returns all remotes. |
||||||
204 | * |
||||||
205 | * @return array<string,Remote> |
||||||
206 | */ |
||||||
207 | public function getRemotes(): array |
||||||
208 | { |
||||||
209 | $o = $this->run('remote', ['--verbose']); |
||||||
210 | |||||||
211 | if (empty($o) || 0 !== $this->exitCode) { |
||||||
212 | return []; |
||||||
213 | } |
||||||
214 | |||||||
215 | if (!isset($this->cache[$i = \md5($o)])) { |
||||||
216 | foreach (\array_filter(\explode(" (push)\n", $o)) as $line) { |
||||||
217 | [$a, $b] = \explode("\n", $line, 2); |
||||||
218 | [$remote, $url] = \explode("\t", $b, 2); |
||||||
219 | $this->cache[$i][$remote] = new Remote($remote, \substr($a, \strlen($remote) + 1, -8), $url); |
||||||
220 | } |
||||||
221 | } |
||||||
222 | |||||||
223 | return $this->cache[$i]; |
||||||
224 | } |
||||||
225 | |||||||
226 | /** |
||||||
227 | * Returns untracked files in the repository. |
||||||
228 | * |
||||||
229 | * @return array<int,array<string,string>> array of [status => '??', file => 'file.txt'] |
||||||
230 | */ |
||||||
231 | public function getUntrackedFiles(bool $staged = false): array |
||||||
232 | { |
||||||
233 | $o = $this->run('status', ['--porcelain', '-uall', $staged ? '-s' : '--untracked-files=all']); |
||||||
234 | |||||||
235 | if (empty($o) || 0 !== $this->exitCode) { |
||||||
236 | return []; |
||||||
237 | } |
||||||
238 | |||||||
239 | if (!isset($this->cache[$i = \md5($o)])) { |
||||||
240 | foreach (\explode("\n", $o) as $line) { |
||||||
241 | if (!empty($line)) { |
||||||
242 | [$status, $file] = \explode(' ', $line, 2); |
||||||
243 | $this->cache[$i][] = \compact('status', 'file'); |
||||||
244 | } |
||||||
245 | } |
||||||
246 | } |
||||||
247 | |||||||
248 | return $this->cache[$i]; |
||||||
249 | } |
||||||
250 | |||||||
251 | /** |
||||||
252 | * Get the git repository's references. |
||||||
253 | * |
||||||
254 | * @return array<int,Revision> |
||||||
255 | */ |
||||||
256 | public function getReferences(): array |
||||||
257 | { |
||||||
258 | $o = $this->run('show-ref'); |
||||||
259 | |||||||
260 | if (empty($o) || 0 !== $this->exitCode) { |
||||||
261 | return []; |
||||||
262 | } |
||||||
263 | |||||||
264 | if (!isset($this->cache[$i = \md5($o)])) { |
||||||
265 | foreach (\explode("\n", $o) as $line) { |
||||||
266 | if (!empty($line)) { |
||||||
267 | [$hash, $ref] = \explode(' ', $line, 2); |
||||||
268 | |||||||
269 | if (\str_starts_with($ref, 'refs/heads/') || \str_starts_with($ref, 'refs/remotes/')) { |
||||||
270 | $this->cache[$i][] = new Branch($this, $ref, $hash); |
||||||
271 | } elseif (\str_starts_with($ref, 'refs/tags/')) { |
||||||
272 | $this->cache[$i][] = new Tag($this, $ref, $hash); |
||||||
273 | } else { |
||||||
274 | $this->cache[$i][] = new Revision($this, $ref, $hash); |
||||||
275 | } |
||||||
276 | } |
||||||
277 | } |
||||||
278 | } |
||||||
279 | |||||||
280 | return $this->cache[$i]; |
||||||
281 | } |
||||||
282 | |||||||
283 | /** |
||||||
284 | * Returns an array of all branches. |
||||||
285 | * |
||||||
286 | * @return array<int,Branch> |
||||||
287 | */ |
||||||
288 | public function getBranches(): array |
||||||
289 | { |
||||||
290 | $o = $this->run('branch', ['-a', '--format=%(refname:short) %(objectname)']); |
||||||
291 | |||||||
292 | if (empty($o) || 0 !== $this->exitCode) { |
||||||
293 | return []; |
||||||
294 | } |
||||||
295 | |||||||
296 | if (!isset($this->cache[$i = \md5($o)])) { |
||||||
297 | foreach (\explode("\n", $o) as $line) { |
||||||
298 | if (!empty($line)) { |
||||||
299 | [$branch, $hash] = \explode(' ', $line, 2); |
||||||
300 | |||||||
301 | if (\in_array($branch, ['refs/heads/HEAD', 'origin/HEAD'], true)) { |
||||||
302 | continue; |
||||||
303 | } |
||||||
304 | |||||||
305 | $ref = \str_starts_with($branch, 'origin/') ? 'remotes/' : 'heads/'; |
||||||
306 | $this->cache[$i][] = new Branch($this, 'refs/'.$ref.$branch, $hash); |
||||||
307 | } |
||||||
308 | } |
||||||
309 | } |
||||||
310 | |||||||
311 | return $this->cache[$i]; |
||||||
312 | } |
||||||
313 | |||||||
314 | /** |
||||||
315 | * Returns branch(es) belonging to a revision, if count is 1, the first branch is returned. |
||||||
316 | * Head is detached if the revision value is HEAD and null is returned. |
||||||
317 | * |
||||||
318 | * @param string $revision The branch ref name or short name, tag, or a commit hash |
||||||
319 | * |
||||||
320 | * @return array<int,Branch>|Branch|null |
||||||
321 | */ |
||||||
322 | public function getBranch(string $revision = 'HEAD'): Branch|array|null |
||||||
323 | { |
||||||
324 | $o = $this->run('branch', ['--points-at', $revision, '--format=%(refname:short) %(objectname)']); |
||||||
325 | |||||||
326 | if (empty($o) || 0 !== $this->exitCode) { |
||||||
327 | return null; |
||||||
328 | } |
||||||
329 | |||||||
330 | if (!isset($this->cache[$i = \md5($o)])) { |
||||||
331 | foreach (\explode("\n", $o) as $line) { |
||||||
332 | if (!empty($line)) { |
||||||
333 | [$branch, $hash] = \explode(' ', $line, 2); |
||||||
334 | |||||||
335 | if (\in_array($branch, ['refs/heads/HEAD', 'origin/HEAD'], true)) { |
||||||
336 | continue; |
||||||
337 | } |
||||||
338 | |||||||
339 | if (\str_starts_with($revision, 'refs/')) { |
||||||
340 | $branch = (\str_starts_with($revision, 'refs/heads/') ? 'refs/heads/' : 'refs/remotes/').$branch; |
||||||
341 | } elseif (\str_starts_with($revision, 'heads/')) { |
||||||
342 | $branch = 'refs/heads/'.$branch; |
||||||
343 | } elseif (\str_starts_with($revision, 'origin/') || \str_starts_with($revision, 'remotes/')) { |
||||||
344 | $branch = 'refs/remotes/origin/'.$branch; |
||||||
345 | } |
||||||
346 | |||||||
347 | $this->cache[$i][] = new Branch($this, $branch, $hash); |
||||||
348 | } |
||||||
349 | } |
||||||
350 | } |
||||||
351 | |||||||
352 | return 1 === \count($this->cache[$i]) ? $this->cache[$i][0] : $this->cache[$i] ?? null; |
||||||
353 | } |
||||||
354 | |||||||
355 | /** |
||||||
356 | * Returns an indexed array of all tags. |
||||||
357 | * |
||||||
358 | * @return array<int,Tag> |
||||||
359 | */ |
||||||
360 | public function getTags(): array |
||||||
361 | { |
||||||
362 | $o = $this->run('tag', ['--sort=-creatordate', '--format=%(refname:short) %(objectname)']); |
||||||
363 | |||||||
364 | if (empty($o) || 0 !== $this->exitCode) { |
||||||
365 | return []; |
||||||
366 | } |
||||||
367 | |||||||
368 | if (!isset($this->cache[$i = \md5($o)])) { |
||||||
369 | foreach (\explode("\n", $o) as $line) { |
||||||
370 | if (!empty($line)) { |
||||||
371 | [$tag, $hash] = \explode(' ', $line, 2); |
||||||
372 | $this->cache[$i][] = new Tag($this, 'refs/tags/'.$tag, $hash); |
||||||
373 | } |
||||||
374 | } |
||||||
375 | } |
||||||
376 | |||||||
377 | return $this->cache[$i]; |
||||||
378 | } |
||||||
379 | |||||||
380 | /** |
||||||
381 | * Returns tag(s) belonging to a revision, if count is 1, the first tag is returned. |
||||||
382 | * |
||||||
383 | * @param string $revision The tag ref name or short name, tag, or a commit hash |
||||||
384 | * |
||||||
385 | * @return array<int,Tag>|Tag|null |
||||||
386 | */ |
||||||
387 | public function getTag(string $revision = 'HEAD'): Tag|array|null |
||||||
388 | { |
||||||
389 | $o = $this->run('tag', ['--points-at', $revision, '--format=%(refname:short) %(objectname)']); |
||||||
390 | |||||||
391 | if (empty($o) || 0 !== $this->exitCode) { |
||||||
392 | return null; |
||||||
393 | } |
||||||
394 | |||||||
395 | if (!isset($this->cache[$i = \md5($o)])) { |
||||||
396 | foreach (\explode("\n", $o) as $line) { |
||||||
397 | if (!empty($line)) { |
||||||
398 | [$tag, $hash] = \explode(' ', $line, 2); |
||||||
399 | $this->cache[$i][] = new Tag($this, 'refs/tags/'.$tag, $hash); |
||||||
400 | } |
||||||
401 | } |
||||||
402 | } |
||||||
403 | |||||||
404 | return 1 === \count($this->cache[$i]) ? $this->cache[$i][0] : $this->cache[$i] ?? null; |
||||||
405 | } |
||||||
406 | |||||||
407 | /** |
||||||
408 | * Returns a commit object from it given hash. |
||||||
409 | */ |
||||||
410 | public function getCommit(string $commitHash): Commit |
||||||
411 | { |
||||||
412 | return $this->cache[$commitHash] ??= new Commit($this, $commitHash); |
||||||
413 | } |
||||||
414 | |||||||
415 | /** |
||||||
416 | * Returns the current commit. |
||||||
417 | */ |
||||||
418 | public function getLastCommit(): ?Commit |
||||||
419 | { |
||||||
420 | $o = $this->run('log', ['--pretty=format:%H', '-n', 1]); |
||||||
421 | |||||||
422 | if (empty($o) || 0 !== $this->exitCode) { |
||||||
423 | return null; |
||||||
424 | } |
||||||
425 | |||||||
426 | return $this->getCommit(\trim($o)); |
||||||
427 | } |
||||||
428 | |||||||
429 | /** |
||||||
430 | * @param array<int,string>|string|null $revisions a list of revisions or null if you want all history |
||||||
431 | * @param array<int,string>|string|null $paths paths to filter on |
||||||
432 | * @param int|null $offset start list from a given position |
||||||
433 | * @param int|null $limit limit number of fetched elements |
||||||
434 | */ |
||||||
435 | public function getLog(array|string $revisions = null, array|string $paths = null, int $offset = null, int $limit = null): Log |
||||||
436 | { |
||||||
437 | return new Log($this, $revisions, $paths, $offset, $limit); |
||||||
438 | } |
||||||
439 | |||||||
440 | /** |
||||||
441 | * Returns the global default git user. |
||||||
442 | */ |
||||||
443 | public function getAuthor(bool $local = false): ?Commit\Identity |
||||||
444 | { |
||||||
445 | if (!isset($this->cache['author'])) { |
||||||
446 | $data = $this->runConcurrent([ |
||||||
447 | ['config', '--get', $local ? '--local' : '--global', 'user.name'], |
||||||
448 | ['config', '--get', $local ? '--local' : '--global', 'user.email'], |
||||||
449 | ], null, false); |
||||||
450 | |||||||
451 | if (empty($data) || 0 !== $this->exitCode) { |
||||||
452 | return null; |
||||||
453 | } |
||||||
454 | |||||||
455 | $this->cache['author'] = new Commit\Identity($data[0], $data[1]); |
||||||
456 | } |
||||||
457 | |||||||
458 | return $this->cache['author']; |
||||||
459 | } |
||||||
460 | |||||||
461 | /** |
||||||
462 | * Returns the last exit code. |
||||||
463 | */ |
||||||
464 | public function getExitCode(): int |
||||||
465 | { |
||||||
466 | return $this->exitCode; |
||||||
467 | } |
||||||
468 | |||||||
469 | /** |
||||||
470 | * Returns the number of concurrent git commands. |
||||||
471 | */ |
||||||
472 | public function getConcurrentRuns(): int |
||||||
473 | { |
||||||
474 | return $this->concurrency; |
||||||
475 | } |
||||||
476 | |||||||
477 | /** |
||||||
478 | * Resets the repository object reference object, cache |
||||||
479 | * and discard all local changes in your working directory. |
||||||
480 | * |
||||||
481 | * @param bool $keep preserve uncommitted local changes if true |
||||||
482 | */ |
||||||
483 | public function reset(string $commitHash = null, bool $keep = false): void |
||||||
484 | { |
||||||
485 | $this->cache = []; |
||||||
486 | $this->run('reset', [$keep ? '--keep' : '--hard', $commitHash ?? 'HEAD']); |
||||||
487 | } |
||||||
488 | |||||||
489 | /** |
||||||
490 | * Cleans up the repository completely without leaving a single file. |
||||||
491 | */ |
||||||
492 | public function clean(): void |
||||||
493 | { |
||||||
494 | $this->runConcurrent([ |
||||||
495 | ['clean', '-f', '-d', '-x'], |
||||||
496 | ['rm', '-rfq', '--ignore-unmatch', '.'], // Extra to ensure everything is removed |
||||||
497 | ['reset'], |
||||||
498 | ]); |
||||||
499 | } |
||||||
500 | |||||||
501 | /** |
||||||
502 | * Initializes the repository as a Git repository. |
||||||
503 | */ |
||||||
504 | public function initialize(int|string ...$args): self |
||||||
505 | { |
||||||
506 | if (!\file_exists($p = $this->path)) { |
||||||
507 | \mkdir($p, 0777, true); |
||||||
508 | } |
||||||
509 | |||||||
510 | $this->run('init', $args); |
||||||
511 | |||||||
512 | return $this; |
||||||
513 | } |
||||||
514 | |||||||
515 | /** |
||||||
516 | * Adds a new commit to repository. |
||||||
517 | * |
||||||
518 | * @param array<int,string> $args arguments to pass to git commit |
||||||
519 | */ |
||||||
520 | public function commit(CommitNew|Commit\Message $commit, array $args = [], string $cwd = null): self |
||||||
521 | { |
||||||
522 | if ($commit instanceof Commit\Message) { |
||||||
523 | $msg = $commit->__toString(); |
||||||
524 | $msg = !empty($msg) ? ['-m', $msg] : ['--allow-empty-message']; |
||||||
525 | $this->runConcurrent([['add', '--all'], ['commit', '--allow-empty', ...$msg, ...$args]], cwd: $cwd); |
||||||
526 | |||||||
527 | return $this; |
||||||
528 | } |
||||||
529 | |||||||
530 | $commands = []; |
||||||
531 | $msg = ($data = $commit->getData())[0]->__toString(); |
||||||
532 | $commands[] = !empty($paths = $data[1] ?? []) ? ['add', ...$paths] : ['add', '--all']; |
||||||
533 | $oldEnv = $this->envVars; |
||||||
534 | |||||||
535 | if (isset($data[2])) { |
||||||
536 | $this->envVars['GIT_AUTHOR_NAME'] = $data[2]->getName(); |
||||||
537 | $this->envVars['GIT_AUTHOR_EMAIL'] = $data[2]->getEmail(); |
||||||
538 | |||||||
539 | if (null !== $d = $data[2]->getDate()) { |
||||||
540 | $this->envVars['GIT_AUTHOR_DATE'] = $d->format('D, d M Y H:i:s'); |
||||||
541 | } |
||||||
542 | |||||||
543 | if (!isset($data[3])) { |
||||||
544 | $data[3] = $data[2]; |
||||||
545 | } |
||||||
546 | } |
||||||
547 | |||||||
548 | if (isset($data[3])) { |
||||||
549 | $this->envVars['GIT_COMMITTER_NAME'] = $data[3]->getName(); |
||||||
550 | $this->envVars['GIT_COMMITTER_EMAIL'] = $data[3]->getEmail(); |
||||||
551 | |||||||
552 | if (null !== $d = $data[3]->getDate()) { |
||||||
553 | $this->envVars['GIT_COMMITTER_DATE'] = $d->format('D, d M Y H:i:s'); |
||||||
554 | } |
||||||
555 | } |
||||||
556 | |||||||
557 | if (!empty($coAuthors = $data[4] ?? [])) { |
||||||
558 | $coAuthors = \array_map(fn (Commit\Identity $i) => $i->getName().' <'.$i->getEmail().'>', $coAuthors); |
||||||
559 | $msg .= "\n".($c = "\n".'Co-Authored-By: ').\implode($c, $coAuthors); |
||||||
560 | } |
||||||
561 | |||||||
562 | $msg = !empty($msg) ? ['-m', $msg] : ['--allow-empty-message']; |
||||||
563 | $commands[] = ['commit', '--allow-empty', ...$msg, ...$args]; |
||||||
564 | $this->runConcurrent($commands, cwd: $cwd); |
||||||
565 | $this->envVars = $oldEnv; |
||||||
566 | |||||||
567 | return $this; |
||||||
568 | } |
||||||
569 | |||||||
570 | /** |
||||||
571 | * Amend a previous commit message from it hash. |
||||||
572 | */ |
||||||
573 | public function amend(string $commitHash, Commit\Message $message, string $cwd = null): bool |
||||||
574 | { |
||||||
575 | $msg = $message->__toString(); |
||||||
576 | $msg = !empty($msg) ? ['-m', $msg] : ['--allow-empty-message']; |
||||||
577 | |||||||
578 | return $this->check('commit', ['-C', $commitHash, ...$msg, '--amend'], null, $cwd); |
||||||
579 | } |
||||||
580 | |||||||
581 | /** |
||||||
582 | * Pushes changes to a remote or git repository. |
||||||
583 | * |
||||||
584 | * @param array<int,string> $args arguments to pass to git push |
||||||
585 | * @param string|null $cwd The working directory command should run from |
||||||
586 | */ |
||||||
587 | public function push(string $remote = null, array $args = [], string $cwd = null): self |
||||||
588 | { |
||||||
589 | if (false === $this->getConfig('push.autoSetupRemote', false)) { |
||||||
590 | if (0 === $this->getExitCode()) { |
||||||
591 | $this->run('config', ['push.autoSetupRemote', 'true']); |
||||||
592 | } elseif (!\in_array('--all', $args, true)) { |
||||||
593 | \array_unshift($args, '--set-upstream', $remote ?? 'origin', $this->getBranch()[1]); |
||||||
594 | $remote = null; // looks like git version is older than 2.35 |
||||||
595 | } |
||||||
596 | } |
||||||
597 | |||||||
598 | if (null !== $remote) { |
||||||
599 | \array_unshift($args, $remote); |
||||||
600 | } |
||||||
601 | |||||||
602 | $this->run('push', $args, cwd: $cwd); |
||||||
603 | |||||||
604 | return $this; |
||||||
605 | } |
||||||
606 | |||||||
607 | /** |
||||||
608 | * Checks if command status is true or false. |
||||||
609 | * |
||||||
610 | * @param string $command Run git command eg. (checkout, branch, tag) |
||||||
611 | * @param array<int,int|string> $args Arguments of the git command |
||||||
612 | * @param callable|string|null $expected The string or callable to check command output |
||||||
613 | * @param string|null $cwd The working directory command should run from |
||||||
614 | */ |
||||||
615 | public function check(string $command, array $args = [], string|callable $expected = null, string $cwd = null): bool |
||||||
616 | { |
||||||
617 | try { |
||||||
618 | $o = $this->run($command, $args, null, $cwd); |
||||||
619 | } catch (ProcessFailedException) { |
||||||
0 ignored issues
–
show
Coding Style
Comprehensibility
introduced
by
|
|||||||
620 | } |
||||||
621 | |||||||
622 | if (0 !== $this->exitCode) { |
||||||
623 | return false; |
||||||
624 | } |
||||||
625 | |||||||
626 | return isset($o) ? ($expected === $o || (\is_callable($expected) ? $expected($o) : true)) : false; |
||||||
627 | } |
||||||
628 | |||||||
629 | /** |
||||||
630 | * @param string $command Run git command eg. (checkout, branch, tag) |
||||||
631 | * @param array<int,int|string> $args Arguments of the git command |
||||||
632 | * @param callable|null $callback Reads buffer, param of (string $type, string $buffer) |
||||||
633 | * @param string|null $cwd The working directory command should run from |
||||||
634 | * |
||||||
635 | * @return string output of a successful process or null if execution failed and debug-mode is disabled |
||||||
636 | * |
||||||
637 | * @throws \RuntimeException while executing git command (debug-mode only) |
||||||
638 | */ |
||||||
639 | public function run(string $command, array $args = [], callable $callback = null, string $cwd = null): ?string |
||||||
640 | { |
||||||
641 | $process = new Process([$this->command, $command, ...$args], $cwd ?? $this->path, $this->envVars, null, $this->timeout); |
||||||
642 | |||||||
643 | if (0 !== $this->concurrency) { |
||||||
644 | $this->concurrency = 0; |
||||||
645 | } |
||||||
646 | |||||||
647 | try { |
||||||
648 | $this->exitCode = $process->mustRun($callback)->getExitCode(); |
||||||
649 | |||||||
650 | return $process->getOutput(); |
||||||
651 | } catch (ExceptionInterface $e) { |
||||||
652 | $this->logger?->error($e->getMessage()); |
||||||
653 | |||||||
654 | return $this->debug ? throw $e : null; |
||||||
655 | } finally { |
||||||
656 | if (null !== $this->logger) { |
||||||
657 | $message = \sprintf(' at "%.2fms".', (\microtime(true) - $process->getStartTime()) * 1000); |
||||||
658 | $this->logger->debug(\sprintf('Command "%s" finished successfully'.$message, $process->getCommandLine())); |
||||||
659 | } |
||||||
660 | } |
||||||
661 | } |
||||||
662 | |||||||
663 | /** |
||||||
664 | * Concurrently run multiple git commands. |
||||||
665 | * |
||||||
666 | * @param array<int,array<int,string>|string> $commands An array list of commands eg. [['log', 'master'], ['git', '-v']] |
||||||
667 | * @param callable|null $callback Reads buffer, param of (array $command, string $type, string $buffer) |
||||||
668 | * @param string|null $cwd The working directory command should run from |
||||||
669 | * |
||||||
670 | * @return array<int,string> |
||||||
671 | */ |
||||||
672 | public function runConcurrent(array $commands, callable $callback = null, bool $exitOnFailure = true, string $cwd = null): array |
||||||
673 | { |
||||||
674 | $outputs = []; |
||||||
675 | $this->concurrency = 0; |
||||||
676 | |||||||
677 | if (null !== $this->logger) { |
||||||
678 | $message = 'Concurrent command(s) [%s] finished successfully'; |
||||||
679 | $lines = []; |
||||||
680 | $start = 0; |
||||||
681 | } |
||||||
682 | |||||||
683 | if ($hasCallback = null !== $callback) { |
||||||
684 | $callback = fn (array $command): callable => fn (string $type, string $buffer) => $callback($type, $buffer, $command); |
||||||
685 | } |
||||||
686 | |||||||
687 | foreach ($commands as $k => $command) { |
||||||
688 | $command = \is_array($command) ? $command : [$command]; |
||||||
689 | $process = new Process([$this->command, ...$command], $cwd ?? $this->path, $this->envVars, null, $this->timeout); |
||||||
690 | |||||||
691 | try { |
||||||
692 | $process->start($hasCallback ? $callback($command) : null); |
||||||
693 | |||||||
694 | foreach ($process->getIterator() as $buffer) { |
||||||
695 | if (!isset($outputs[$k])) { |
||||||
696 | $outputs[$k] = $buffer; |
||||||
697 | continue; |
||||||
698 | } |
||||||
699 | $outputs[$k] .= "\n" === $buffer[0] ? $buffer : "\n".$buffer; |
||||||
700 | } |
||||||
701 | |||||||
702 | $this->exitCode = $process->wait(); |
||||||
703 | ++$this->concurrency; |
||||||
704 | } catch (ExceptionInterface $e) { |
||||||
705 | $this->exitCode = 1; |
||||||
706 | } |
||||||
707 | |||||||
708 | if (0 !== $this->exitCode) { |
||||||
709 | $this->logger?->error( |
||||||
710 | \sprintf('Concurrent executed "%s/%s" successfully, but failed on "%s".', $this->concurrency, \count($commands), $process->getCommandLine()), |
||||||
711 | ['error' => null] |
||||||
712 | ); |
||||||
713 | |||||||
714 | if ($exitOnFailure) { |
||||||
715 | return $this->debug ? throw ($e ?? new ProcessFailedException($process)) : []; |
||||||
716 | } |
||||||
717 | } |
||||||
718 | |||||||
719 | if (isset($lines)) { |
||||||
720 | $lines[] = $process->getCommandLine(); |
||||||
721 | |||||||
722 | if (isset($start)) { |
||||||
723 | $start += \microtime(true) - $process->getStartTime(); |
||||||
724 | } |
||||||
725 | } |
||||||
726 | } |
||||||
727 | |||||||
728 | if (isset($message, $start)) { |
||||||
729 | $this->logger->debug(\sprintf($message.' at "%.2fms".', \implode(', ', $lines ?? []), $start * 1000)); |
||||||
0 ignored issues
–
show
The method
debug() does not exist on null .
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces. This is most likely a typographical error or the method has been renamed. ![]() |
|||||||
730 | } |
||||||
731 | |||||||
732 | return $outputs; |
||||||
733 | } |
||||||
734 | |||||||
735 | /** |
||||||
736 | * Executes a shell command on the repository, using PHP pipes. |
||||||
737 | * |
||||||
738 | * @param string $command The command to execute |
||||||
739 | */ |
||||||
740 | public function shell(string $command, array $env = []): void |
||||||
741 | { |
||||||
742 | $argument = \sprintf('%s \'%s\'', $command, $this->getGitPath()); |
||||||
743 | $prefix = ''; |
||||||
744 | |||||||
745 | foreach ($env as $name => $value) { |
||||||
746 | $prefix .= \sprintf('export %s=%s;', \escapeshellarg($name), \escapeshellarg($value)); |
||||||
747 | } |
||||||
748 | |||||||
749 | \proc_open($prefix.'git shell -c '.\escapeshellarg($argument), [\STDIN, \STDOUT, \STDERR], $pipes); |
||||||
750 | } |
||||||
751 | } |
||||||
752 |