This repository was archived by the owner on Apr 27, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 128
Expand file tree
/
Copy pathEnvironmentDeleteCommand.php
More file actions
349 lines (316 loc) · 16.6 KB
/
EnvironmentDeleteCommand.php
File metadata and controls
349 lines (316 loc) · 16.6 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
<?php
namespace Platformsh\Cli\Command\Environment;
use Platformsh\Cli\Command\CommandBase;
use Platformsh\Cli\Console\ArrayArgument;
use Platformsh\Cli\Util\Wildcard;
use Platformsh\Client\Model\Environment;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class EnvironmentDeleteCommand extends CommandBase
{
protected function configure()
{
$this
->setName('environment:delete')
->setAliases(['environment:deactivate'])
->setDescription('Deactivate or delete one or more environments')
->addArgument('environment', InputArgument::IS_ARRAY, "Select environment(s) by ID.\nThe % character may be used as a wildcard." . "\n" . ArrayArgument::SPLIT_HELP)
->addOption('delete-branch', null, InputOption::VALUE_NONE, 'Delete Git branch(es) (inactive environments)')
->addOption('no-delete-branch', null, InputOption::VALUE_NONE, 'Do not delete Git branch(es) (inactive environments)')
->addOption('type', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Select all environments of a type (adding to any others selected)' . "\n" . ArrayArgument::SPLIT_HELP)
->addOption('only-type', 't', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Include only environment(s) of a specific type' . "\n" . ArrayArgument::SPLIT_HELP)
->addOption('exclude', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, "Environment(s) to exclude.\nThe % character may be used as a wildcard.\n" . ArrayArgument::SPLIT_HELP)
->addOption('exclude-type', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Environment type(s) to exclude' . "\n" . ArrayArgument::SPLIT_HELP)
->addOption('inactive', null, InputOption::VALUE_NONE, 'Select all inactive environments (adding to any others selected')
->addOption('merged', null, InputOption::VALUE_NONE, 'Select all merged environments (adding to any others selected)');
$this->addProjectOption()
->addEnvironmentOption()
->addWaitOptions();
$this->addExample('Deactivate and delete the currently checked out environment');
$this->addExample('Deactivate and delete the environments "test" and "example-1"', 'test example-1');
$this->addExample('Delete all inactive environments', '--inactive');
$this->addExample('Deactivate and delete all environments merged with their parent', '--merged');
$this->setHelp(<<<EOF
Deactivating an environment will destroy all its data and services. Only the
code in the Git branch remains.
This command allows you to deactivate environment(s) and delete their Git branches.
EOF
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->validateInput($input, true);
$environments = $this->api()->getEnvironments($this->getSelectedProject());
/**
* A list of selected environments, keyed by ID to avoid duplication.
*
* @var array<string, Environment> $selectedEnvironments
*/
$selectedEnvironments = [];
$error = false;
$anythingSpecified = false;
// Add the environment(s) specified in the arguments or options.
$specifiedEnvironmentIds = ArrayArgument::getArgument($input, 'environment');
if ($input->getOption('environment')) {
$specifiedEnvironmentIds = array_merge([$input->getOption('environment')], $specifiedEnvironmentIds);
}
if ($specifiedEnvironmentIds) {
$anythingSpecified = true;
$allIds = \array_map(function (Environment $e) { return $e->id; }, $environments);
$specifiedEnvironmentIds = Wildcard::select($allIds, $specifiedEnvironmentIds);
$notFound = array_diff($specifiedEnvironmentIds, array_keys($environments));
if (!empty($notFound)) {
// Refresh the environments list if any environment is not found.
$environments = $this->api()->getEnvironments($this->getSelectedProject(), true);
$notFound = array_diff($specifiedEnvironmentIds, array_keys($environments));
}
foreach ($notFound as $notFoundId) {
$this->stdErr->writeln("Environment not found: <error>$notFoundId</error>");
$error = true;
}
$specifiedEnvironments = array_intersect_key($environments, array_flip($specifiedEnvironmentIds));
$this->stdErr->writeln(count($specifiedEnvironments) . ' environment(s) found by ID');
$this->stdErr->writeln('');
foreach ($specifiedEnvironments as $specifiedEnvironment) {
$selectedEnvironments[$specifiedEnvironment->id] = $specifiedEnvironment;
}
}
// Gather inactive environments.
if ($input->getOption('inactive')) {
$anythingSpecified = true;
if ($input->getOption('no-delete-branch')) {
$this->stdErr->writeln('The option --no-delete-branch cannot be combined with --inactive.');
return 1;
}
$inactive = array_filter(
$environments,
function ($environment) {
/** @var Environment $environment */
return $environment->status == 'inactive';
}
);
$this->stdErr->writeln(count($inactive) . ' inactive environment(s) found.');
$this->stdErr->writeln('');
foreach ($inactive as $inactiveEnv) {
$selectedEnvironments[$inactiveEnv->id] = $inactiveEnv;
}
}
// Gather merged environments.
if ($input->getOption('merged')) {
$anythingSpecified = true;
$merged = [];
foreach ($environments as $environment) {
$merge_info = $environment->getProperty('merge_info', false) ?: [];
if (isset($environment->parent, $merge_info['commits_ahead'], $merge_info['parent_ref']) && $merge_info['commits_ahead'] === 0) {
$selectedEnvironments[$environment->id] = $merged[$environment->id] = $environment;
}
}
$this->stdErr->writeln(count($merged) . ' merged environment(s) found.');
$this->stdErr->writeln('');
}
// Gather environments with the specified --type (can be multiple).
if ($types = ArrayArgument::getOption($input, 'type')) {
$anythingSpecified = true;
$withTypes = [];
foreach ($environments as $environment) {
if (\in_array($environment->type, $types)) {
$selectedEnvironments[$environment->id] = $withTypes[$environment->id] = $environment;
}
}
$this->stdErr->writeln(count($withTypes) . ' environment(s) found matching type(s): ' . implode(', ', $types));
$this->stdErr->writeln('');
}
// Add the current environment if nothing is otherwise specified.
if (!$anythingSpecified
&& empty($selectedEnvironments)
&& ($current = $this->getCurrentEnvironment($this->getSelectedProject()))) {
$this->stdErr->writeln('Nothing specified; selecting the current environment: '. $this->api()->getEnvironmentLabel($current));
$this->stdErr->writeln('');
$selectedEnvironments[$current->id] = $current;
}
// Exclude environment type(s) specified via --exclude-type or --only-type.
$excludeTypes = ArrayArgument::getOption($input, 'exclude-type');
$onlyTypes = ArrayArgument::getOption($input, 'only-type');
$filtered = \array_filter($selectedEnvironments, function (Environment $environment) use ($excludeTypes, $onlyTypes) {
if (\in_array($environment->type, $excludeTypes, true)) {
return false;
}
if (!empty($onlyTypes) && !\in_array($environment->type, $onlyTypes, true)) {
return false;
}
return true;
});
if (($numExcluded = count($selectedEnvironments) - count($filtered)) > 0) {
$this->stdErr->writeln($numExcluded . ' environment(s) excluded by type.');
$this->stdErr->writeln('');
}
$selectedEnvironments = $filtered;
// Exclude environment ID(s) specified in --exclude.
$excludeIds = ArrayArgument::getOption($input, 'exclude');
if (!empty($excludeIds)) {
$resolved = Wildcard::select(\array_keys($selectedEnvironments), $excludeIds);
if (count($resolved)) {
$selectedEnvironments = \array_diff_key($selectedEnvironments, \array_flip($resolved));
$this->stdErr->writeln(count($resolved) . ' environment(s) excluded by ID.');
$this->stdErr->writeln('');
}
}
if (count($selectedEnvironments)) {
$this->stdErr->writeln('Selected environment(s): ' . $this->listEnvironments($selectedEnvironments));
$this->stdErr->writeln('');
}
// Confirm which of the environments the user wishes to be deactivated
// or deleted.
$this->api()->sortResources($selectedEnvironments, 'id');
$toDeleteBranch = [];
$toDeactivate = [];
$needNewline = false;
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
foreach ($selectedEnvironments as $environment) {
$environmentId = $environment->id;
// Check that the environment does not have children.
// @todo remove this check when Platform's behavior is fixed
foreach ($environments as $potentialChild) {
if ($potentialChild->parent === $environment->id) {
$this->stdErr->writeln(\sprintf(
"The environment %s has children and therefore can't be deactivated or deleted.",
$this->api()->getEnvironmentLabel($environment, 'error')
));
$this->stdErr->writeln("Please delete the environment's children first.");
$error = $needNewline = true;
continue 2;
}
}
if (!\in_array($environment->status, ['active', 'inactive', 'dirty', 'deleting'])) {
$this->stdErr->writeln("The environment <error>$environmentId</error> has an unrecognised status <error>" . $environment->status . "</error>.");
$error = $needNewline = true;
continue;
}
if ($environment->status === 'inactive' && $input->getOption('no-delete-branch')) {
$this->stdErr->writeln("The environment <comment>$environmentId</comment> is inactive and <comment>--no-delete-branch</comment> was specified, so it will not be deleted.");
$needNewline = true;
continue;
}
if ($environment->status === 'deleting') {
$this->stdErr->writeln("The environment <comment>$environmentId</comment> is already being deactivated or deleted.");
$needNewline = true;
continue;
}
if ($environment->status === 'dirty') {
$this->stdErr->writeln("The environment <error>$environmentId</error> is currently building, and therefore can't be deactivated or deleted. Please wait.");
$error = $needNewline = true;
continue;
}
// Ask about deactivation if the environment is active.
if ($environment->isActive()) {
$needNewline = true;
$this->stdErr->writeln(\sprintf(
'The environment %s is currently active. Deactivating it will destroy all associated data and services.',
$this->api()->getEnvironmentLabel($environment, 'comment')
));
if ($questionHelper->confirm('Are you sure you want to deactivate this environment?')) {
$toDeactivate[$environmentId] = $environment;
} else {
$error = true;
}
}
// Ask about deleting the branch, which requires either an inactive
// environment, or waiting for it to be deactivated.
if (!$input->getOption('no-delete-branch')
&& ($environment->status === 'inactive' || (isset($toDeactivate[$environmentId]) && $this->shouldWait($input)))) {
$message = isset($toDeactivate[$environmentId])
? "Delete the inactive environment (Git branch) too?"
: "Are you sure you want to delete the inactive environment (Git branch) <comment>$environmentId</comment>?";
if ($input->getOption('delete-branch') || ($input->isInteractive() && $questionHelper->confirm($message))) {
$toDeleteBranch[$environmentId] = $environment;
} elseif (!isset($toDeactivate[$environmentId])) {
$error = true;
}
$needNewline = true;
}
}
if ($needNewline) {
$this->stdErr->writeln('');
}
if (empty($toDeleteBranch) && empty($toDeactivate)) {
$this->stdErr->writeln('No environments to deactivate or delete.');
if (!$anythingSpecified) {
$this->stdErr->writeln(\sprintf('For help, run: <info>%s help environment:delete</info>', $this->config()->get('application.executable')));
}
return $error ? 1 : 0;
}
$success = $this->deleteMultiple($toDeactivate, $toDeleteBranch, $input) && !$error;
return $success ? 0 : 1;
}
/**
* @param Environment[] $environments
*
* @return string
*/
private function listEnvironments(array $environments)
{
$uniqueIds = \array_unique(\array_map(function(Environment $e) { return $e->id; }, $environments));
natcasesort($uniqueIds);
return '<info>' . implode('</info>, <info>', $uniqueIds) . '</info>';
}
/**
* @param array $toDeactivate
* @param array $toDeleteBranch
* @param InputInterface $input
*
* @return bool
*/
protected function deleteMultiple(array $toDeactivate, array $toDeleteBranch, InputInterface $input)
{
$error = false;
$deactivateActivities = [];
$deactivated = 0;
/** @var Environment $environment */
foreach ($toDeactivate as $environmentId => $environment) {
try {
$this->stdErr->writeln("Deactivating environment <info>$environmentId</info>");
$deactivateActivities[] = $environment->deactivate();
$deactivated++;
} catch (\Exception $e) {
$this->stdErr->writeln($e->getMessage());
}
}
if ($this->shouldWait($input)) {
/** @var \Platformsh\Cli\Service\ActivityMonitor $activityMonitor */
$activityMonitor = $this->getService('activity_monitor');
if (!$activityMonitor->waitMultiple($deactivateActivities, $this->getSelectedProject())) {
$error = true;
}
}
$deleted = 0;
foreach ($toDeleteBranch as $environmentId => $environment) {
try {
if ($environment->status !== 'inactive') {
$environment->refresh();
if ($environment->status !== 'inactive') {
$this->stdErr->writeln("Cannot delete Git branch <error>$environmentId</error>: the environment is not (yet) inactive.");
continue;
}
}
$environment->delete();
$this->stdErr->writeln("Deleted Git branch (inactive environment) <info>$environmentId</info>");
$deleted++;
} catch (\Exception $e) {
$this->stdErr->writeln($e->getMessage());
}
}
if ($deleted > 0) {
$this->stdErr->writeln("Run <info>git fetch --prune</info> to remove deleted branches from your local cache.");
}
if ($deleted < count($toDeleteBranch) || $deactivated < count($toDeactivate)) {
$error = true;
}
if (($deleted || $deactivated || $error) && isset($environment)) {
$this->api()->clearEnvironmentsCache($environment->project);
}
return !$error;
}
}