-
-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathGitRepository.php
More file actions
626 lines (514 loc) · 13.2 KB
/
GitRepository.php
File metadata and controls
626 lines (514 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
<?php
declare(strict_types=1);
namespace CzProject\GitPhp;
class GitRepository
{
/** @var string */
protected $repository;
/** @var IRunner */
protected $runner;
/**
* @param string $repository
* @throws GitException
*/
public function __construct($repository, ?IRunner $runner = NULL)
{
if (basename($repository) === '.git') {
$repository = dirname($repository);
}
$path = realpath($repository);
if ($path === FALSE) {
throw new GitException("Repository '$repository' not found.");
}
$this->repository = $path;
$this->runner = $runner !== NULL ? $runner : new Runners\CliRunner;
}
/**
* @return string
*/
public function getRepositoryPath()
{
return $this->repository;
}
/**
* Creates a tag.
* `git tag <name>`
* @param string $name
* @param array<mixed>|NULL $options
* @throws GitException
* @return static
*/
public function createTag($name, $options = NULL)
{
$this->run('tag', $options, '--end-of-options', $name);
return $this;
}
/**
* Removes tag.
* `git tag -d <name>`
* @param string $name
* @throws GitException
* @return static
*/
public function removeTag($name)
{
$this->run('tag', [
'-d' => $name,
]);
return $this;
}
/**
* Renames tag.
* `git tag <new> <old>`
* `git tag -d <old>`
* @param string $oldName
* @param string $newName
* @throws GitException
* @return static
*/
public function renameTag($oldName, $newName)
{
// http://stackoverflow.com/a/1873932
// create new as alias to old (`git tag NEW OLD`)
$this->run('tag', '--end-of-options', $newName, $oldName);
// delete old (`git tag -d OLD`)
$this->removeTag($oldName);
return $this;
}
/**
* Returns list of tags in repo.
* @return string[]|NULL NULL => no tags
* @throws GitException
*/
public function getTags()
{
return $this->extractFromCommand(['tag'], 'trim');
}
/**
* Merges branches.
* `git merge <options> <name>`
* @param string $branch
* @param array<mixed>|NULL $options
* @throws GitException
* @return static
*/
public function merge($branch, $options = NULL)
{
$this->run('merge', $options, '--end-of-options', $branch);
return $this;
}
/**
* Creates new branch.
* `git branch <name>`
* (optionaly) `git checkout <name>`
* @param string $name
* @param bool $checkout
* @throws GitException
* @return static
*/
public function createBranch($name, $checkout = FALSE)
{
// git branch $name
$this->run('branch', '--end-of-options', $name);
if ($checkout) {
$this->checkout($name);
}
return $this;
}
/**
* Removes branch.
* `git branch -d <name>`
* @param string $name
* @throws GitException
* @return static
*/
public function removeBranch($name)
{
$this->run('branch', [
'-d' => $name,
]);
return $this;
}
/**
* Gets name of current branch
* `git branch` + magic
* @return string
* @throws GitException
*/
public function getCurrentBranchName()
{
try {
$branch = $this->extractFromCommand(['branch', '-a', '--no-color'], function($value) {
if (isset($value[0]) && $value[0] === '*') {
return trim(substr($value, 1));
}
return FALSE;
});
if (is_array($branch)) {
return $branch[0];
}
} catch (GitException $e) {
// nothing
}
throw new GitException('Getting of current branch name failed.');
}
/**
* Returns list of all (local & remote) branches in repo.
* @return string[]|NULL NULL => no branches
* @throws GitException
*/
public function getBranches()
{
return $this->extractFromCommand(['branch', '-a', '--no-color'], function($value) {
return trim(substr($value, 1));
});
}
/**
* Returns list of remote branches in repo.
* @return string[]|NULL NULL => no branches
* @throws GitException
*/
public function getRemoteBranches()
{
return $this->extractFromCommand(['branch', '-r', '--no-color'], function($value) {
return trim(substr($value, 1));
});
}
/**
* Returns list of local branches in repo.
* @return string[]|NULL NULL => no branches
* @throws GitException
*/
public function getLocalBranches()
{
return $this->extractFromCommand(['branch', '--no-color'], function($value) {
return trim(substr($value, 1));
});
}
/**
* Checkout branch.
* `git checkout <branch>`
* @param string $name
* @throws GitException
* @return static
*/
public function checkout($name)
{
if (!is_string($name)) {
throw new InvalidArgumentException('Branch name must be string.');
}
if ($name === '') {
throw new InvalidArgumentException('Branch name cannot be empty.');
}
if ($name[0] === '-') {
throw new InvalidArgumentException('Branch name cannot be option name.');
}
$this->run('checkout', $name);
return $this;
}
/**
* Removes file(s).
* `git rm <file>`
* @param string|string[] $file
* @throws GitException
* @return static
*/
public function removeFile($file)
{
if (!is_array($file)) {
$file = func_get_args();
}
foreach ($file as $item) {
$this->run('rm', '-r', '--end-of-options', $item);
}
return $this;
}
/**
* Adds file(s).
* `git add <file>`
* @param string|string[] $file
* @throws GitException
* @return static
*/
public function addFile($file)
{
if (!is_array($file)) {
$file = func_get_args();
}
foreach ($file as $item) {
assert(is_string($item));
// make sure the given item exists
// this can be a file or an directory, git supports both
$path = Helpers::isAbsolute($item) ? $item : ($this->getRepositoryPath() . DIRECTORY_SEPARATOR . $item);
if (!file_exists($path)) {
throw new GitException("The path at '$item' does not represent a valid file.");
}
$this->run('add', '--end-of-options', $item);
}
return $this;
}
/**
* Adds all created, modified & removed files.
* `git add --all`
* @throws GitException
* @return static
*/
public function addAllChanges()
{
$this->run('add', '--all');
return $this;
}
/**
* Renames file(s).
* `git mv <file>`
* @param string|string[] $file from: array('from' => 'to', ...) || (from, to)
* @param string|NULL $to
* @throws GitException
* @return static
*/
public function renameFile($file, $to = NULL)
{
if (!is_array($file)) { // rename(file, to);
$file = [
$file => $to,
];
}
foreach ($file as $from => $to) {
$this->run('mv', '--end-of-options', $from, $to);
}
return $this;
}
/**
* Commits changes
* `git commit <params> -m <message>`
* @param string $message
* @param array<mixed>|NULL $options
* @throws GitException
* @return static
*/
public function commit($message, $options = NULL)
{
$this->run('commit', $options, [
'-m' => $message,
]);
return $this;
}
/**
* Returns last commit ID on current branch
* `git log --pretty=format:"%H" -n 1`
* @return CommitId
* @throws GitException
*/
public function getLastCommitId()
{
$result = $this->run('log', '--pretty=format:%H', '-n', '1');
$lastLine = $result->getOutputLastLine();
return new CommitId((string) $lastLine);
}
/**
* @return Commit
*/
public function getLastCommit()
{
return $this->getCommit($this->getLastCommitId());
}
/**
* @param string|CommitId $commitId
* @return Commit
*/
public function getCommit($commitId)
{
if (!($commitId instanceof CommitId)) {
$commitId = new CommitId($commitId);
}
// subject
$result = $this->run('log', '-1', $commitId, '--format=%s');
$subject = rtrim($result->getOutputAsString());
// body
$result = $this->run('log', '-1', $commitId, '--format=%b');
$body = rtrim($result->getOutputAsString());
// author email
$result = $this->run('log', '-1', $commitId, '--format=%ae');
$authorEmail = rtrim($result->getOutputAsString());
// author name
$result = $this->run('log', '-1', $commitId, '--format=%an');
$authorName = rtrim($result->getOutputAsString());
// author date
$result = $this->run('log', '-1', $commitId, '--pretty=format:%ad', '--date=iso-strict');
$authorDate = \DateTimeImmutable::createFromFormat(\DateTime::ATOM, (string) $result->getOutputLastLine());
if (!($authorDate instanceof \DateTimeImmutable)) {
throw new GitException('Failed fetching of commit author date.', 0, NULL, $result);
}
// committer email
$result = $this->run('log', '-1', $commitId, '--format=%ce');
$committerEmail = rtrim($result->getOutputAsString());
// committer name
$result = $this->run('log', '-1', $commitId, '--format=%cn');
$committerName = rtrim($result->getOutputAsString());
// committer date
$result = $this->run('log', '-1', $commitId, '--pretty=format:%cd', '--date=iso-strict');
$committerDate = \DateTimeImmutable::createFromFormat(\DateTime::ATOM, (string) $result->getOutputLastLine());
if (!($committerDate instanceof \DateTimeImmutable)) {
throw new GitException('Failed fetching of commit committer date.', 0, NULL, $result);
}
return new Commit(
$commitId,
$subject,
$body !== '' ? $body : NULL,
$authorEmail,
$authorName !== '' ? $authorName : NULL,
$authorDate,
$committerEmail,
$committerName !== '' ? $committerName : NULL,
$committerDate
);
}
/**
* Exists changes?
* `git status` + magic
* @return bool
* @throws GitException
*/
public function hasChanges()
{
// Make sure the `git status` gets a refreshed look at the working tree.
$this->run('update-index', '-q', '--refresh');
$result = $this->run('status', '--porcelain');
return $result->hasOutput();
}
/**
* Pull changes from a remote
* @param string|string[]|NULL $remote
* @param array<mixed>|NULL $options
* @return static
* @throws GitException
*/
public function pull($remote = NULL, ?array $options = NULL)
{
$this->run('pull', $options, '--end-of-options', $remote);
return $this;
}
/**
* Push changes to a remote
* @param string|string[]|NULL $remote
* @param array<mixed>|NULL $options
* @return static
* @throws GitException
*/
public function push($remote = NULL, ?array $options = NULL)
{
$this->run('push', $options, '--end-of-options', $remote);
return $this;
}
/**
* Run fetch command to get latest branches
* @param string|string[]|NULL $remote
* @param array<mixed>|NULL $options
* @return static
* @throws GitException
*/
public function fetch($remote = NULL, ?array $options = NULL)
{
$this->run('fetch', $options, '--end-of-options', $remote);
return $this;
}
/**
* Adds new remote repository
* @param string $name
* @param string $url
* @param array<mixed>|NULL $options
* @return static
* @throws GitException
*/
public function addRemote($name, $url, ?array $options = NULL)
{
$this->run('remote', 'add', $options, '--end-of-options', $name, $url);
return $this;
}
/**
* Renames remote repository
* @param string $oldName
* @param string $newName
* @return static
* @throws GitException
*/
public function renameRemote($oldName, $newName)
{
$this->run('remote', 'rename', '--end-of-options', $oldName, $newName);
return $this;
}
/**
* Removes remote repository
* @param string $name
* @return static
* @throws GitException
*/
public function removeRemote($name)
{
$this->run('remote', 'remove', '--end-of-options', $name);
return $this;
}
/**
* Changes remote repository URL
* @param string $name
* @param string $url
* @param array<mixed>|NULL $options
* @return static
* @throws GitException
*/
public function setRemoteUrl($name, $url, ?array $options = NULL)
{
$this->run('remote', 'set-url', $options, '--end-of-options', $name, $url);
return $this;
}
/**
* @param mixed ...$cmd
* @return string[] returns output
* @throws GitException
*/
public function execute(...$cmd)
{
$result = $this->run(...$cmd);
return $result->getOutput();
}
/**
* Runs command and returns result.
* @param mixed ...$args
* @return RunnerResult
* @throws GitException
*/
public function run(...$args)
{
$result = $this->runner->run($this->repository, $args);
if (!$result->isOk()) {
throw new GitException("Command '{$result->getCommand()}' failed (exit-code {$result->getExitCode()}).", $result->getExitCode(), NULL, $result);
}
return $result;
}
/**
* @param array<mixed> $args
* @param (callable(string $value): (string|FALSE))|NULL $filter
* @return string[]|NULL
* @throws GitException
*/
protected function extractFromCommand(array $args, ?callable $filter = NULL)
{
$result = $this->run(...$args);
$output = $result->getOutput();
if ($filter !== NULL) {
$newArray = [];
foreach ($output as $line) {
$value = $filter($line);
if ($value === FALSE) {
continue;
}
$newArray[] = (string) $value;
}
$output = $newArray;
}
if (empty($output)) {
return NULL;
}
return $output;
}
}