forked from elkuku/patchtester
-
Notifications
You must be signed in to change notification settings - Fork 45
/
PullModel.php
1074 lines (916 loc) · 25.4 KB
/
PullModel.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
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
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Patch testing component for the Joomla! CMS
*
* @copyright Copyright (C) 2011 - 2012 Ian MacLennan, Copyright (C) 2013 - 2018 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later
*/
namespace PatchTester\Model;
use Joomla\Archive\Zip;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Factory;
use Joomla\CMS\Filesystem\Path;
use Joomla\CMS\Http\HttpFactory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Version;
use Joomla\Filesystem\File;
use Joomla\Filesystem\Folder;
use Joomla\Registry\Registry;
use PatchTester\GitHub\Exception\UnexpectedResponse;
use PatchTester\GitHub\GitHub;
use PatchTester\Helper;
use RuntimeException;
use stdClass;
/**
* Methods supporting pull requests.
*
* @since 2.0
*/
class PullModel extends AbstractModel
{
/**
* Array containing top level non-production folders
*
* @var array
* @since 2.0
*/
protected $nonProductionFolders = array(
'build',
'docs',
'installation',
'tests',
'.github',
);
/**
* Array containing non-production files
*
* @var array
* @since 2.0
*/
protected $nonProductionFiles = array(
'.drone.yml',
'.gitignore',
'.php_cs',
'.travis.yml',
'README.md',
'build.xml',
'composer.json',
'composer.lock',
'phpunit.xml.dist',
'robots.txt.dist',
'travisci-phpunit.xml',
'LICENSE',
'RoboFile.dist.ini',
'RoboFile.php',
'codeception.yml',
'jorobo.dist.ini',
'manifest.xml',
'crowdin.yaml',
);
/**
* The namespace mapper
*
* @var \JNamespacePsr4Map
* @since 4.0.0
*/
protected $namespaceMapper;
/**
* Instantiate the model.
*
* @param Registry $state The model state.
* @param \JDatabaseDriver $db The database adpater.
*
* @since 4.0.0
*/
public function __construct(Registry $state = null, \JDatabaseDriver $db = null)
{
parent::__construct($state, $db);
$this->namespaceMapper = new \JNamespacePsr4Map;
}
/**
* Patches the code with the supplied pull request
* However uses different methods for different repositories.
*
* @param integer $id ID of the pull request to apply
*
* @return boolean
*
* @since 3.0
*
* @throws RuntimeException
*/
public function apply(int $id): bool
{
$params = ComponentHelper::getParams('com_patchtester');
// Decide based on repository settings whether patch will be applied through Github or CIServer
if ((bool) $params->get('ci_switch', 0))
{
return $this->applyWithCIServer($id);
}
return $this->applyWithGitHub($id);
}
/**
* Patches the code with the supplied pull request
*
* @param integer $id ID of the pull request to apply
*
* @return boolean
*
* @since 3.0
*
* @throws RuntimeException
*/
private function applyWithCIServer(int $id): bool
{
// Get the CIServer Registry
$ciSettings = Helper::initializeCISettings();
// Get the Github object
$github = Helper::initializeGithub();
// Retrieve pullData for sha later on.
$pull = $this->retrieveGitHubData($github, $id);
if ($pull->head->repo === null)
{
throw new RuntimeException(Text::_('COM_PATCHTESTER_REPO_IS_GONE'));
}
$sha = $pull->head->sha;
// Create tmp folder if it does not exist
if (!file_exists($ciSettings->get('folder.temp')))
{
Folder::create($ciSettings->get('folder.temp'));
}
$tempPath = $ciSettings->get('folder.temp') . '/' . $id;
$backupsPath = $ciSettings->get('folder.backups') . '/' . $id;
$delLogPath = $tempPath . '/' . $ciSettings->get('zip.log.name');
$zipPath = $tempPath . '/' . $ciSettings->get('zip.name');
$serverZipPath = sprintf($ciSettings->get('zip.url'), $id);
// Patch has already been applied
if (file_exists($backupsPath))
{
return false;
}
$version = new Version;
$httpOption = new Registry;
$httpOption->set('userAgent', $version->getUserAgent('Joomla', true, false));
// Try to download the zip file
try
{
$http = HttpFactory::getHttp($httpOption);
$result = $http->get($serverZipPath);
}
catch (RuntimeException $e)
{
$result = null;
}
if ($result === null || ($result->getStatusCode() !== 200 && $result->getStatusCode() !== 310))
{
throw new RuntimeException(Text::_('COM_PATCHTESTER_SERVER_RESPONDED_NOT_200'));
}
// Assign to variable to avlod PHP notice "Indirect modification of overloaded property"
$content = (string) $result->getBody();
// Write the file to disk
File::write($zipPath, $content);
// Check if zip folder could have been downloaded
if (!file_exists($zipPath))
{
throw new RuntimeException(Text::_('COM_PATCHTESTER_ZIP_DOES_NOT_EXIST'));
}
Folder::create($tempPath);
$zip = new Zip;
if (!$zip->extract($zipPath, $tempPath))
{
Folder::delete($tempPath);
throw new RuntimeException(Text::_('COM_PATCHTESTER_ZIP_EXTRACT_FAILED'));
}
// Remove zip to avoid get listing afterwards
File::delete($zipPath);
// Verify the composer autoloader for any invalid entries
if ($this->verifyAutoloader($tempPath) === false)
{
// There is something broken in the autoloader, clean up and go back
Folder::delete($tempPath);
throw new RuntimeException(Text::_('COM_PATCHTESTER_PATCH_BREAKS_SITE'));
}
// Get files from deleted_logs
$deletedFiles = (file_exists($delLogPath) ? file($delLogPath) : []);
$deletedFiles = array_map('trim', $deletedFiles);
if (file_exists($delLogPath))
{
// Remove deleted_logs to avoid get listing afterwards
File::delete($delLogPath);
}
// Retrieve all files and merge them into one array
$files = Folder::files($tempPath, null, true, true);
$files = str_replace(Path::clean($tempPath . '\\'), '', $files);
$files = array_merge($files, $deletedFiles);
Folder::create($backupsPath);
// Moves existent files to backup and replace them or creates new one if they don't exist
foreach ($files as $key => $file)
{
try
{
$filePath = explode(DIRECTORY_SEPARATOR, Path::clean($file));
array_pop($filePath);
$filePath = implode(DIRECTORY_SEPARATOR, $filePath);
// Deleted_logs returns files as well as folder, if value is folder, unset and skip
if (is_dir(JPATH_ROOT . '/' . $file))
{
unset($files[$key]);
continue;
}
if (file_exists(JPATH_ROOT . '/' . $file))
{
// Create directories if they don't exist until file
if (!file_exists($backupsPath . '/' . $filePath))
{
Folder::create($backupsPath . '/' . $filePath);
}
File::move(JPATH_ROOT . '/' . $file, $backupsPath . '/' . $file);
}
if (file_exists($tempPath . '/' . $file))
{
// Create directories if they don't exist until file
if (!file_exists(JPATH_ROOT . '/' . $filePath) || !is_dir(JPATH_ROOT . '/' . $filePath))
{
Folder::create(JPATH_ROOT . '/' . $filePath);
}
File::copy($tempPath . '/' . $file, JPATH_ROOT . '/' . $file);
}
}
catch (RuntimeException $exception)
{
Folder::delete($tempPath);
Folder::move($backupsPath, $backupsPath . '_failed');
throw new RuntimeException(
Text::sprintf('COM_PATCHTESTER_FAILED_APPLYING_PATCH', $file, $exception->getMessage())
);
}
}
// Clear temp folder and store applied patch in database
Folder::delete($tempPath);
$this->saveAppliedPatch($id, $files, $sha);
// Update the autoloader file
$this->namespaceMapper->create();
// Change the media version
$version = new Version;
$version->refreshMediaVersion();
return true;
}
/**
* Patches the code with the supplied pull request
*
* @param GitHub $github github object
* @param integer $id Id of the pull request
*
* @return stdClass The pull request data
*
* @since 2.0
*
* @throws RuntimeException
*/
private function retrieveGitHubData(GitHub $github, int $id): stdClass
{
try
{
$rateResponse = $github->getRateLimit();
$rate = json_decode($rateResponse->body, false);
}
catch (UnexpectedResponse $exception)
{
throw new RuntimeException(
Text::sprintf('COM_PATCHTESTER_COULD_NOT_CONNECT_TO_GITHUB', $exception->getMessage()),
$exception->getCode(),
$exception
);
}
// If over the API limit, we can't build this list
if ((int) $rate->resources->core->remaining === 0)
{
throw new RuntimeException(
Text::sprintf('COM_PATCHTESTER_API_LIMIT_LIST', Factory::getDate($rate->resources->core->reset))
);
}
try
{
$pullResponse = $github->getPullRequest(
$this->getState()->get('github_user'),
$this->getState()->get('github_repo'),
$id
);
$pull = json_decode($pullResponse->body, false);
}
catch (UnexpectedResponse $exception)
{
throw new RuntimeException(
Text::sprintf('COM_PATCHTESTER_COULD_NOT_CONNECT_TO_GITHUB', $exception->getMessage()),
$exception->getCode(),
$exception
);
}
return $pull;
}
/**
* Verify if the autoload contains any broken entries.
*
* @param string $path The path to look for the autoloader
*
* @return boolean True if there are broken dependencies | False otherwise.
*
* @since 4.0.0
*/
private function verifyAutoloader(string $path): bool
{
$result = false;
// Check if we have an autoload file
if (!file_exists($path . '/libraries/vendor/autoload.php'))
{
return $result;
}
$composerFiles = [
'autoload_static.php',
'autoload_files.php',
'autoload_classmap.php',
'autoload_namespaces.php',
'autoload_psr4.php',
];
$filesToCheck = [];
array_walk(
$composerFiles,
static function ($composerFile) use (&$filesToCheck, $path) {
if (file_exists($path . '/libraries/vendor/composer/' . $composerFile) === false)
{
return;
}
if ($composerFile === 'autoload_static.php')
{
// Get the generated token
$autoload = file_get_contents($path . '/libraries/vendor/autoload.php');
$resultMatch = preg_match('/ComposerAutoloaderInit(.*)::/', $autoload, $match);
if (!$resultMatch)
{
return;
}
// Check if the class is already defined
$autoloadClass = '\Composer\Autoload\ComposerStaticInit' . $match[1];
if (class_exists($autoloadClass))
{
return;
}
require_once $path . '/libraries/vendor/composer/autoload_static.php';
// Get all the files
$files = $autoloadClass::$files;
$filesToCheck = array_merge($filesToCheck, $files);
}
else
{
$files = require $path . '/libraries/vendor/composer/' . $composerFile;
$filesToCheck = array_merge($filesToCheck, $files);
}
}
);
return $this->checkFilesExist($filesToCheck, $path);
}
/**
* Check a list of files if they exist.
*
* @param array $files The list of files to check
* @param string $path The path where the temporary patch resides
*
* @return boolean True if all files exist | False otherwise.
*
* @since 4.0.0
*/
private function checkFilesExist(array $files, string $path): bool
{
$path = Path::clean($path);
foreach ($files as $file)
{
if (is_array($file))
{
$this->checkFilesExist($file, $path);
}
elseif (!file_exists($file))
{
// Check if the file exists in the Joomla filesystem
$file = str_ireplace($path, JPATH_SITE, $file);
if (!file_exists($file))
{
return false;
}
}
}
return true;
}
/**
* Saves the applied patch into database
*
* @param integer $id ID of the applied pull request
* @param array $fileList List of files
* @param string $sha sha-key from pull request
*
* @return integer $id last inserted id
*
* @since 3.0
*/
private function saveAppliedPatch(int $id, array $fileList, string $sha = null): int
{
$record = (object) array(
'pull_id' => $id,
'data' => json_encode($fileList),
'patched_by' => Factory::getUser()->id,
'applied' => 1,
'applied_version' => JVERSION,
);
$db = $this->getDb();
$db->insertObject('#__patchtester_tests', $record);
$insertId = $db->insertid();
if ($sha !== null)
{
// Insert the retrieved commit SHA into the pulls table for this item
$db->setQuery(
$db->getQuery(true)
->update('#__patchtester_pulls')
->set('sha = ' . $db->quote($sha))
->where($db->quoteName('pull_id') . ' = ' . $id)
)->execute();
}
return $insertId;
}
/**
* Patches the code with the supplied pull request
*
* @param integer $id ID of the pull request to apply
*
* @return boolean
*
* @since 2.0
*
* @throws RuntimeException
*/
private function applyWithGitHub(int $id): bool
{
// Get the Github object
$github = Helper::initializeGithub();
$pull = $this->retrieveGitHubData($github, $id);
if ($pull->head->repo === null)
{
throw new RuntimeException(Text::_('COM_PATCHTESTER_REPO_IS_GONE'));
}
try
{
$filesResponse = $github->getFilesForPullRequest(
$this->getState()->get('github_user'),
$this->getState()->get('github_repo'),
$id
);
$files = json_decode($filesResponse->body, false);
}
catch (UnexpectedResponse $exception)
{
throw new RuntimeException(
Text::sprintf('COM_PATCHTESTER_COULD_NOT_CONNECT_TO_GITHUB', $exception->getMessage()),
$exception->getCode(),
$exception
);
}
if (!count($files))
{
return false;
}
$parsedFiles = $this->parseFileList($files);
if (!count($parsedFiles))
{
return false;
}
foreach ($parsedFiles as $file)
{
switch ($file->action)
{
case 'deleted':
if (!file_exists(JPATH_ROOT . '/' . $file->filename))
{
throw new RuntimeException(
Text::sprintf('COM_PATCHTESTER_FILE_DELETED_DOES_NOT_EXIST_S', $file->filename)
);
}
break;
case 'added':
case 'modified':
case 'renamed':
// If the backup file already exists, we can't apply the patch
if (file_exists(JPATH_COMPONENT . '/backups/' . md5($file->filename) . '.txt'))
{
throw new RuntimeException(Text::sprintf('COM_PATCHTESTER_CONFLICT_S', $file->filename));
}
if ($file->action === 'modified' && !file_exists(JPATH_ROOT . '/' . $file->filename))
{
throw new RuntimeException(
Text::sprintf('COM_PATCHTESTER_FILE_MODIFIED_DOES_NOT_EXIST_S', $file->filename)
);
}
try
{
$contentsResponse = $github->getFileContents(
$pull->head->user->login,
$pull->head->repo->name,
$file->repofilename,
urlencode($pull->head->ref)
);
$contents = json_decode($contentsResponse->body, false);
// In case encoding type ever changes
switch ($contents->encoding)
{
case 'base64':
$file->body = base64_decode($contents->content);
break;
default:
throw new RuntimeException(Text::_('COM_PATCHTESTER_ERROR_UNSUPPORTED_ENCODING'));
}
}
catch (UnexpectedResponse $exception)
{
throw new RuntimeException(
Text::sprintf('COM_PATCHTESTER_COULD_NOT_CONNECT_TO_GITHUB', $exception->getMessage()),
$exception->getCode(),
$exception
);
}
break;
}
}
// At this point, we have ensured that we have all the new files and there are no conflicts
foreach ($parsedFiles as $file)
{
// We only create a backup if the file already exists
if ($file->action === 'deleted'
|| (file_exists(JPATH_ROOT . '/' . $file->filename)
&& $file->action === 'modified')
|| (file_exists(JPATH_ROOT . '/' . $file->originalFile) && $file->action === 'renamed'))
{
$filename = $file->action === 'renamed' ? $file->originalFile : $file->filename;
$src = JPATH_ROOT . '/' . $filename;
$dest = JPATH_COMPONENT . '/backups/' . md5($filename) . '.txt';
if (!File::copy(Path::clean($src), $dest))
{
throw new RuntimeException(Text::sprintf('COM_PATCHTESTER_ERROR_CANNOT_COPY_FILE', $src, $dest));
}
}
switch ($file->action)
{
case 'modified':
case 'added':
if (!File::write(Path::clean(JPATH_ROOT . '/' . $file->filename), $file->body))
{
throw new RuntimeException(
Text::sprintf('COM_PATCHTESTER_ERROR_CANNOT_WRITE_FILE', JPATH_ROOT . '/' . $file->filename)
);
}
break;
case 'deleted':
if (!File::delete(Path::clean(JPATH_ROOT . '/' . $file->filename)))
{
throw new RuntimeException(
Text::sprintf(
'COM_PATCHTESTER_ERROR_CANNOT_DELETE_FILE',
JPATH_ROOT . '/' . $file->filename
)
);
}
break;
case 'renamed':
if (!File::delete(Path::clean(JPATH_ROOT . '/' . $file->originalFile)))
{
throw new RuntimeException(
Text::sprintf(
'COM_PATCHTESTER_ERROR_CANNOT_DELETE_FILE',
JPATH_ROOT . '/' . $file->originalFile
)
);
}
if (!File::write(Path::clean(JPATH_ROOT . '/' . $file->filename), $file->body))
{
throw new RuntimeException(
Text::sprintf('COM_PATCHTESTER_ERROR_CANNOT_WRITE_FILE', JPATH_ROOT . '/' . $file->filename)
);
}
break;
}
// We don't need the file's body any longer (and it causes issues with binary data when json_encode() is run), so remove it
unset($file->body);
}
$this->saveAppliedPatch($pull->number, $parsedFiles, $pull->head->sha);
// Update the autoloader file
$this->namespaceMapper->create();
// Change the media version
$version = new Version;
$version->refreshMediaVersion();
return true;
}
/**
* Parse the list of modified files from a pull request
*
* @param stdClass $files The modified files to parse
*
* @return array
*
* @since 3.0.0
*/
private function parseFileList(array $files): array
{
$parsedFiles = array();
/*
* Check if the patch tester is running in a development environment
* If we are not in development, we'll need to check the exclusion lists
*/
$isDev = file_exists(JPATH_INSTALLATION . '/index.php');
foreach ($files as $file)
{
if (!$isDev)
{
$filePath = explode('/', $file->filename);
if (in_array($filePath[0], $this->nonProductionFiles, true))
{
continue;
}
if (in_array($filePath[0], $this->nonProductionFolders, true))
{
continue;
}
}
// Sometimes the repo filename is not the production file name
$prodFileName = $file->filename;
$prodRenamedFileName = $file->previous_filename ?? false;
$filePath = explode('/', $prodFileName);
// Remove the `src` here to match the CMS paths if needed
if ($filePath[0] === 'src')
{
$prodFileName = str_replace('src/', '', $prodFileName);
}
if ($prodRenamedFileName)
{
$filePath = explode('/', $prodRenamedFileName);
// Remove the `src` here to match the CMS paths if needed
if ($filePath[0] === 'src')
{
$prodRenamedFileName = str_replace('src/', '', $prodRenamedFileName);
}
}
$parsedFiles[] = (object) array(
'action' => $file->status,
'filename' => $prodFileName,
'repofilename' => $file->filename,
'fileurl' => $file->contents_url,
'originalFile' => $prodRenamedFileName,
);
}
return $parsedFiles;
}
/**
* Reverts the specified pull request
* However uses different methods for different repositories.
*
* @param integer $id ID of the pull request to revert
*
* @return boolean
*
* @since 3.0
* @throws RuntimeException
*/
public function revert(int $id): bool
{
$params = ComponentHelper::getParams('com_patchtester');
// Decide based on repository settings whether patch will be applied through Github or CIServer
if ((bool) $params->get('ci_switch', 0))
{
return $this->revertWithCIServer($id);
}
return $this->revertWithGitHub($id);
}
/**
* Reverts the specified pull request with CIServer options
*
* @param integer $id ID of the pull request to revert
*
* @return boolean
*
* @since 3.0
* @throws RuntimeException
*/
public function revertWithCIServer(int $id): bool
{
// Get the CIServer Registry
$ciSettings = Helper::initializeCISettings();
$testRecord = $this->getTestRecord($id);
// We don't want to restore files from an older version
if ($testRecord->applied_version !== JVERSION)
{
return $this->removeTest($testRecord);
}
$files = json_decode($testRecord->data, false);
if (!$files)
{
throw new RuntimeException(
Text::sprintf(
'COM_PATCHTESTER_ERROR_READING_DATABASE_TABLE',
__METHOD__,
htmlentities($testRecord->data)
)
);
}
$backupsPath = $ciSettings->get('folder.backups') . "/$testRecord->pull_id";
foreach ($files as $file)
{
try
{
$filePath = explode("\\", $file);
array_pop($filePath);
$filePath = implode("\\", $filePath);
// Delete file from root of it exists
if (file_Exists(JPATH_ROOT . "/$file"))
{
File::delete(JPATH_ROOT . "/$file");
// Move from backup, if it exists there
if (file_exists($backupsPath . '/' . $file))
{
File::move($backupsPath . '/' . $file, JPATH_ROOT . '/' . $file);
}
// If folder is empty, remove it as well
if (count(glob(JPATH_ROOT . '/' . $filePath . '/*')) === 0)
{
Folder::delete(JPATH_ROOT . '/' . $filePath);
}
}
// Move from backup, if file exists there - got deleted by patch
elseif (file_exists($backupsPath . '/' . $file))
{
if (!file_exists(JPATH_ROOT . '/' . $filePath))
{
Folder::create(JPATH_ROOT . '/' . $filePath);
}
File::move($backupsPath . '/' . $file, JPATH_ROOT . '/' . $file);
}
}
catch (RuntimeException $exception)
{
throw new RuntimeException(
Text::sprintf('COM_PATCHTESTER_FAILED_REVERT_PATCH', $file, $exception->getMessage())
);
}
}
Folder::delete($backupsPath);
// Update the autoloader file
$this->namespaceMapper->create();
// Change the media version
$version = new Version;
$version->refreshMediaVersion();
return $this->removeTest($testRecord);
}
/**
* Retrieves test data from database by specific id
*
* @param integer $id ID of the record
*
* @return stdClass $testRecord The record looking for
*
* @since 3.0.0
*/
private function getTestRecord(int $id): stdClass
{
$db = $this->getDb();
return $db->setQuery(
$db->getQuery(true)
->select('*')
->from('#__patchtester_tests')
->where('id = ' . (int) $id)
)->loadObject();
}
/**
* Remove the database record for a test
*
* @param stdClass $testRecord The record being deleted
*
* @return boolean
*
* @since 3.0.0
*/
private function removeTest(stdClass $testRecord): bool
{
$db = $this->getDb();
// Remove the retrieved commit SHA from the pulls table for this item
$db->setQuery(
$db->getQuery(true)
->update('#__patchtester_pulls')
->set('sha = ' . $db->quote(''))
->where($db->quoteName('id') . ' = ' . (int) $testRecord->id)
)->execute();
// And delete the record from the tests table
$db->setQuery(
$db->getQuery(true)
->delete('#__patchtester_tests')
->where('id = ' . (int) $testRecord->id)
)->execute();
return true;
}
/**
* Reverts the specified pull request with Github Requests
*
* @param integer $id ID of the pull request to revert
*
* @return boolean
*
* @since 2.0
* @throws RuntimeException
*/
public function revertWithGitHub(int $id): bool
{
$testRecord = $this->getTestRecord($id);
// We don't want to restore files from an older version
if ($testRecord->applied_version != JVERSION)
{
return $this->removeTest($testRecord);
}
$files = json_decode($testRecord->data, false);
if (!$files)
{
throw new RuntimeException(
Text::sprintf(
'COM_PATCHTESTER_ERROR_READING_DATABASE_TABLE',
__METHOD__,
htmlentities($testRecord->data)
)
);
}
foreach ($files as $file)
{
switch ($file->action)
{
case 'deleted':
case 'modified':
$src = JPATH_COMPONENT . '/backups/' . md5($file->filename) . '.txt';
$dest = JPATH_ROOT . '/' . $file->filename;
if (!File::copy($src, $dest))
{
throw new RuntimeException(
Text::sprintf('COM_PATCHTESTER_ERROR_CANNOT_COPY_FILE', $src, $dest)
);
}