MergeRepoWorker::getPriority()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php declare(strict_types=1);
2
3
/*
4
 * This file is part of Biurad opensource projects.
5
 *
6
 * @copyright 2022 Biurad Group (https://biurad.com/)
7
 * @license   https://opensource.org/licenses/BSD-3-Clause License
8
 *
9
 * For the full copyright and license information, please view the LICENSE
10
 * file that was distributed with this source code.
11
 */
12
13
namespace Biurad\Monorepo\Worker;
14
15
use Biurad\Monorepo\{Monorepo, PriorityInterface, WorkerInterface, WorkflowCommand};
16
use Symfony\Component\Console\Input\{InputInterface, InputOption};
17
use Symfony\Component\Console\Style\SymfonyStyle;
18
19
/**
20
 * A workflow worker to merge a repository into the main repository.
21
 *
22
 * @author Divine Niiquaye Ibok <[email protected]>
23
 */
24
class MergeRepoWorker implements PriorityInterface, WorkerInterface
25
{
26
    private function __construct()
27
    {
28
    }
29
30
    /**
31
     * {@inheritdoc}
32
     */
33
    public function getPriority(): int
34
    {
35
        return 0;
36
    }
37
38
    /**
39
     * {@inheritdoc}
40
     */
41
    public function getDescription(): string
42
    {
43
        return 'Running non-existing repositories merge';
44
    }
45
46
    /**
47
     * {@inheritdoc}
48
     */
49
    public static function configure(WorkflowCommand $command): self
50
    {
51
        $command->addOption('read-tree', null, InputOption::VALUE_NONE, 'Force use read-tree merge even if filter-repo command exist');
52
53
        return new self();
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59
    public function work(Monorepo $repo, InputInterface $input, SymfonyStyle $output): int
60
    {
61
        $mainRepo = $repo->getRepository();
62
        $output->writeln('<info>Checking git filter-repo command existence...</info>');
63
64
        if ($readTree = $input->getOption('read-tree')) {
65
            $output->writeln('<warning>Using read-tree merge is dangerous and may break your repository.</warning>');
66
67
            if (!$input->getOption('quiet') && !$output->confirm('Do you want to continue?', false)) {
68
                return $mainRepo->getExitCode();
69
            }
70
        } elseif (!$mainRepo->check('filter-repo', ['-h'])) {
71
            $output->writeln('Visit <comment>https://github.com/newren/git-filter-repo</comment> and install git-filter-repo.');
72
73
            return WorkflowCommand::FAILURE;
74
        }
75
76
        if (!empty($mainRepo->run('status', ['--porcelain']))) {
77
            $output->writeln('<error>Git status shows pending changes in repo</error>');
78
79
            return WorkflowCommand::FAILURE;
80
        }
81
82
        return $repo->resolveRepository($output, static function (array $required) use ($output, $repo, $mainRepo, $readTree): int {
0 ignored issues
show
Unused Code introduced by
The import $repo is not used and could be removed.

This check looks for imports that have been defined, but are not used in the scope.

Loading history...
83
            [$url, $remote, $path, $clonePath] = $required;
84
            $output->writeln(\sprintf('<info>Rewriting %s commit history to point to %s</info>', $url, $path));
85
86
            if (!$readTree) {
87
                $mainRepo->run('filter-repo', ['--force', '--to-subdirectory-filter', $path], null, $clonePath);
88
            }
89
90
            $getRemoteBranches = $mainRepo->runConcurrent([
91
                ['config', '--add', "remote.{$remote}.fetch", "+refs/tags/*:refs/tags/{$remote}/*"],
92
                ['config', "remote.{$remote}.tagOpt", '--no-tags'],
93
                ['fetch', '--all'],
94
                ['for-each-ref', '--format="%(refname:lstrip=3)"', "refs/remotes/{$remote}"],
95
            ])[3] ?? '';
96
97
            foreach (\explode("\n", $getRemoteBranches) as $branch) {
98
                if (empty($branch = \trim($branch, '"'))) {
99
                    continue;
100
                }
101
                $hasBranch = $mainRepo->check('show-ref', ['--verify', "refs/heads/{$branch}"]);
102
                $mergeMsg = "Merge branch '{$remote}/{$branch}' into {$branch}";
103
104
                if ($readTree) {
105
                    $commands = [
106
                        ['checkout', '-b', $hasBranch ? $branch.($i = \uniqid('-')) : $branch, "{$remote}/{$branch}"],
107
                        ['rm', '-rf', '*'],
108
                        ['read-tree', '--prefix', $path.'/', "{$remote}/{$branch}"],
109
                        ['commit', '-m', "Added remote-tracking {$remote}/{$branch}", '--allow-empty'],
110
                        ['reset', '--quiet', '--hard'],
111
                    ];
112
113
                    if ($hasBranch) {
114
                        $commands[] = ['checkout', $branch];
115
                        $commands[] = ['merge', '--allow-unrelated-histories', $branch.$i, '-m', $mergeMsg];
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $i does not seem to be defined for all execution paths leading up to this point.
Loading history...
116
                        $commands[] = ['branch', '-D', $branch.$i];
117
                    }
118
                } else {
119
                    $commands = [
120
                        ['checkout', '--quiet', "{$remote}/{$branch}"],
121
                        ['switch', '--quiet', ...($hasBranch ? [$branch] : ['-c', $branch])],
122
                        ['merge', "{$remote}/{$branch}", '--allow-unrelated-histories', '--no-edit', '--no-verify', '--quiet', '-m', $mergeMsg],
123
                    ];
124
                }
125
126
                $mainRepo->runConcurrent($commands);
127
            }
128
129
            if (0 === $merged = $mainRepo->getExitCode()) {
130
                $output->writeln(\sprintf('Merged "%s" into <info>%s/%s</info>', $url, $mainRepo->getPath(), \ltrim($path, '/')));
131
            }
132
133
            return $merged;
134
        }, static fn (array $v): bool => 'true' === $v[3]);
135
    }
136
}
137