-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathGitRepo.php
More file actions
800 lines (748 loc) · 23.3 KB
/
GitRepo.php
File metadata and controls
800 lines (748 loc) · 23.3 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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
<?php
namespace woolfg\dokuwiki\plugin\gitbacked;
// phpcs:disable PSR1.Files.SideEffects.FoundWithSymbols
if (__FILE__ == $_SERVER['SCRIPT_FILENAME']) die('Bad load order');
/**
* Git Repository Interface Class
*
* This class enables the creating, reading, and manipulation
* of a git repository
*
* @class GitRepo
*/
class GitRepo
{
// This regex will filter a probable password from any string containing a Git URL.
// Limitation: it will work for the first git URL occurrence in a string.
// Used https://regex101.com/ for evaluating!
public const REGEX_GIT_URL_FILTER_PWD = "/^(.*)((http:)|(https:))([^:]+)(:[^@]*)?(.*)/im";
public const REGEX_GIT_URL_FILTER_PWD_REPLACE_PATTERN = "$1$2$5$7";
protected $repo_path;
protected $bare = false;
protected $envopts = [];
// Fix for PHP <=7.3 compatibility: Type declarations for properties work since PHP >= 7.4 only.
// protected ?\action_plugin_gitbacked_editcommit $plugin = null;
protected $plugin;
/**
* Create a new git repository
*
* Accepts a creation path, and, optionally, a source path
*
* @access public
* @param string repository path
* @param \action_plugin_gitbacked_editcommit plugin
* @param string directory to source
* @param string reference path
* @return GitRepo or null in case of an error
*/
public static function &createNew(
$repo_path,
\action_plugin_gitbacked_editcommit $plugin = null,
$source = null,
$remote_source = false,
$reference = null
) {
if (is_dir($repo_path) && file_exists($repo_path . "/.git") && is_dir($repo_path . "/.git")) {
throw new \Exception(self::handleCreateNewError(
$repo_path,
$reference,
'"' . $repo_path . '" is already a git repository',
$plugin
));
} else {
$repo = new self($repo_path, $plugin, true, false);
if (is_string($source)) {
if ($remote_source) {
if (!is_dir($reference) || !is_dir($reference . '/.git')) {
throw new \Exception(self::handleCreateNewError(
$repo_path,
$reference,
'"' . $reference . '" is not a git repository. Cannot use as reference.',
$plugin
));
} elseif (strlen($reference)) {
$reference = realpath($reference);
$reference = "--reference $reference";
}
$repo->cloneRemote($source, $reference);
} else {
$repo->cloneFrom($source);
}
} else {
$repo->run('init');
}
return $repo;
}
}
/**
* Constructor
*
* Accepts a repository path
*
* @access public
* @param string repository path
* @param \action_plugin_gitbacked_editcommit plugin
* @param bool create if not exists?
* @return void
*/
public function __construct(
$repo_path = null,
\action_plugin_gitbacked_editcommit $plugin = null,
$create_new = false,
$_init = true
) {
$this->plugin = $plugin;
if (is_string($repo_path)) {
$this->setRepoPath($repo_path, $create_new, $_init);
}
}
/**
* Set the repository's path
*
* Accepts the repository path
*
* @access public
* @param string repository path
* @param bool create if not exists?
* @param bool initialize new Git repo if not exists?
* @return void
*/
public function setRepoPath($repo_path, $create_new = false, $_init = true)
{
if (is_string($repo_path)) {
if ($new_path = realpath($repo_path)) {
$repo_path = $new_path;
if (is_dir($repo_path)) {
$next_parent_repo_path = $this->absoluteGitDir($repo_path);
if (!empty($next_parent_repo_path)) {
$this->repo_path = $next_parent_repo_path;
$this->bare = false;
// Is this a work tree?
} elseif (file_exists($repo_path . "/.git") && is_dir($repo_path . "/.git")) {
$this->repo_path = $repo_path;
$this->bare = false;
// Is this a bare repo?
} elseif (is_file($repo_path . "/config")) {
$parse_ini = parse_ini_file($repo_path . "/config");
if ($parse_ini['bare']) {
$this->repo_path = $repo_path;
$this->bare = true;
}
} elseif ($create_new) {
$this->repo_path = $repo_path;
if ($_init) {
$this->run('init');
}
} elseif (!$_init) {
// If we do not have to init the repo, we just reflect that there is no repo path yet.
// This may be the case for auto determining repos,
// if there is no repo related to the current resource going to be commited.
$this->repo_path = '';
} else {
throw new \Exception($this->handleRepoPathError(
$repo_path,
'"' . $repo_path . '" is not a git repository'
));
}
} else {
throw new \Exception($this->handleRepoPathError(
$repo_path,
'"' . $repo_path . '" is not a directory'
));
}
} elseif ($create_new) {
if ($parent = realpath(dirname($repo_path))) {
mkdir($repo_path);
$this->repo_path = $repo_path;
if ($_init) $this->run('init');
} else {
throw new \Exception($this->handleRepoPathError(
$repo_path,
'cannot create repository in non-existent directory'
));
}
} else {
throw new \Exception($this->handleRepoPathError(
$repo_path,
'"' . $repo_path . '" does not exist'
));
}
}
}
/**
* Get the path to the repo directory
*
* @access public
* @return string
*/
public function getRepoPath()
{
return $this->repo_path;
}
/**
* Get the path to the git repo directory (eg. the ".git" directory)
*
* @access public
* @return string
*/
public function gitDirectoryPath()
{
return ($this->bare) ? $this->repo_path : $this->repo_path . "/.git";
}
/**
* Tests if git is installed
*
* @access public
* @return bool
*/
public function testGit()
{
$descriptorspec = [1 => ['pipe', 'w'], 2 => ['pipe', 'w']];
$pipes = [];
$resource = proc_open(Git::getBin(), $descriptorspec, $pipes);
stream_get_contents($pipes[1]);
stream_get_contents($pipes[2]);
foreach ($pipes as $pipe) {
fclose($pipe);
}
$status = trim(proc_close($resource));
return ($status != 127);
}
/**
* Determine closest parent git repository for a given path as absolute PHP realpath().
*
* @access public
* @return string the next parent git repo root dir as absolute PHP realpath()
* or empty string, if no parent repo found.
*/
public function absoluteGitDir($path)
{
$descriptorspec = [1 => ['pipe', 'w'], 2 => ['pipe', 'w']];
$pipes = [];
// Using --git-dir rather than --absolute-git-dir for a wider git versions compatibility
//$command = Git::getBin() . " rev-parse --absolute-git-dir";
$command = Git::getBin() . " rev-parse --git-dir";
//dbglog("GitBacked - Command: ".$command);
$resource = proc_open($command, $descriptorspec, $pipes, $path);
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
foreach ($pipes as $pipe) {
fclose($pipe);
}
$status = trim(proc_close($resource));
if ($status == 0) {
$repo_git_dir = trim($stdout);
//dbglog("GitBacked - $command: '" . $repo_git_dir . "'");
if (!empty($repo_git_dir)) {
if (strcmp($repo_git_dir, ".git") === 0) {
// convert to absolute path based on this command execution directory
$repo_git_dir = $path . '/' . $repo_git_dir;
}
$repo_path = dirname(realpath($repo_git_dir));
//dbglog('GitBacked - $repo_path: ' . $repo_path);
if (file_exists($repo_path . "/.git") && is_dir($repo_path . "/.git")) {
return $repo_path;
}
}
}
return '';
}
/**
* Run a command in the git repository
*
* Accepts a shell command to run
*
* @access protected
* @param string command to run
* @return string or null in case of an error
*/
protected function runCommand($command)
{
//dbglog("Git->run_command: repo_path=[" . $this->repo_path . "])");
if (empty($this->repo_path)) {
throw new \Exception($this->handleRepoPathError(
$this->repo_path,
"Failure on GitRepo->runCommand(): Git command must not be run for an empty repo path"
));
}
//dbglog("Git->runCommand(command=[".$command."])");
$descriptorspec = [1 => ['pipe', 'w'], 2 => ['pipe', 'w']];
$pipes = [];
$cwd = $this->repo_path;
//dbglog("GitBacked - cwd: [".$cwd."]");
/* Provide any $this->envopts via putenv
* and call proc_open with env=null to inherit the rest
* of env variables from the original process of the system.
* Note: Variables set by putenv live for a
* single PHP request run only. These variables
* are visible "locally". They are NOT listed by getenv(),
* but they are visible to the process forked by proc_open().
*/
foreach ($this->envopts as $k => $v) {
putenv(sprintf("%s=%s", $k, $v));
}
$resource = proc_open($command, $descriptorspec, $pipes, $cwd, null);
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
foreach ($pipes as $pipe) {
fclose($pipe);
}
$status = trim(proc_close($resource));
//dbglog("GitBacked: runCommand status: ".$status);
if ($status) {
//dbglog("GitBacked - stderr: [".$stderr."]");
// Remove a probable password from the Git URL, if the URL is contained in the error message
$error_message = preg_replace(
$this::REGEX_GIT_URL_FILTER_PWD,
$this::REGEX_GIT_URL_FILTER_PWD_REPLACE_PATTERN,
$stderr
);
//dbglog("GitBacked - error_message: [".$error_message."]");
throw new \Exception($this->handleCommandError(
$this->repo_path,
$cwd,
$command,
$status,
$error_message
));
} else {
$this->handleCommandSuccess($this->repo_path, $cwd, $command);
}
return $stdout;
}
/**
* Run a git command in the git repository
*
* Accepts a git command to run
*
* @access public
* @param string command to run
* @return string
*/
public function run($command)
{
return $this->runCommand(Git::getBin() . " " . $command);
}
/**
* Handles error on create_new
*
* @access protected
* @param string repository path
* @param string error message
* @return string error message
*/
protected static function handleCreateNewError($repo_path, $reference, $error_message, $plugin)
{
if ($plugin instanceof \action_plugin_gitbacked_editcommit) {
$plugin->notifyCreateNewError($repo_path, $reference, $error_message);
}
return $error_message;
}
/**
* Handles error on setting the repo path
*
* @access protected
* @param string repository path
* @param string error message
* @return string error message
*/
protected function handleRepoPathError($repo_path, $error_message)
{
if ($this->plugin instanceof \action_plugin_gitbacked_editcommit) {
$this->plugin->notifyRepoPathError($repo_path, $error_message);
}
return $error_message;
}
/**
* Handles error on git command
*
* @access protected
* @param string repository path
* @param string current working dir
* @param string command line
* @param int exit code of command (status)
* @param string error message
* @return string error message
*/
protected function handleCommandError($repo_path, $cwd, $command, $status, $error_message)
{
if ($this->plugin instanceof \action_plugin_gitbacked_editcommit) {
$this->plugin->notifyCommandError($repo_path, $cwd, $command, $status, $error_message);
}
return $error_message;
}
/**
* Handles success on git command
*
* @access protected
* @param string repository path
* @param string current working dir
* @param string command line
* @return void
*/
protected function handleCommandSuccess($repo_path, $cwd, $command)
{
if ($this->plugin instanceof \action_plugin_gitbacked_editcommit) {
$this->plugin->notifyCommandSuccess($repo_path, $cwd, $command);
}
}
/**
* Runs a 'git status' call
*
* Accept a convert to HTML bool
*
* @access public
* @param bool return string with <br />
* @return string
*/
public function status($html = false)
{
$msg = $this->run("status");
if ($html == true) {
$msg = str_replace("\n", "<br />", $msg);
}
return $msg;
}
/**
* Runs a `git add` call
*
* Accepts a list of files to add
*
* @access public
* @param mixed files to add
* @return string
*/
public function add($files = "*")
{
if (is_array($files)) {
$files = '"' . implode('" "', $files) . '"';
}
return $this->run("add $files -v");
}
/**
* Runs a `git rm` call
*
* Accepts a list of files to remove
*
* @access public
* @param mixed files to remove
* @param Boolean use the --cached flag?
* @return string
*/
public function rm($files = "*", $cached = false)
{
if (is_array($files)) {
$files = '"' . implode('" "', $files) . '"';
}
return $this->run("rm " . ($cached ? '--cached ' : '') . $files);
}
/**
* Runs a `git commit` call
*
* Accepts a commit message string
*
* @access public
* @param string commit message
* @param boolean should all files be committed automatically (-a flag)
* @return string
*/
public function commit($message = "", $commit_all = true)
{
$flags = $commit_all ? '-av' : '-v';
$msgfile = GitBackedUtil::createMessageFile($message);
try {
return $this->run("commit --allow-empty " . $flags . " --file=" . $msgfile);
} finally {
unlink($msgfile);
}
}
/**
* Runs a `git clone` call to clone the current repository
* into a different directory
*
* Accepts a target directory
*
* @access public
* @param string target directory
* @return string
*/
public function cloneTo($target)
{
return $this->run("clone --local " . $this->repo_path . " $target");
}
/**
* Runs a `git clone` call to clone a different repository
* into the current repository
*
* Accepts a source directory
*
* @access public
* @param string source directory
* @return string
*/
public function cloneFrom($source)
{
return $this->run("clone --local $source " . $this->repo_path);
}
/**
* Runs a `git clone` call to clone a remote repository
* into the current repository
*
* Accepts a source url
*
* @access public
* @param string source url
* @param string reference path
* @return string
*/
public function cloneRemote($source, $reference)
{
return $this->run("clone $reference $source " . $this->repo_path);
}
/**
* Runs a `git clean` call
*
* Accepts a remove directories flag
*
* @access public
* @param bool delete directories?
* @param bool force clean?
* @return string
*/
public function clean($dirs = false, $force = false)
{
return $this->run("clean" . (($force) ? " -f" : "") . (($dirs) ? " -d" : ""));
}
/**
* Runs a `git branch` call
*
* Accepts a name for the branch
*
* @access public
* @param string branch name
* @return string
*/
public function createBranch($branch)
{
return $this->run("branch $branch");
}
/**
* Runs a `git branch -[d|D]` call
*
* Accepts a name for the branch
*
* @access public
* @param string branch name
* @return string
*/
public function deleteBranch($branch, $force = false)
{
return $this->run("branch " . (($force) ? '-D' : '-d') . " $branch");
}
/**
* Runs a `git branch` call
*
* @access public
* @param bool keep asterisk mark on active branch
* @return array
*/
public function listBranches($keep_asterisk = false)
{
$branchArray = explode("\n", $this->run("branch"));
foreach ($branchArray as $i => &$branch) {
$branch = trim($branch);
if (! $keep_asterisk) {
$branch = str_replace("* ", "", $branch);
}
if ($branch == "") {
unset($branchArray[$i]);
}
}
return $branchArray;
}
/**
* Lists remote branches (using `git branch -r`).
*
* Also strips out the HEAD reference (e.g. "origin/HEAD -> origin/master").
*
* @access public
* @return array
*/
public function listRemoteBranches()
{
$branchArray = explode("\n", $this->run("branch -r"));
foreach ($branchArray as $i => &$branch) {
$branch = trim($branch);
if ($branch == "" || strpos($branch, 'HEAD -> ') !== false) {
unset($branchArray[$i]);
}
}
return $branchArray;
}
/**
* Returns name of active branch
*
* @access public
* @param bool keep asterisk mark on branch name
* @return string
*/
public function activeBranch($keep_asterisk = false)
{
$branchArray = $this->listBranches(true);
$activeBranch = preg_grep("/^\*/", $branchArray);
reset($activeBranch);
if ($keep_asterisk) {
return current($activeBranch);
} else {
return str_replace("* ", "", current($activeBranch));
}
}
/**
* Runs a `git checkout` call
*
* Accepts a name for the branch
*
* @access public
* @param string branch name
* @return string
*/
public function checkout($branch)
{
return $this->run("checkout $branch");
}
/**
* Runs a `git merge` call
*
* Accepts a name for the branch to be merged
*
* @access public
* @param string $branch
* @return string
*/
public function merge($branch)
{
return $this->run("merge $branch --no-ff");
}
/**
* Runs a git fetch on the current branch
*
* @access public
* @return string
*/
public function fetch()
{
return $this->run("fetch");
}
/**
* Add a new tag on the current position
*
* Accepts the name for the tag and the message
*
* @param string $tag
* @param string $message
* @return string
*/
public function addTag($tag, $message = null)
{
if ($message === null) {
$message = $tag;
}
$msgfile = GitBackedUtil::createMessageFile($message);
try {
return $this->run("tag -a $tag --file=" . $msgfile);
} finally {
unlink($msgfile);
}
}
/**
* List all the available repository tags.
*
* Optionally, accept a shell wildcard pattern and return only tags matching it.
*
* @access public
* @param string $pattern Shell wildcard pattern to match tags against.
* @return array Available repository tags.
*/
public function listTags($pattern = null)
{
$tagArray = explode("\n", $this->run("tag -l $pattern"));
foreach ($tagArray as $i => &$tag) {
$tag = trim($tag);
if ($tag == '') {
unset($tagArray[$i]);
}
}
return $tagArray;
}
/**
* Push specific branch to a remote
*
* Accepts the name of the remote and local branch
*
* @param string $remote
* @param string $branch
* @return string
*/
public function push($remote, $branch)
{
return $this->run("push --tags $remote $branch");
}
/**
* Pull specific branch from remote
*
* Accepts the name of the remote and local branch
*
* @param string $remote
* @param string $branch
* @return string
*/
public function pull($remote, $branch)
{
return $this->run("pull $remote $branch");
}
/**
* List log entries.
*
* @param strgin $format
* @return string
*/
public function log($format = null)
{
if ($format === null) {
return $this->run('log');
} else {
return $this->run('log --pretty=format:"' . $format . '"');
}
}
/**
* Sets the project description.
*
* @param string $new
*/
public function setDescription($new)
{
$path = $this->gitDirectoryPath();
file_put_contents($path . "/description", $new);
}
/**
* Gets the project description.
*
* @return string
*/
public function getDescription()
{
$path = $this->gitDirectoryPath();
return file_get_contents($path . "/description");
}
/**
* Sets custom environment options for calling Git
*
* @param string key
* @param string value
*/
public function setenv($key, $value)
{
$this->envopts[$key] = $value;
}
}
/* End of file */