-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathBinCommand.php
More file actions
361 lines (296 loc) · 9.71 KB
/
BinCommand.php
File metadata and controls
361 lines (296 loc) · 9.71 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
<?php
declare(strict_types=1);
namespace Bamarni\Composer\Bin\Command;
use Bamarni\Composer\Bin\Config\Config;
use Bamarni\Composer\Bin\Config\ConfigFactory;
use Bamarni\Composer\Bin\ApplicationFactory\FreshInstanceApplicationFactory;
use Bamarni\Composer\Bin\Input\BinInputFactory;
use Bamarni\Composer\Bin\CommandForwardingContext;
use Bamarni\Composer\Bin\Logger;
use Bamarni\Composer\Bin\ApplicationFactory\NamespaceApplicationFactory;
use Composer\Command\BaseCommand;
use Composer\Factory;
use Composer\IO\IOInterface;
use Composer\IO\NullIO;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Throwable;
use function chdir;
use function count;
use function file_exists;
use function file_put_contents;
use function getcwd;
use function glob;
use function method_exists;
use function min;
use function mkdir;
use function putenv;
use function sprintf;
use const GLOB_ONLYDIR;
/**
* @final Will be final in 2.x.
*/
class BinCommand extends BaseCommand
{
private const ALL_NAMESPACES = 'all';
private const ROOT_NAMESPACE = 'root';
private const NAMESPACE_ARG = 'namespace';
/**
* @var NamespaceApplicationFactory
*/
private $applicationFactory;
/**
* @var Logger
*/
private $logger;
public function __construct(
?NamespaceApplicationFactory $applicationFactory = null,
?Logger $logger = null
) {
parent::__construct('bin');
$this->applicationFactory = $applicationFactory ?? new FreshInstanceApplicationFactory();
$this->logger = $logger ?? new Logger(new NullIO());
}
protected function configure(): void
{
$this
->setDescription('Run a command inside a bin namespace')
->addArgument(
self::NAMESPACE_ARG,
InputArgument::REQUIRED
)
->ignoreValidationErrors();
}
public function setIO(IOInterface $io): void
{
parent::setIO($io);
$this->logger = new Logger($io);
}
public function getIO(): IOInterface
{
$io = parent::getIO();
$this->logger = new Logger($io);
return $io;
}
public function isProxyCommand(): bool
{
return true;
}
public function execute(InputInterface $input, OutputInterface $output): int
{
// Switch to requireComposer() once Composer 2.3 is set as the minimum
// @phpstan-ignore function.alreadyNarrowedType
$composer = method_exists($this, 'requireComposer')
? $this->requireComposer()
: $this->getComposer();
$config = Config::fromComposer($composer);
$currentWorkingDir = getcwd();
$this->logger->logDebug(
sprintf(
'Current working directory: <comment>%s</comment>',
$currentWorkingDir
)
);
// Ensures Composer is reset – we are setting some environment variables
// & co. so a fresh Composer instance is required.
$this->resetComposers();
$this->configureBinLinksDir($config);
$vendorRoot = $config->getTargetDirectory();
$namespace = $input->getArgument(self::NAMESPACE_ARG);
$binInput = BinInputFactory::createInput(
$namespace,
$input
);
if (self::ROOT_NAMESPACE === $namespace) {
return $this->executeInNamespace(
$currentWorkingDir,
$currentWorkingDir,
$binInput,
$output,
true
);
}
return (self::ALL_NAMESPACES !== $namespace)
? $this->executeInNamespace(
$currentWorkingDir,
$vendorRoot.'/'.$namespace,
$binInput,
$output
) : $this->executeAllNamespaces(
$currentWorkingDir,
$vendorRoot,
$binInput,
$output
);
}
/**
* @return list<string>
*/
private static function getBinNamespaces(string $binVendorRoot): array
{
return glob($binVendorRoot.'/*', GLOB_ONLYDIR);
}
private function executeAllNamespaces(
string $originalWorkingDir,
string $binVendorRoot,
InputInterface $input,
OutputInterface $output
): int {
$namespaces = self::getBinNamespaces($binVendorRoot);
if (count($namespaces) === 0) {
$this->logger->logStandard('<warning>Could not find any bin namespace.</warning>');
// Is a valid scenario: the user may not have set up any bin
// namespace yet
return 0;
}
$exitCode = 0;
foreach ($namespaces as $namespace) {
$exitCode += $this->executeInNamespace(
$originalWorkingDir,
$namespace,
$input,
$output
);
}
return min($exitCode, 255);
}
private function executeInNamespace(
string $originalWorkingDir,
string $namespace,
InputInterface $input,
OutputInterface $output,
bool $disableCommandForwarding = false
): int {
$this->logger->logStandard(
sprintf(
'Checking namespace <comment>%s</comment>',
$namespace
)
);
try {
self::createNamespaceDirIfDoesNotExist($namespace);
} catch (CouldNotCreateNamespaceDir $exception) {
$this->logger->logStandard(
sprintf(
'<warning>%s</warning>',
$exception->getMessage()
)
);
return 1;
}
// Use a new application: this avoids a variety of issues:
// - A command may be added in a namespace which may cause side effects
// when executed in another namespace afterwards (since it is the same
// process).
// - Different plugins may be registered in the namespace in which case
// an already executed application will not pick that up.
$namespaceApplication = $this->applicationFactory->create(
$this->getApplication()
);
$previousCommandForwardingDisabled = CommandForwardingContext::isCommandForwardingDisabled();
if ($disableCommandForwarding) {
CommandForwardingContext::setCommandForwardingDisabled(true);
}
// It is important to clean up the state either for follow-up plugins
// or for example the execution in the next namespace.
$cleanUp = function () use (
$originalWorkingDir,
$disableCommandForwarding,
$previousCommandForwardingDisabled
): void {
if ($disableCommandForwarding) {
CommandForwardingContext::setCommandForwardingDisabled(
$previousCommandForwardingDisabled
);
}
$this->chdir($originalWorkingDir);
$this->resetComposers();
};
$this->chdir($namespace);
$this->ensureComposerFileExists();
$namespaceInput = BinInputFactory::createNamespaceInput($input);
$this->logger->logDebug(
sprintf(
'Running <info>`@composer %s`</info>.',
$namespaceInput->__toString()
)
);
try {
$exitCode = $namespaceApplication->doRun($namespaceInput, $output);
} catch (Throwable $executionFailed) {
// Ensure we do the cleanup even in case of failure
$cleanUp();
throw $executionFailed;
}
$cleanUp();
return $exitCode;
}
/**
* @throws CouldNotCreateNamespaceDir
*/
private static function createNamespaceDirIfDoesNotExist(string $namespace): void
{
if (file_exists($namespace)) {
return;
}
$mkdirResult = mkdir($namespace, 0777, true);
if (!$mkdirResult && !is_dir($namespace)) {
throw CouldNotCreateNamespaceDir::forNamespace($namespace);
}
}
private function configureBinLinksDir(Config $config): void
{
if (!$config->binLinksAreEnabled()) {
return;
}
$binDir = ConfigFactory::createConfig()->get('bin-dir');
putenv(
sprintf(
'COMPOSER_BIN_DIR=%s',
$binDir
)
);
$this->logger->logDebug(
sprintf(
'Configuring bin directory to <comment>%s</comment>.',
$binDir
)
);
}
private function ensureComposerFileExists(): void
{
// Some plugins require access to the Composer file e.g. Symfony Flex
$namespaceComposerFile = Factory::getComposerFile();
if (file_exists($namespaceComposerFile)) {
return;
}
file_put_contents($namespaceComposerFile, '{}');
$this->logger->logDebug(
sprintf(
'Created the file <comment>%s</comment>.',
$namespaceComposerFile
)
);
}
private function resetComposers(): void
{
$this->getApplication()->resetComposer();
foreach ($this->getApplication()->all() as $command) {
if ($command instanceof BaseCommand) {
$command->resetComposer();
}
}
}
private function chdir(string $dir): void
{
chdir($dir);
$this->logger->logDebug(
sprintf(
'Changed current directory to <comment>%s</comment>.',
$dir
)
);
}
}