/
Repository.php
615 lines (512 loc) · 16 KB
/
Repository.php
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
<?php
namespace GitList\Component\Git;
use GitList\Component\Git\Commit\Commit;
use GitList\Component\Git\Model\Tree;
use GitList\Component\Git\Model\Blob;
use GitList\Component\Git\Model\Diff;
use Symfony\Component\Filesystem\Filesystem;
class Repository
{
protected $path;
protected $client;
public function __construct($path, Client $client)
{
$this->setPath($path);
$this->setClient($client);
}
public function setClient(Client $client)
{
$this->client = $client;
}
public function getClient()
{
return $this->client;
}
public function create()
{
mkdir($this->getPath());
$this->getClient()->run($this, 'init');
return $this;
}
public function getConfig($key)
{
$key = $this->getClient()->run($this, 'config ' . $key);
return trim($key);
}
public function setConfig($key, $value)
{
$this->getClient()->run($this, "config $key \"$value\"");
return $this;
}
/**
* Add untracked files
*
* @access public
* @param mixed $files Files to be added to the repository
*/
public function add($files = '.')
{
if (is_array($files)) {
$files = implode(' ', $files);
}
$this->getClient()->run($this, "add $files");
return $this;
}
/**
* Add all untracked files
*
* @access public
*/
public function addAll()
{
$this->getClient()->run($this, "add -A");
return $this;
}
/**
* Commit changes to the repository
*
* @access public
* @param string $message Description of the changes made
*/
public function commit($message)
{
$this->getClient()->run($this, "commit -m \"$message\"");
return $this;
}
/**
* Checkout a branch
*
* @access public
* @param string $branch Branch to be checked out
*/
public function checkout($branch)
{
$this->getClient()->run($this, "checkout $branch");
return $this;
}
/**
* Pull repository changes
*
* @access public
*/
public function pull()
{
$this->getClient()->run($this, "pull");
return $this;
}
/**
* Update remote references
*
* @access public
* @param string $repository Repository to be pushed
* @param string $refspec Refspec for the push
*/
public function push($repository = null, $refspec = null)
{
$command = "push";
if ($repository) {
$command .= " $repository";
}
if ($refspec) {
$command .= " $refspec";
}
$this->getClient()->run($this, $command);
return $this;
}
/**
* Show a list of the repository branches
*
* @access public
* @return array List of branches
*/
public function getBranches()
{
$branches = $this->getClient()->run($this, "branch");
$branches = explode("\n", $branches);
$branches = array_filter(preg_replace('/[\*\s]/', '', $branches));
return $branches;
}
/**
* Show the current repository branch
*
* @access public
* @return string Current repository branch
*/
public function getCurrentBranch()
{
$branches = $this->getClient()->run($this, "branch");
$branches = explode("\n", $branches);
foreach ($branches as $branch) {
if ($branch[0] == '*') {
return substr($branch, 2);
}
}
}
/**
* Check if a specified branch exists
*
* @access public
* @param string $branch Branch to be checked
* @return boolean True if the branch exists
*/
public function hasBranch($branch)
{
$branches = $this->getBranches();
$status = in_array($branch, $branches);
return $status;
}
/**
* Create a new repository branch
*
* @access public
* @param string $branch Branch name
*/
public function createBranch($branch)
{
$this->getClient()->run($this, "branch $branch");
}
/**
* Show a list of the repository tags
*
* @access public
* @return array List of tags
*/
public function getTags()
{
$tags = $this->getClient()->run($this, "tag");
$tags = explode("\n", $tags);
if (empty($tags[0])) {
return NULL;
}
return $tags;
}
/**
* Show the amount of commits on the repository
*
* @access public
* @return integer Total number of commits
*/
public function getTotalCommits($file = null)
{
if (defined('PHP_WINDOWS_VERSION_BUILD')) {
$command = "rev-list --count --all $file";
} else {
$command = "rev-list --all $file | wc -l";
}
$commits = $this->getClient()->run($this, $command);
return $commits;
}
/**
* Show the repository commit log
*
* @access public
* @return array Commit log
*/
public function getCommits($file = null, $page = 0)
{
$page = 15 * $page;
$pager = "--skip=$page --max-count=15";
$command = 'log ' . $pager . ' --pretty=format:"\"%h\": {\"hash\": \"%H\", \"short_hash\": \"%h\", \"tree\": \"%T\", \"parent\": \"%P\", \"author\": \"%an\", \"author_email\": \"%ae\", \"date\": \"%at\", \"commiter\": \"%cn\", \"commiter_email\": \"%ce\", \"commiter_date\": \"%ct\", \"message\": \"%f\"}"';
if ($file) {
$command .= " $file";
}
$logs = $this->getClient()->run($this, $command);
if (empty($logs)) {
throw new \RuntimeException('No commit log available');
}
$logs = str_replace("\n", ',', $logs);
$logs = json_decode("{ $logs }", true);
foreach ($logs as $log) {
$log['message'] = str_replace('-', ' ', $log['message']);
$commit = new Commit;
$commit->importData($log);
$commits[] = $commit;
}
return $commits;
}
public function getRelatedCommits($hash)
{
$logs = $this->getClient()->run($this, 'log --pretty=format:"\"%h\": {\"hash\": \"%H\", \"short_hash\": \"%h\", \"tree\": \"%T\", \"parent\": \"%P\", \"author\": \"%an\", \"author_email\": \"%ae\", \"date\": \"%at\", \"commiter\": \"%cn\", \"commiter_email\": \"%ce\", \"commiter_date\": \"%ct\", \"message\": \"%f\"}"');
if (empty($logs)) {
throw new \RuntimeException('No commit log available');
}
$logs = str_replace("\n", ',', $logs);
$logs = json_decode("{ $logs }", true);
foreach ($logs as $log) {
$log['message'] = str_replace('-', ' ', $log['message']);
$logTree = $this->getClient()->run($this, 'diff-tree -t -r ' . $log['hash']);
$lines = explode("\n", $logTree);
array_shift($lines);
$files = array();
foreach ($lines as $key => $line) {
if (empty($line)) {
unset($lines[$key]);
continue;
}
$files[] = preg_split("/[\s]+/", $line);
}
// Now let's find the commits who have our hash within them
foreach ($files as $file) {
if ($file[1] == 'commit') {
continue;
}
if ($file[3] == $hash) {
$commit = new Commit;
$commit->importData($log);
$commits[] = $commit;
break;
}
}
}
return $commits;
}
public function getCommit($commitHash)
{
$logs = $this->getClient()->run($this, 'show --pretty=format:"{\"hash\": \"%H\", \"short_hash\": \"%h\", \"tree\": \"%T\", \"parent\": \"%P\", \"author\": \"%an\", \"author_email\": \"%ae\", \"date\": \"%at\", \"commiter\": \"%cn\", \"commiter_email\": \"%ce\", \"commiter_date\": \"%ct\", \"message\": \"%f\"}" ' . $commitHash);
if (empty($logs)) {
throw new \RuntimeException('No commit log available');
}
$logs = explode("\n", $logs);
// Read commit metadata
$data = json_decode($logs[0], true);
$data['message'] = str_replace('-', ' ', $data['message']);
$commit = new Commit;
$commit->importData($data);
unset($logs[0]);
if (empty($logs[1])) {
$logs = explode("\n", $this->getClient()->run($this, 'diff ' . $commitHash . '~1..' . $commitHash));
}
// Read diff logs
$lineNumOld = 0;
$lineNumNew = 0;
foreach ($logs as $log) {
if ('diff' === substr($log, 0, 4)) {
if (isset($diff)) {
$diffs[] = $diff;
}
$diff = new Diff;
preg_match('/^diff --[\S]+ (a\/)?([\S]+)( b\/)?/', $log, $name);
$diff->setFile($name[2]);
continue;
}
if ('index' === substr($log, 0, 5)) {
$diff->setIndex($log);
continue;
}
if ('---' === substr($log, 0, 3)) {
$diff->setOld($log);
continue;
}
if ('+++' === substr($log, 0, 3)) {
$diff->setNew($log);
continue;
}
// Handle binary files properly.
if ('Binary' === substr($log, 0, 6)) {
$m = array();
if (preg_match('/Binary files (.+) and (.+) differ/', $log, $m)) {
$diff->setOld($m[1]);
$diff->setNew(" {$m[2]}");
}
}
if (!empty($log)) {
switch ($log[0]) {
case "@":
// Set the line numbers
preg_match('/@@ -([0-9]+)/', $log, $matches);
$lineNumOld = $matches[1] - 1;
$lineNumNew = $matches[1] - 1;
break;
case "-":
$lineNumOld++;
break;
case "+":
$lineNumNew++;
break;
default:
$lineNumOld++;
$lineNumNew++;
}
} else {
$lineNumOld++;
$lineNumNew++;
}
$diff->addLine($log, $lineNumOld, $lineNumNew);
}
if (isset($diff)) {
$diffs[] = $diff;
}
$commit->setDiffs($diffs);
return $commit;
}
public function getAuthorStatistics()
{
$logs = $this->getClient()->run($this, 'log --pretty=format:"%an||%ae" ' . $this->getHead());
if (empty($logs)) {
throw new \RuntimeException('No statistics available');
}
$logs = explode("\n", $logs);
$logs = array_count_values($logs);
arsort($logs);
foreach ($logs as $user => $count) {
$user = explode('||', $user);
$data[] = array('name' => $user[0], 'email' => $user[1], 'commits' => $count);
}
return $data;
}
/**
* Get the current HEAD.
*
* @return string the name of the HEAD branch.
*/
public function getHead()
{
if (file_exists($this->getPath() . '/.git/HEAD')) {
$file = @file_get_contents($this->getPath() . '/.git/HEAD');
} elseif (file_exists($this->getPath() . '/HEAD')) {
$file = @file_get_contents($this->getPath() . '/HEAD');
} else {
return 'master';
}
// Find first existing branch
foreach (explode("\n", $file) as $line) {
$m = array();
if (preg_match('#ref:\srefs/heads/(.+)#', $line, $m)) {
if ($this->hasBranch($m[1])) {
return $m[1];
}
}
}
// Default to something sane if in a detached HEAD state.
$branches = $this->getBranches();
if (!empty($branches)) {
return current($branches);
}
return 'master';
}
public function getStatistics($branch)
{
// Calculate amount of files, extensions and file size
$logs = $this->getClient()->run($this, 'ls-tree -r -l ' . $branch);
$lines = explode("\n", $logs);
$files = array();
$data['extensions'] = array();
$data['size'] = 0;
$data['files'] = 0;
foreach ($lines as $key => $line) {
if (empty($line)) {
unset($lines[$key]);
continue;
}
$files[] = preg_split("/[\s]+/", $line);
}
foreach ($files as $file) {
if ($file[1] == 'blob') {
$data['files']++;
}
if (is_numeric($file[3])) {
$data['size'] += $file[3];
}
if (($pos = strrpos($file[4], '.')) !== FALSE) {
$data['extensions'][] = substr($file[4], $pos);
}
}
$data['extensions'] = array_count_values($data['extensions']);
arsort($data['extensions']);
return $data;
}
/**
* Extract the tree hash for a given branch or tree reference
*
* @param string $branch
* @return string
*/
public function getBranchTree($branch)
{
$hash = $this->getClient()->run($this, "log --pretty=\"%T\" --max-count=1 $branch");
$hash = trim($hash, "\r\n ");
return $hash ? : false;
}
/**
* Create a TAR or ZIP archive of a git tree
*
* @param string $tree Tree-ish reference
* @param string $output Output File name
* @param string $format Archive format
*/
public function createArchive($tree, $output, $format = 'zip')
{
$fs = new Filesystem;
$fs->mkdir(dirname($output));
$this->getClient()->run($this, "archive --format=$format --output=$output $tree");
}
/**
* Get the Tree for the provided folder
*
* @param string $tree Folder that will be parsed
* @return Tree Instance of Tree for the provided folder
*/
public function getTree($tree)
{
$tree = new Tree($tree, $this->getClient(), $this);
$tree->parse();
return $tree;
}
/**
* Get the Blob for the provided file
*
* @param string $blob File that will be parsed
* @return Blob Instance of Blob for the provided file
*/
public function getBlob($blob)
{
return new Blob($blob, $this->getClient(), $this);
}
/**
* Blames the provided file and parses the output
*
* @param string $file File that will be blamed
* @return array Commits hashes containing the lines
*/
public function getBlame($file)
{
$blame = array();
$logs = $this->getClient()->run($this, "blame -s $file");
$logs = explode("\n", $logs);
$i = 0;
$previous_commit = '';
foreach ($logs as $log) {
if ($log == '') {
continue;
}
preg_match_all("/([a-zA-Z0-9^]{8})\s+.*?([0-9]+)\)(.+)/", $log, $match);
$current_commit = $match[1][0];
$current_commit = str_replace('^', '', $current_commit);
if ($current_commit != $previous_commit) {
++$i;
$blame[$i] = array('line' => '', 'commit' => $current_commit);
}
$blame[$i]['line'] .= PHP_EOL . $match[3][0];
$previous_commit = $current_commit;
}
return $blame;
}
/**
* Get the current Repository path
*
* @return string Path where the repository is located
*/
public function getPath()
{
return $this->path;
}
/**
* Set the current Repository path
*
* @param string $path Path where the repository is located
*/
public function setPath($path)
{
$this->path = $path;
}
}