-
Notifications
You must be signed in to change notification settings - Fork 122
Expand file tree
/
Copy pathStatusCommand.php
More file actions
445 lines (395 loc) · 15.4 KB
/
Copy pathStatusCommand.php
File metadata and controls
445 lines (395 loc) · 15.4 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
<?php
declare(strict_types=1);
/**
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* 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
* @license https://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Migrations\Command;
use Cake\Command\Command;
use Cake\Console\Arguments;
use Cake\Console\ConsoleIo;
use Cake\Console\ConsoleOptionParser;
use Cake\Core\Plugin;
use Migrations\Config\ConfigInterface;
use Migrations\Db\Adapter\UnifiedMigrationsTableStorage;
use Migrations\Migration\Manager;
use Migrations\Migration\ManagerFactory;
/**
* Status command for built in backend
*/
class StatusCommand extends Command
{
/**
* Exit code for when status command is run and there are missing migrations
*
* @var int
*/
public const CODE_STATUS_MISSING = 2;
/**
* Exit code for when status command is run and there are no missing migrations,
* but does have down migrations
*
* @var int
*/
public const CODE_STATUS_DOWN = 3;
/**
* @inheritDoc
*/
public static function getDescription(): string
{
return 'Display the state of migrations.';
}
/**
* The default name added to the application command list
*
* @return string
*/
public static function defaultName(): string
{
return 'migrations status';
}
/**
* Configure the option parser
*
* @param \Cake\Console\ConsoleOptionParser $parser The option parser to configure
* @return \Cake\Console\ConsoleOptionParser
*/
protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser
{
$parser->setDescription([
'The <info>status</info> command prints a list of all migrations, along with their current status',
'',
'<info>migrations status -c secondary</info>',
'<info>migrations status -c secondary -f json</info>',
'<info>migrations status --all</info>',
'Print a summary for the app and every loaded plugin that has migrations.',
'Add <info>-v</info> to also print the per-section migration tables.',
'<info>migrations status --cleanup</info>',
'Remove *MISSING* migrations from the migration tracking table',
'<info>migrations status --validate</info>',
'Load every migration class and fail if any of them cannot be loaded.',
])->addOption('plugin', [
'short' => 'p',
'help' => 'The plugin to run migrations for',
])->addOption('all', [
'help' => 'Print a status summary for the app and every loaded plugin that has migrations. '
. 'Use -v to also print the per-section migration tables. '
. 'Cannot be combined with --plugin or --cleanup.',
'boolean' => true,
'default' => false,
])->addOption('connection', [
'short' => 'c',
'help' => 'The datasource connection to use',
'default' => 'default',
])->addOption('source', [
'short' => 's',
'help' => 'The folder under src/Config that migrations are in',
'default' => ConfigInterface::DEFAULT_MIGRATION_FOLDER,
])->addOption('format', [
'short' => 'f',
'help' => 'The output format: text or json. Defaults to text.',
'choices' => ['text', 'json'],
'default' => 'text',
])->addOption('cleanup', [
'help' => 'Remove MISSING migrations from the migration tracking table',
'boolean' => true,
'default' => false,
])->addOption('validate', [
'help' => 'Load every migration class and fail if any of them cannot be loaded. '
. 'Migration classes are otherwise only loaded when they are executed.',
'boolean' => true,
'default' => false,
]);
return $parser;
}
/**
* Execute the command.
*
* @param \Cake\Console\Arguments $args The command arguments.
* @param \Cake\Console\ConsoleIo $io The console io
* @return int|null The exit code or null for success
*/
public function execute(Arguments $args, ConsoleIo $io): ?int
{
/** @var string|null $format */
$format = $args->getOption('format');
$clean = $args->getOption('cleanup');
$all = (bool)$args->getOption('all');
if ($all) {
if ($args->getOption('plugin')) {
$io->err('<error>The --all option cannot be combined with --plugin.</error>');
return Command::CODE_ERROR;
}
if ($clean) {
$io->err('<error>The --all option cannot be combined with --cleanup.</error>');
return Command::CODE_ERROR;
}
return $this->executeAll($args, $io, $format);
}
$factory = new ManagerFactory([
'plugin' => $args->getOption('plugin'),
'source' => $args->getOption('source'),
'connection' => $args->getOption('connection'),
'dry-run' => $args->getOption('dry-run'),
]);
$manager = $factory->createManager($io);
if ($args->getOption('validate')) {
/** @var string|null $plugin */
$plugin = $args->getOption('plugin');
if (!$this->validateMigrations($manager, $io, $plugin ?? 'app')) {
return Command::CODE_ERROR;
}
if ($format !== 'json') {
$io->out(sprintf(
'<success>All %d migrations can be loaded.</success>',
count($manager->getMigrationVersions()),
));
}
}
if ($clean) {
$removed = $manager->cleanupMissingMigrations();
if ($removed === 0) {
$io->out('<info>No missing migrations to clean up.</info>');
} else {
$io->out(sprintf('<info>Removed %d missing migration(s) from migration log.</info>', $removed));
}
return Command::CODE_SUCCESS;
}
$migrations = $manager->printStatus($format);
$tableName = $manager->getSchemaTableName();
switch ($format) {
case 'json':
$flags = 0;
if ($args->getOption('verbose')) {
$flags = JSON_PRETTY_PRINT;
}
$migrationString = (string)json_encode($migrations, $flags);
$io->out($migrationString);
break;
default:
$this->display($migrations, $io, $tableName);
break;
}
return Command::CODE_SUCCESS;
}
/**
* Execute the status command for the app and every loaded plugin
* that ships migrations.
*
* @param \Cake\Console\Arguments $args The command arguments.
* @param \Cake\Console\ConsoleIo $io The console io.
* @param string|null $format Output format.
* @return int The exit code: CODE_STATUS_MISSING (2) when there are missing entries,
* CODE_STATUS_DOWN (3) when there are pending down migrations, CODE_SUCCESS otherwise.
*/
protected function executeAll(Arguments $args, ConsoleIo $io, ?string $format): int
{
$sections = ['app' => null];
foreach (Plugin::loaded() as $pluginName) {
$migrationsPath = Plugin::path($pluginName) . 'config' . DS
. $args->getOption('source') . DS;
if (!is_dir($migrationsPath)) {
continue;
}
$sections[$pluginName] = $pluginName;
}
$verbose = (bool)$args->getOption('verbose');
$validate = (bool)$args->getOption('validate');
$validationFailed = false;
$jsonResults = [];
$summary = [];
$exitCode = Command::CODE_SUCCESS;
foreach ($sections as $label => $plugin) {
$factory = new ManagerFactory([
'plugin' => $plugin,
'source' => $args->getOption('source'),
'connection' => $args->getOption('connection'),
'dry-run' => $args->getOption('dry-run'),
]);
$manager = $factory->createManager($io);
if ($validate && !$this->validateMigrations($manager, $io, $label)) {
$validationFailed = true;
}
$migrations = $manager->printStatus($format);
$sectionExit = $this->statusExitCode($migrations);
// Precedence: MISSING > DOWN > SUCCESS — once we see MISSING anywhere, keep it.
if ($sectionExit === self::CODE_STATUS_MISSING) {
$exitCode = self::CODE_STATUS_MISSING;
} elseif ($sectionExit === self::CODE_STATUS_DOWN && $exitCode === Command::CODE_SUCCESS) {
$exitCode = self::CODE_STATUS_DOWN;
}
$summary[$label] = $this->countActions($migrations);
if ($format === 'json') {
$jsonResults[$label] = $migrations;
continue;
}
if (!$verbose) {
continue;
}
$heading = $label === 'app' ? 'APP' : $label;
$io->out('');
$io->out('==================================================');
$io->out(sprintf('<info>%s</info>', $heading));
$io->out('==================================================');
$this->display($migrations, $io, $manager->getSchemaTableName());
}
if ($validationFailed) {
return Command::CODE_ERROR;
}
if ($format === 'json') {
$flags = 0;
if ($verbose) {
$flags = JSON_PRETTY_PRINT;
}
$io->out((string)json_encode($jsonResults, $flags));
return $exitCode;
}
$this->displaySummary($io, $summary);
return $exitCode;
}
/**
* Load every migration class and print the ones that could not be loaded.
*
* @param \Migrations\Migration\Manager $manager The manager to load migrations with.
* @param \Cake\Console\ConsoleIo $io The console io.
* @param string $label The section the migrations belong to.
* @return bool True when every migration class could be loaded.
*/
protected function validateMigrations(Manager $manager, ConsoleIo $io, string $label): bool
{
$errors = $manager->validateMigrations();
if (!$errors) {
return true;
}
$io->err(sprintf(
'<error>%s: %d migration(s) could not be loaded:</error>',
$label === 'app' ? 'APP' : $label,
count($errors),
));
foreach ($errors as $version => $message) {
$io->err(sprintf(' - %d: %s', $version, $message));
}
return false;
}
/**
* Count actionable items (down + missing) in a section's migrations array.
*
* @param array $migrations The result of {@see Manager::printStatus()}.
* @return array{down: int, missing: int}
*/
protected function countActions(array $migrations): array
{
$down = 0;
$missing = 0;
foreach ($migrations as $migration) {
if (!empty($migration['missing'])) {
$missing++;
continue;
}
if (($migration['status'] ?? null) === 'down') {
$down++;
}
}
return ['down' => $down, 'missing' => $missing];
}
/**
* Render the trailing summary block listing sections that need action.
*
* @param \Cake\Console\ConsoleIo $io The console io.
* @param array<string, array{down: int, missing: int}> $summary
* @return void
*/
protected function displaySummary(ConsoleIo $io, array $summary): void
{
$needsAction = array_filter(
$summary,
fn(array $counts): bool => $counts['down'] > 0 || $counts['missing'] > 0,
);
$io->out('');
if (!$needsAction) {
$io->out(sprintf(
'<success>Summary: all %d sections are up to date.</success>',
count($summary),
));
return;
}
$io->out(sprintf(
'<warning>Summary: %d of %d sections require action:</warning>',
count($needsAction),
count($summary),
));
foreach ($needsAction as $label => $counts) {
$heading = $label === 'app' ? 'APP' : $label;
$parts = [];
if ($counts['down'] > 0) {
$parts[] = sprintf('%d pending', $counts['down']);
}
if ($counts['missing'] > 0) {
$parts[] = sprintf('%d missing', $counts['missing']);
}
$io->out(sprintf(' - %s: %s', $heading, implode(', ', $parts)));
}
}
/**
* Compute the appropriate status exit code for a single section's migrations array.
*
* @param array $migrations The result of {@see Manager::printStatus()}.
* @return int CODE_STATUS_MISSING when missing entries exist, CODE_STATUS_DOWN when
* any migration is pending (down), otherwise CODE_SUCCESS.
*/
protected function statusExitCode(array $migrations): int
{
$hasDown = false;
foreach ($migrations as $migration) {
if (!empty($migration['missing'])) {
return self::CODE_STATUS_MISSING;
}
if (($migration['status'] ?? null) === 'down') {
$hasDown = true;
}
}
return $hasDown ? self::CODE_STATUS_DOWN : Command::CODE_SUCCESS;
}
/**
* Print migration status to stdout.
*
* @param \Cake\Console\ConsoleIo $io The console io
* @param string $tableName The migration tracking table name
* @return void
*/
protected function display(array $migrations, ConsoleIo $io, string $tableName): void
{
$io->out(sprintf('using migration table <info>%s</info>', $tableName));
if ($tableName !== UnifiedMigrationsTableStorage::TABLE_NAME) {
$io->warning('You are using legacy phinxlog tables. Run `migrations upgrade` to switch to the unified `cake_migrations` table.');
}
$io->out('');
if ($migrations) {
$rows = [];
$rows[] = ['Status', 'Migration ID', 'Migration Name'];
foreach ($migrations as $migration) {
$status = $migration['status'] === 'up' ? '<info>up</info>' : '<error>down</error>';
$name = $migration['name'] ?
'<comment>' . $migration['name'] . '</comment>' :
'<error>** MISSING **</error>';
$missingComment = '';
if (!empty($migration['missing'])) {
$missingComment = '<error>** MISSING **</error>';
}
$rows[] = [$status, sprintf('%14.0f ', $migration['id']), $name . $missingComment];
}
$io->helper('table')->output($rows);
} else {
$msg = 'There are no available migrations. Try creating one using the <info>create</info> command.';
$io->err('');
$io->err($msg);
$io->err('');
}
}
}