-
Notifications
You must be signed in to change notification settings - Fork 2
/
composer
executable file
·554 lines (467 loc) · 17.8 KB
/
composer
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
#!/usr/bin/env php
<?php
/**
* This is a wrapper around composer that installs or updates it
* and delegates call to it as if composer itself was called.
*
* If it breaks, check out newer version or report an issue at
* https://github.com/kamazee/composer-wrapper
*
* @version 1.3.0
*/
if (!class_exists('ComposerWrapper')) {
class ComposerWrapperParams {
/**
* @var string|null
*/
private $channel;
/**
* @var string
*/
private $updateFreq = '7 days';
/**
* @var string
*/
private $composerDir = __DIR__;
private $composerJson;
public function __construct()
{
$composerJsonFromEnv = \getenv('COMPOSER');
if (\is_string($composerJsonFromEnv) && $composerJsonFromEnv !== '') {
$this->composerJson = $composerJsonFromEnv;
return;
}
$this->composerJson = \getcwd() . DIRECTORY_SEPARATOR . 'composer.json';
}
public function loadReal()
{
$this->loadComposerJson();
// env variables have the highest priority
$this->loadEnv();
}
private function loadEnv()
{
if ( false !== $value = \getenv('COMPOSER_UPDATE_FREQ')) {
$this->setUpdateFreq($value);
}
if ( false !== $value = \getenv('COMPOSER_CHANNEL')) {
$this->setChannel($value);
}
if ( false !== $value = \getenv('COMPOSER_DIR')) {
$this->setComposerDir($value);
}
}
private function loadComposerJson()
{
$file = $this->composerJson;
// It is the same logic of reading composer.json as is in the Composer
if (!is_file($file)
|| !is_readable($file)
|| !is_array($composer = json_decode(file_get_contents($file), true))) {
return;
}
if (empty($composer['extra']['wrapper'])) {
return;
}
$wrapper = $composer['extra']['wrapper'];
if (array_key_exists('update-freq', $wrapper)) {
$this->setUpdateFreq($wrapper['update-freq']);
}
if (array_key_exists('channel', $wrapper)) {
$this->setChannel($wrapper['channel']);
}
if (array_key_exists('composer-dir', $wrapper)) {
$this->setComposerDir($wrapper['composer-dir']);
}
}
/**
* @return string|null
*/
public function getChannel()
{
return $this->channel;
}
/**
* @param false|string $channel
*/
public function setChannel($channel)
{
$this->channel = (string) $channel;
}
/**
* @return string
*/
public function getUpdateFreq()
{
return $this->updateFreq;
}
/**
* @param string $updateFreq
*/
public function setUpdateFreq($updateFreq)
{
$now = new DateTime('now', new DateTimeZone('UTC'));
$modified = clone $now;
//hack: DateTime $modifier argument validation. Taken from https://stackoverflow.com/a/34899724/2165434
$success = @$modified->modify($updateFreq);
if ($success === false) {
throw new \Exception(sprintf('Wrong update frequency is requested: %s; should be valid DateTime modifier (follow %s for the help)', $updateFreq,'https://www.php.net/manual/en/datetime.modify.php'));
}
//endhack
if ($modified < $now) {
throw new \Exception(sprintf('Wrong update frequency is requested: %s; composer update frequency must not be negative', $updateFreq));
}
$this->updateFreq = (string) $updateFreq;
}
/**
* @return string
*/
public function getComposerDir()
{
return $this->composerDir;
}
/**
* @param string $composerDir
*/
public function setComposerDir($composerDir)
{
if (!is_dir($composerDir) || !is_writable($composerDir)) {
throw new \Exception(sprintf(
"Wrong composer dir is requested: %s; argument is not a dir or is not writable dir",
$composerDir));
}
$this->composerDir = (string) $composerDir;
}
}
class ComposerWrapper
{
const COMPOSER_HASHBANG = "#!/usr/bin/env php\n";
const EXPECTED_INSTALLER_CHECKSUM_URL = 'https://composer.github.io/installer.sig';
const INSTALLER_URL = 'https://getcomposer.org/installer';
const INSTALLER_FILE = 'composer-setup.php';
const EXIT_CODE_SUCCESS = 0;
const EXIT_CODE_ERROR_DOWNLOADING_CHECKSUM = 1;
const MSG_ERROR_DOWNLOADING_CHECKSUM = 'Error when downloading composer installer checksum';
const EXIT_CODE_ERROR_DOWNLOADING_INSTALLER = 2;
const MSG_ERROR_DOWNLOADING_INSTALLER = 'Error when downloading composer installer';
const EXIT_CODE_ERROR_INSTALLER_CHECKSUM_MISMATCH = 3;
const MSG_ERROR_INSTALLER_CHECKSUM_MISMATCH = 'Failed to install composer: checksum of composer installer does not match expected checksum';
const EXIT_CODE_ERROR_WHEN_INSTALLING = 4;
const MSG_ERROR_WHEN_INSTALLING = 'Error when running composer installer';
const EXIT_CODE_ERROR_MAKING_EXECUTABLE = 5;
const MSG_SELF_UPDATE_FAILED = 'composer self-update failed; proceeding with existing';
const EXIT_CODE_COMPOSER_EXCEPTION = 6;
/**
* @var ComposerWrapperParams
*/
protected $params;
public function __construct(ComposerWrapperParams $params = null)
{
if (null === $params ) {
$this->params = new ComposerWrapperParams();
$this->params->loadReal();
} else {
$this->params = $params;
}
}
protected function file_get_contents()
{
return \call_user_func_array('file_get_contents', func_get_args());
}
protected function copy()
{
return \call_user_func_array('copy', \func_get_args());
}
protected function passthru($command, &$exitCode)
{
\passthru($command, $exitCode);
}
protected function unlink()
{
return \call_user_func_array('unlink', \func_get_args());
}
protected function touch()
{
return \call_user_func_array('touch', \func_get_args());
}
/**
* @param array $arrayCommand
* @param string $channel
* @return bool
*/
protected function supportsChannelFlag($arrayCommand, $channel)
{
$command = implode(' ', $arrayCommand);
try {
$php = \escapeshellarg($this->getPhpBinary());
$output = $this->getCliCallOutput($php . ' ' . $command);
} catch (Exception $e) {
throw new \Exception(
'Error when trying to check support for forcing ' .
'specific channel on either self-update or installer',
0,
$e
);
}
foreach ($output as $line) {
$line = trim($line);
if (0 === strpos($line, "--$channel ")) {
return true;
}
}
return false;
}
protected function getCliCallOutput($command)
{
$output = array();
\exec($command, $output, $exitCode);
if (0 !== $exitCode) {
throw new \Exception(
"Can't get current composer version" .
"Exit code: $exitCode, output: " . \implode(\PHP_EOL, $output)
);
}
return $output;
}
public function getPhpBinary()
{
if (defined('PHP_BINARY')) {
return \PHP_BINARY;
}
return \PHP_BINDIR . '/php';
}
public function installComposer($dir)
{
$installerPathName = $dir . DIRECTORY_SEPARATOR . static::INSTALLER_FILE;
if (!$this->copy(static::INSTALLER_URL, $installerPathName)) {
throw new Exception(
self::MSG_ERROR_DOWNLOADING_INSTALLER,
self::EXIT_CODE_ERROR_DOWNLOADING_INSTALLER
);
}
$this->verifyChecksum($installerPathName);
$requestedChannel = $this->params->getChannel();
$channelFlag = null;
if (null !== $requestedChannel) {
$installerHelpCommand = array(
\escapeshellarg($installerPathName),
'--no-ansi',
'--help',
);
if ($this->supportsChannelFlag($installerHelpCommand, $requestedChannel)) {
$channelFlag = '--' . $requestedChannel;
} else {
$this->showError(
"Installer doesn't allow to specify channel or channel is wrong.\n" .
"Requested channel $requestedChannel flag is ignored.\n" .
"The installer's default is going to be installed.\n" .
"Please remove channel requirement from wrapper's environment variables or extra.wrapper section of composer.json file (as installer doesn't seem to support channel flags anymore), or report an issue at https://github.com/kamazee/composer-wrapper/issues is you think it does and the support is not detected properly"
);
}
}
$commandParts = array(
\escapeshellarg($this->getPhpBinary()),
\escapeshellarg($installerPathName),
'--install-dir=' . \escapeshellarg($dir),
);
if (null !== $channelFlag) {
$commandParts[] = $channelFlag;
}
$this->passthru(
implode(' ', $commandParts),
$exitCode
);
$this->unlink($installerPathName);
if (self::EXIT_CODE_SUCCESS !== $exitCode) {
throw new Exception(
self::MSG_ERROR_WHEN_INSTALLING,
self::EXIT_CODE_ERROR_WHEN_INSTALLING
);
}
unset($exitCode);
}
protected function verifyChecksum($installerPathName)
{
$expectedInstallerHash = $this->file_get_contents(static::EXPECTED_INSTALLER_CHECKSUM_URL);
if (empty($expectedInstallerHash)) {
throw new Exception(
self::MSG_ERROR_DOWNLOADING_CHECKSUM,
self::EXIT_CODE_ERROR_DOWNLOADING_CHECKSUM
);
}
$expectedInstallerHash = trim($expectedInstallerHash);
$actualInstallerHash = \hash_file('sha384', $installerPathName);
if ($expectedInstallerHash !== $actualInstallerHash) {
$this->unlink($installerPathName);
throw new Exception(
self::MSG_ERROR_INSTALLER_CHECKSUM_MISMATCH,
self::EXIT_CODE_ERROR_INSTALLER_CHECKSUM_MISMATCH
);
}
}
protected function ensureInstalled($filename)
{
if (\file_exists($filename)) {
return;
}
$this->installComposer(dirname($filename));
}
protected function ensureExecutable($filename)
{
if (!\file_exists($filename)) {
throw new Exception("Can't make $filename executable: it doesn't exist");
}
if (\is_executable($filename)) {
return;
}
$currentMode = \fileperms($filename);
$executablePermissions = $currentMode | 0111;
if (false === \chmod($filename, $executablePermissions)) {
throw new Exception(
"Can't make $filename executable",
self::EXIT_CODE_ERROR_MAKING_EXECUTABLE
);
}
}
protected function isUpToDate($filename)
{
$composerUpdateFrequency = $this->params->getUpdateFreq();
$now = new \DateTime('now', new DateTimeZone('UTC'));
$mtimeTimestamp = \filemtime($filename);
$mtimePlusFrequency = \DateTime::createFromFormat(
'U',
$mtimeTimestamp,
new \DateTimeZone('UTC')
)
->modify($composerUpdateFrequency);
return $mtimePlusFrequency > $now;
}
protected function selfUpdate($filename)
{
$arguments = array_merge(array('self-update'), $this->getSelfUpdateFlags($filename));
$exitCode = $this->runByRealComposerSubprocess($filename, $arguments);
// composer exits both when self-update downloaded a new version
// and when no new version was available (and everything went OK)
if (self::EXIT_CODE_SUCCESS === $exitCode) {
$this->touch($filename);
} else {
// if self-update failed, next call should try it again, hence no touch()
$this->showError(self::MSG_SELF_UPDATE_FAILED);
}
}
public function runByRealComposerSubprocess($filename, array $arguments)
{
$command = \escapeshellarg($filename);
if (count($arguments) > 0) {
$command .= ' ' . implode(' ', array_map('escapeshellarg', $arguments));
}
$this->passthru(
$command,
$exitCode
);
return $exitCode;
}
private function getSelfUpdateFlags($filename)
{
$channelRequested = $this->params->getChannel();
$flags = array();
if (null === $channelRequested) {
return $flags;
}
$selfUpdateHelpCommand = array(
\escapeshellarg($filename),
'--no-ansi',
'help',
'self-update',
);
if ($this->supportsChannelFlag($selfUpdateHelpCommand, $channelRequested)) {
$flags[] = "--$channelRequested";
} elseif (1 == $channelRequested) {
// 1.10.5 supports channel flags, so should be a good intermediate version
$flags[] = '1.10.5';
} else {
$this->showError(
"Forcing channel $channelRequested is requested but current composer version doesn't support --$channelRequested flag, so nothing will be forced."
);
}
return $flags;
}
protected function ensureUpToDate($filename)
{
if (!\file_exists($filename)) {
throw new \Exception("Can't run composer self-update for $filename: it doesn't exist");
}
if ($this->isUpToDate($filename)) {
return;
}
$this->selfUpdate($filename);
}
protected function delegate($filename)
{
\ob_start(
function ($buffer) {
if (0 === \strpos($buffer, ComposerWrapper::COMPOSER_HASHBANG)) {
return \substr($buffer, \strlen(ComposerWrapper::COMPOSER_HASHBANG));
}
return false;
}
);
try {
require $filename;
} catch (Exception $e) {
\ob_end_flush();
throw new Exception(
"Composer exception was thrown: {$e->getMessage()}",
self::EXIT_CODE_COMPOSER_EXCEPTION,
$e
);
}
\ob_end_flush();
}
public function showError($text)
{
\fwrite(STDERR, $text . "\n");
}
protected function isSelfUpdate($cliArguments)
{
foreach ($cliArguments as $cliArgument) {
if ('-' === \substr($cliArgument, 0, 1)) {
continue;
}
// If the first argument that is not a CLI option (i.e. not starts with dash, '-'),
// and it's self-update, it should be run in a subprocess rather than delegated
// because otherwise wrapper will be replaced
if ('self-update' === $cliArgument || 'selfupdate' === $cliArgument) {
return true;
}
}
return false;
}
/**
* @throws Exception
*/
public function run($cliArguments)
{
$composerPathName = "{$this->params->getComposerDir()}/composer.phar";
$this->ensureInstalled($composerPathName);
$this->ensureExecutable($composerPathName);
if ($this->isSelfUpdate($cliArguments)) {
return $this->runByRealComposerSubprocess($composerPathName, $cliArguments);
}
$this->ensureUpToDate($composerPathName);
$this->delegate($composerPathName);
}
}
}
if ('cli' === \PHP_SAPI && @\realpath($_SERVER['argv'][0]) === __FILE__) {
$runner = new ComposerWrapper();
try {
$exitCode = $runner->run(\array_slice($_SERVER['argv'], 1));
if (null !== $exitCode) {
exit($exitCode);
}
} catch (Exception $e) {
$runner->showError('ERROR: ' . $e->getMessage());
exit($e->getCode());
}
}