| 148 |
lars |
1 |
<?php
|
|
|
2 |
|
|
|
3 |
namespace Spatie\Ignition\Solutions\SolutionProviders;
|
|
|
4 |
|
|
|
5 |
use Illuminate\Support\Str;
|
|
|
6 |
use ParseError;
|
|
|
7 |
use Spatie\Ignition\Contracts\BaseSolution;
|
|
|
8 |
use Spatie\Ignition\Contracts\HasSolutionsForThrowable;
|
|
|
9 |
use Throwable;
|
|
|
10 |
|
|
|
11 |
class MergeConflictSolutionProvider implements HasSolutionsForThrowable
|
|
|
12 |
{
|
|
|
13 |
public function canSolve(Throwable $throwable): bool
|
|
|
14 |
{
|
|
|
15 |
if (! ($throwable instanceof ParseError)) {
|
|
|
16 |
return false;
|
|
|
17 |
}
|
|
|
18 |
|
|
|
19 |
if (! $this->hasMergeConflictExceptionMessage($throwable)) {
|
|
|
20 |
return false;
|
|
|
21 |
}
|
|
|
22 |
|
|
|
23 |
$file = (string)file_get_contents($throwable->getFile());
|
|
|
24 |
|
|
|
25 |
if (! str_contains($file, '=======')) {
|
|
|
26 |
return false;
|
|
|
27 |
}
|
|
|
28 |
if (! str_contains($file, '>>>>>>>')) {
|
|
|
29 |
return false;
|
|
|
30 |
}
|
|
|
31 |
|
|
|
32 |
return true;
|
|
|
33 |
}
|
|
|
34 |
|
|
|
35 |
public function getSolutions(Throwable $throwable): array
|
|
|
36 |
{
|
|
|
37 |
$file = (string)file_get_contents($throwable->getFile());
|
|
|
38 |
preg_match('/\>\>\>\>\>\>\> (.*?)\n/', $file, $matches);
|
|
|
39 |
$source = $matches[1];
|
|
|
40 |
|
|
|
41 |
$target = $this->getCurrentBranch(basename($throwable->getFile()));
|
|
|
42 |
|
|
|
43 |
return [
|
|
|
44 |
BaseSolution::create("Merge conflict from branch '$source' into $target")
|
|
|
45 |
->setSolutionDescription('You have a Git merge conflict. To undo your merge do `git reset --hard HEAD`'),
|
|
|
46 |
];
|
|
|
47 |
}
|
|
|
48 |
|
|
|
49 |
protected function getCurrentBranch(string $directory): string
|
|
|
50 |
{
|
|
|
51 |
$branch = "'".trim((string)shell_exec("cd {$directory}; git branch | grep \\* | cut -d ' ' -f2"))."'";
|
|
|
52 |
|
|
|
53 |
if ($branch === "''") {
|
|
|
54 |
$branch = 'current branch';
|
|
|
55 |
}
|
|
|
56 |
|
|
|
57 |
return $branch;
|
|
|
58 |
}
|
|
|
59 |
|
|
|
60 |
protected function hasMergeConflictExceptionMessage(Throwable $throwable): bool
|
|
|
61 |
{
|
|
|
62 |
// For PHP 7.x and below
|
|
|
63 |
if (Str::startsWith($throwable->getMessage(), 'syntax error, unexpected \'<<\'')) {
|
|
|
64 |
return true;
|
|
|
65 |
}
|
|
|
66 |
|
|
|
67 |
// For PHP 8+
|
|
|
68 |
if (Str::startsWith($throwable->getMessage(), 'syntax error, unexpected token "<<"')) {
|
|
|
69 |
return true;
|
|
|
70 |
}
|
|
|
71 |
|
|
|
72 |
return false;
|
|
|
73 |
}
|
|
|
74 |
}
|