-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathRectorCommand.php
More file actions
291 lines (250 loc) · 9.68 KB
/
RectorCommand.php
File metadata and controls
291 lines (250 loc) · 9.68 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
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 4.0.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\Upgrade\Command;
use Cake\Console\Arguments;
use Cake\Console\BaseCommand;
use Cake\Console\ConsoleIo;
use Cake\Console\ConsoleOptionParser;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use RegexIterator;
use SplFileInfo;
use Symfony\Component\Process\Process;
/**
* Runs rector rulesets against the provided path.
*/
class RectorCommand extends BaseCommand
{
protected const CODE_CHANGES = 2;
/**
* Execute.
*
* @param \Cake\Console\Arguments $args The command arguments.
* @param \Cake\Console\ConsoleIo $io The console io
* @return int|null
*/
public function execute(Arguments $args, ConsoleIo $io): ?int
{
$path = (string)$args->getArgument('path');
if (!file_exists($path)) {
$io->error("The provided path `{$path}` does not exist.");
return static::CODE_ERROR;
}
$autoload = $args->getOption('autoload');
if (empty($autoload)) {
$autoload = $this->detectAutoload($io, $path);
}
if ($autoload === null) {
$io->error('No autoload file could be found. Use the `--autoload` flag to provide a path.');
return static::CODE_ERROR;
}
if (!file_exists($autoload)) {
$io->error("The autoload file `{$autoload}` does not exist. Use the `--autoload` flag to provide a path.");
return static::CODE_ERROR;
}
$result = $this->runRector($io, $args, $autoload);
if ($result === false) {
$io->error('Something went wrong while running rector. Ensure that `php` is on your PATH.');
return static::CODE_ERROR;
}
$success = '🎉 Upgrade complete! 🎉';
if ($args->getOption('dry-run')) {
$success .= ' [DRY-RUN]';
}
$io->success($success);
return static::CODE_SUCCESS;
}
/**
* Run rector as a sub-process.
*
* @param \Cake\Console\ConsoleIo $io The io object to output with
* @param \Cake\Console\Arguments $args The Arguments object
* @param string $autoload The autoload file path.
* @return bool
*/
protected function runRector(ConsoleIo $io, Arguments $args, string $autoload): bool
{
$io->info('Starting rector at ' . date('Y-m-d H:i:s'));
if ($args->getOption('per-file')) {
$result = $this->processPerFile($io, $args, $autoload);
} else {
$result = $this->processDirectory($io, $args, $autoload);
}
if (!$result) {
$io->error('Something went wrong while running rector.');
return false;
}
$io->info('Rector completed successfully at ' . date('Y-m-d H:i:s'));
return true;
}
/**
* Find the application autoload file by traversing up the file system
* looking for a `vendor/autoload.php` file.
*
* @param \Cake\Console\ConsoleIo $io The io object
* @param string $path The path to start scanning from
* @return string|null The path to a vendor/autoload.php or null
*/
protected function detectAutoload(ConsoleIo $io, string $path): ?string
{
$path = realpath($path);
$io->verbose("Detecting autoload file for {$path}");
$segments = explode(DIRECTORY_SEPARATOR, $path);
while (true) {
if (count($segments) === 0) {
break;
}
$check = implode(DIRECTORY_SEPARATOR, $segments) . '/vendor/autoload.php';
$io->verbose("-> Checking {$check}");
if (file_exists($check)) {
$io->verbose("-> Found {$check}");
return $check;
}
array_pop($segments);
}
return null;
}
protected function processDirectory(ConsoleIo $io, Arguments $args, string $autoload): bool
{
$config = ROOT . '/config/rector/' . basename((string)$args->getOption('rules')) . '.php';
$path = realpath((string)$args->getArgument('path'));
$command = $this->buildCommand($args, $autoload, $config, $path);
$io->verbose("Running <info>{$command}</info>");
$process = Process::fromShellCommandline($command);
$process->setEnv($_ENV);
$process->setTimeout(null);
$process->start();
foreach ($process as $type => $data) {
if ($type === Process::OUT) {
$io->out($data);
} elseif ($type === Process::ERR) {
$io->err($data);
}
}
return $process->getExitCode() !== static::CODE_ERROR;
}
protected function processPerFile(ConsoleIo $io, Arguments $args, string $autoload): bool
{
$config = ROOT . '/config/rector/' . basename((string)$args->getOption('rules')) . '.php';
$path = realpath((string)$args->getArgument('path'));
if (is_file($path)) {
$phpFiles = [
new SplFileInfo($path),
];
} else {
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
$phpFiles = new RegexIterator($files, '/\.php|\.ctp$/');
}
$result = true;
$totalFiles = $changedFiles = 0;
/** @var \SplFileInfo $file */
foreach ($phpFiles as $file) {
$io->out('Processing ' . $file->getPathname());
$command = $this->buildCommand($args, $autoload, $config, $file->getPathname());
$io->verbose("Running <info>{$command}</info>");
$process = Process::fromShellCommandline($command);
$process->setEnv($_ENV);
$process->setTimeout(null);
$process->start();
foreach ($process as $type => $data) {
if ($type === Process::OUT) {
$io->out($data);
} elseif ($type === Process::ERR) {
$io->err($data);
}
}
if ($process->getExitCode() === static::CODE_ERROR) {
$result = false;
} elseif ($process->getExitCode() === static::CODE_CHANGES) {
$changedFiles++;
}
$totalFiles++;
}
$io->out("{$changedFiles}/{$totalFiles} files changed.");
return $result;
}
/**
* Gets the option parser instance and configures it.
*
* @param \Cake\Console\ConsoleOptionParser $parser The parser to build
* @return \Cake\Console\ConsoleOptionParser
*/
protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser
{
$parser
->setDescription([
'Apply rector refactoring rules',
'',
'Run rector rules against `path`. By default the <info>cakephp50</info> ' .
'rules are run.',
'',
'You will want to run the <info>cakephp50</info> rules multiple times on ' .
'subdirectories of your application:',
'',
'<info>bin/cake upgrade rector ~/app/src</info>',
'<info>bin/cake upgrade rector ~/app/config</info>',
'<info>bin/cake upgrade rector ~/app/templates</info>',
'<info>bin/cake upgrade rector ~/app/tests</info>',
])
->addArgument('path', [
'help' => 'The path to the application or plugin.',
'required' => true,
])
->addOption('rules', [
'help' => 'The rector ruleset to run',
'default' => 'cakephp50',
])
->addOption('autoload', [
'help' => 'The path to the application/plugin autoload if one cannot be auto-detected, ' .
'or is detected incorrectly.',
])
->addOption('per-file', [
'help' => 'Run rector on a per-file basis instead of the whole directory.',
'boolean' => true,
])
->addOption('dry-run', [
'help' => 'Enable to get a preview of what modifications will be applied.',
'boolean' => true,
'short' => 'd',
])
->addOption('no-diff', [
'help' => 'Disable rector diff output which can cause issues with large files.',
'boolean' => true,
]);
return $parser;
}
/**
* @param \Cake\Console\Arguments $args
* @param string $autoload
* @param string $config
* @param string|bool $path
* @return string
*/
protected function buildCommand(Arguments $args, string $autoload, string $config, bool|string $path): string
{
$cmdPath = ROOT . '/vendor/bin/rector process';
return sprintf(
'%s %s %s %s --autoload-file=%s --config=%s %s --clear-cache',
$cmdPath,
$args->getOption('dry-run') ? '--dry-run' : '',
$args->getOption('verbose') ? '--debug' : '',
$args->getOption('no-diff') ? '--no-diffs' : '',
escapeshellarg($autoload),
escapeshellarg($config),
escapeshellarg($path),
);
}
}