-
-
Notifications
You must be signed in to change notification settings - Fork 100
/
Compile.php
748 lines (612 loc) · 22.3 KB
/
Compile.php
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
<?php
declare(strict_types=1);
/*
* This file is part of the box project.
*
* (c) Kevin Herrera <kevin@herrera.io>
* Théo Fidry <theo.fidry@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace KevinGH\Box\Console\Command;
use Amp\MultiReasonException;
use Assert\Assertion;
use DateTimeImmutable;
use DateTimeZone;
use KevinGH\Box\Box;
use KevinGH\Box\Compactor;
use KevinGH\Box\Configuration;
use KevinGH\Box\Console\Logger\BuildLogger;
use KevinGH\Box\MapFile;
use KevinGH\Box\PhpSettingsHandler;
use KevinGH\Box\RequirementChecker\RequirementsDumper;
use KevinGH\Box\StubGenerator;
use RuntimeException;
use stdClass;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Logger\ConsoleLogger;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\VarDumper\Cloner\VarCloner;
use Symfony\Component\VarDumper\Dumper\CliDumper;
use const DATE_ATOM;
use function array_shift;
use function count;
use function explode;
use function function_exists;
use function get_class;
use function implode;
use function ini_get;
use function KevinGH\Box\disable_parallel_processing;
use function KevinGH\Box\FileSystem\chmod;
use function KevinGH\Box\FileSystem\dump_file;
use function KevinGH\Box\FileSystem\make_path_relative;
use function KevinGH\Box\FileSystem\remove;
use function KevinGH\Box\FileSystem\rename;
use function KevinGH\Box\formatted_filesize;
use function KevinGH\Box\get_phar_compression_algorithms;
use function putenv;
use function strlen;
use function strtolower;
use function substr;
use function trim;
/**
* @final
* @private
* TODO: make final when Build is removed
*/
class Compile extends Configurable
{
use ChangeableWorkingDirectory;
private const HELP = <<<'HELP'
The <info>%command.name%</info> command will compile code in a new PHAR based on a variety of settings.
<comment>
This command relies on a configuration file for loading
PHAR packaging settings. If a configuration file is not
specified through the <info>--config|-c</info> option, one of
the following files will be used (in order): <info>box.json</info>,
<info>box.json.dist</info>
</comment>
The configuration file is actually a JSON object saved to a file. For more
information check the documentation online:
<comment>
https://github.com/humbug/box
</comment>
HELP;
private const DEBUG_OPTION = 'debug';
private const NO_PARALLEL_PROCESSING_OPTION = 'no-parallel';
private const NO_RESTART_OPTION = 'no-restart';
private const DEV_OPTION = 'dev';
private const NO_CONFIG_OPTION = 'no-config';
private const DEBUG_DIR = '.box_dump';
/**
* {@inheritdoc}
*/
protected function configure(): void
{
parent::configure();
$this->setName('compile');
$this->setDescription('Compile an application into a PHAR');
$this->setHelp(self::HELP);
$this->addOption(
self::DEBUG_OPTION,
null,
InputOption::VALUE_NONE,
'Dump the files added to the PHAR in a `'.self::DEBUG_DIR.'` directory'
);
$this->addOption(
self::NO_PARALLEL_PROCESSING_OPTION,
null,
InputOption::VALUE_NONE,
'Disable the parallel processing'
);
$this->addOption(
self::NO_RESTART_OPTION,
null,
InputOption::VALUE_NONE,
'Do not restart the PHP process. Box restarts the process by default to disable xdebug and set `phar.readonly=0`'
);
$this->addOption(
self::DEV_OPTION,
null,
InputOption::VALUE_NONE,
'Skips the compression step'
);
$this->addOption(
self::NO_CONFIG_OPTION,
null,
InputOption::VALUE_NONE,
'Ignore the config file even when one is specified with the --config option'
);
$this->configureWorkingDirOption();
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output): void
{
$io = new SymfonyStyle($input, $output);
if ($input->getOption(self::NO_RESTART_OPTION)) {
putenv('BOX_ALLOW_XDEBUG=1');
}
if ($debug = $input->getOption(self::DEBUG_OPTION)) {
$output->setVerbosity(OutputInterface::VERBOSITY_DEBUG);
}
self::checkPhpSettings($io, $output);
if ($input->getOption(self::NO_PARALLEL_PROCESSING_OPTION)) {
disable_parallel_processing();
$io->writeln('<info>[debug] Disabled parallel processing</info>', OutputInterface::VERBOSITY_DEBUG);
}
$this->changeWorkingDirectory($input);
$io->writeln($this->getApplication()->getHelp());
$io->writeln('');
$config = $input->getOption(self::NO_CONFIG_OPTION)
? Configuration::create(null, new stdClass())
: $this->getConfig($input, $output, true)
;
$path = $config->getOutputPath();
$logger = new BuildLogger($io);
$startTime = microtime(true);
$this->removeExistingArtefacts($config, $logger, $debug);
$logger->logStartBuilding($path);
$this->createPhar($config, $input, $output, $logger, $io, $debug);
$this->correctPermissions($path, $config, $logger);
$logger->log(
BuildLogger::STAR_PREFIX,
'Done.'
);
$io->comment(
sprintf(
"<info>PHAR size: %s\nMemory usage: %.2fMB (peak: %.2fMB), time: %.2fs<info>",
formatted_filesize($path),
round(memory_get_usage() / 1024 / 1024, 2),
round(memory_get_peak_usage() / 1024 / 1024, 2),
round(microtime(true) - $startTime, 2)
)
);
}
/**
* Taken from Composer.
*
* @see https://github.com/composer/composer/blob/34c371f5f23e25eb9aa54ccc65136cf50930612e/bin/composer#L20-L50
*/
private static function checkPhpSettings(SymfonyStyle $io, OutputInterface $output): void
{
if (function_exists('ini_set')) {
$memoryInBytes = function (string $value): string {
$unit = strtolower($value[strlen($value) - 1]);
$value = (int) $value;
switch ($unit) {
case 'g':
$value *= 1024;
// no break (cumulative multiplier)
case 'm':
$value *= 1024;
// no break (cumulative multiplier)
case 'k':
$value *= 1024;
}
return $value;
};
$memoryLimit = trim(ini_get('memory_limit'));
// Increase memory_limit if it is lower than 500MB
if ($memoryLimit !== '-1' && $memoryInBytes($memoryLimit) < 1024 * 1024 * 512 && false === getenv('BOX_MEMORY_LIMIT')) {
@ini_set('memory_limit', '512M');
$io->writeln(
sprintf(
'<info>[debug] Bumped the memory limit from "%s" to "%s".</info>',
$memoryLimit,
'512M'
),
OutputInterface::VERBOSITY_DEBUG
);
}
// Set user defined memory limit
if ($newMemoryLimit = getenv('BOX_MEMORY_LIMIT')) {
@ini_set('memory_limit', $newMemoryLimit);
$io->writeln(
sprintf(
'<info>[debug] Bumped the memory limit from "%s" to BOX_MEMORY_LIMIT="%s".</info>',
$memoryLimit,
$newMemoryLimit
),
OutputInterface::VERBOSITY_DEBUG
);
}
}
(new PhpSettingsHandler(new ConsoleLogger($output)))->check();
}
private function createPhar(
Configuration $config,
InputInterface $input,
OutputInterface $output,
BuildLogger $logger,
SymfonyStyle $io,
bool $debug
): void {
$box = Box::create(
$config->getTmpOutputPath()
);
$box->getPhar()->startBuffering();
$this->setReplacementValues($config, $box, $logger);
$this->registerCompactors($config, $box, $logger);
$this->registerFileMapping($config, $box, $logger);
// Registering the main script _before_ adding the rest if of the files is _very_ important. The temporary
// file used for debugging purposes and the Composer dump autoloading will not work correctly otherwise.
$main = $this->registerMainScript($config, $box, $logger);
$check = $this->registerRequirementsChecker($config, $box, $logger);
$this->addFiles($config, $box, $logger, $io);
$this->registerStub($config, $box, $main, $check, $logger);
$this->configureMetadata($config, $box, $logger);
$this->configureCompressionAlgorithm($config, $box, $input->getOption(self::DEV_OPTION), $logger);
$box->getPhar()->stopBuffering();
if ($debug) {
$box->getPhar()->extractTo(self::DEBUG_DIR, null, true);
}
$this->signPhar($config, $box, $config->getTmpOutputPath(), $input, $output, $logger);
if ($config->getTmpOutputPath() !== $config->getOutputPath()) {
rename($config->getTmpOutputPath(), $config->getOutputPath());
}
}
private function removeExistingArtefacts(Configuration $config, BuildLogger $logger, bool $debug): void
{
$path = $config->getOutputPath();
if ($debug) {
remove(self::DEBUG_DIR);
$date = (new DateTimeImmutable('now', new DateTimeZone('UTC')))->format(DATE_ATOM);
$file = null !== $config->getFile() ? $config->getFile() : 'No config file';
remove(self::DEBUG_DIR);
dump_file(
self::DEBUG_DIR.'/.box_configuration',
<<<EOF
//
// Processed content of the configuration file "$file" dumped for debugging purposes
// Time: $date
//
EOF
.(new CliDumper())->dump(
(new VarCloner())->cloneVar($config),
true
)
);
}
if (false === file_exists($path)) {
return;
}
$logger->log(
BuildLogger::QUESTION_MARK_PREFIX,
sprintf(
'Removing the existing PHAR "%s"',
$path
)
);
remove($path);
}
private function setReplacementValues(Configuration $config, Box $box, BuildLogger $logger): void
{
$values = $config->getProcessedReplacements();
if ([] === $values) {
return;
}
$logger->log(
BuildLogger::QUESTION_MARK_PREFIX,
'Setting replacement values'
);
foreach ($values as $key => $value) {
$logger->log(
BuildLogger::PLUS_PREFIX,
sprintf(
'%s: %s',
$key,
$value
)
);
}
$box->registerPlaceholders($values);
}
private function registerCompactors(Configuration $config, Box $box, BuildLogger $logger): void
{
$compactors = $config->getCompactors();
if ([] === $compactors) {
$logger->log(
BuildLogger::QUESTION_MARK_PREFIX,
'No compactor to register'
);
return;
}
$logger->log(
BuildLogger::QUESTION_MARK_PREFIX,
'Registering compactors'
);
$logCompactors = function (Compactor $compactor) use ($logger): void {
$compactorClassParts = explode('\\', get_class($compactor));
if ('_HumbugBox' === substr($compactorClassParts[0], 0, strlen('_HumbugBox'))) {
array_shift($compactorClassParts);
}
$logger->log(
BuildLogger::PLUS_PREFIX,
implode('\\', $compactorClassParts)
);
};
array_map($logCompactors, $compactors);
$box->registerCompactors($compactors);
}
private function registerFileMapping(Configuration $config, Box $box, BuildLogger $logger): void
{
$fileMapper = $config->getFileMapper();
$this->logMap($fileMapper, $logger);
$box->registerFileMapping(
$config->getBasePath(),
$fileMapper
);
}
private function addFiles(Configuration $config, Box $box, BuildLogger $logger, SymfonyStyle $io): void
{
$logger->log(BuildLogger::QUESTION_MARK_PREFIX, 'Adding binary files');
$count = count($config->getBinaryFiles());
$box->addFiles($config->getBinaryFiles(), true);
$logger->log(
BuildLogger::CHEVRON_PREFIX,
0 === $count
? 'No file found'
: sprintf('%d file(s)', $count)
);
$logger->log(BuildLogger::QUESTION_MARK_PREFIX, 'Adding files');
$count = count($config->getFiles());
try {
$box->addFiles($config->getFiles(), false, null !== $config->getComposerJson());
} catch (MultiReasonException $exception) {
// This exception is handled a different way to give me meaningful feedback to the user
foreach ($exception->getReasons() as $reason) {
$io->error($reason);
}
throw $exception;
}
$logger->log(
BuildLogger::CHEVRON_PREFIX,
0 === $count
? 'No file found'
: sprintf('%d file(s)', $count)
);
}
private function registerMainScript(Configuration $config, Box $box, BuildLogger $logger): ?string
{
$main = $config->getMainScriptPath();
$logger->log(
BuildLogger::QUESTION_MARK_PREFIX,
sprintf(
'Adding main file: %s',
$main
)
);
$localMain = $box->addFile(
$main,
$config->getMainScriptContents()
);
$relativeMain = make_path_relative($main, $config->getBasePath());
if ($localMain !== $relativeMain) {
$logger->log(
BuildLogger::CHEVRON_PREFIX,
$localMain
);
}
return $localMain;
}
private function registerRequirementsChecker(Configuration $config, Box $box, BuildLogger $logger): bool
{
if (false === $config->checkRequirements()) {
return false;
}
$logger->log(
BuildLogger::QUESTION_MARK_PREFIX,
'Adding requirements checker'
);
$checkFiles = RequirementsDumper::dump($config->getComposerLockDecodedContents(), null !== $config->getCompressionAlgorithm());
foreach ($checkFiles as $fileWithContents) {
[$file, $contents] = $fileWithContents;
$box->addFile('.box/'.$file, $contents, true);
}
return true;
}
private function registerStub(Configuration $config, Box $box, string $main, bool $checkRequirements, BuildLogger $logger): void
{
if ($config->isStubGenerated()) {
$logger->log(
BuildLogger::QUESTION_MARK_PREFIX,
'Generating new stub'
);
$stub = $this->createStub($config, $main, $checkRequirements, $logger);
$box->getPhar()->setStub($stub->generate());
} elseif (null !== ($stub = $config->getStubPath())) {
$logger->log(
BuildLogger::QUESTION_MARK_PREFIX,
sprintf(
'Using stub file: %s',
$stub
)
);
$box->registerStub($stub);
} else {
// TODO: add warning that the check requirements could not be added
$aliasWasAdded = $box->getPhar()->setAlias($config->getAlias());
Assertion::true(
$aliasWasAdded,
sprintf(
'The alias "%s" is invalid. See Phar::setAlias() documentation for more information.',
$config->getAlias()
)
);
$box->getPhar()->setDefaultStub($main);
$logger->log(
BuildLogger::QUESTION_MARK_PREFIX,
'Using default stub'
);
}
}
private function configureMetadata(Configuration $config, Box $box, BuildLogger $logger): void
{
if (null !== ($metadata = $config->getMetadata())) {
$logger->log(
BuildLogger::QUESTION_MARK_PREFIX,
'Setting metadata'
);
$logger->log(
BuildLogger::MINUS_PREFIX,
is_string($metadata) ? $metadata : var_export($metadata, true)
);
$box->getPhar()->setMetadata($metadata);
}
}
private function configureCompressionAlgorithm(Configuration $config, Box $box, bool $dev, BuildLogger $logger): void
{
if (null !== ($algorithm = $config->getCompressionAlgorithm())) {
$logger->log(
BuildLogger::QUESTION_MARK_PREFIX,
sprintf(
'Compressing with the algorithm "<comment>%s</comment>"',
array_search($algorithm, get_phar_compression_algorithms(), true)
)
);
$box->getPhar()->compressFiles($algorithm);
} else {
$logger->log(
BuildLogger::QUESTION_MARK_PREFIX,
$dev
? 'No compression'
: '<error>No compression</error>'
);
}
}
private function signPhar(
Configuration $config,
Box $box,
string $path,
InputInterface $input,
OutputInterface $output,
BuildLogger $logger
): void {
// sign using private key, if applicable
//TODO: check that out
remove($path.'.pubkey');
$key = $config->getPrivateKeyPath();
if (null === $key) {
if (null !== ($algorithm = $config->getSigningAlgorithm())) {
$box->getPhar()->setSignatureAlgorithm($algorithm);
}
return;
}
$logger->log(
BuildLogger::QUESTION_MARK_PREFIX,
'Signing using a private key'
);
$passphrase = $config->getPrivateKeyPassphrase();
if ($config->isPrivateKeyPrompt()) {
if (false === $input->isInteractive()) {
throw new RuntimeException(
sprintf(
'Accessing to the private key "%s" requires a passphrase but none provided. Either '
.'provide one or run this command in interactive mode.',
$key
)
);
}
/** @var $dialog QuestionHelper */
$dialog = $this->getHelper('question');
$question = new Question('Private key passphrase:');
$question->setHidden(false);
$question->setHiddenFallback(false);
$passphrase = $dialog->ask($input, $output, $question);
$output->writeln('');
}
$box->signUsingFile($key, $passphrase);
}
private function correctPermissions(string $path, Configuration $config, BuildLogger $logger): void
{
if (null !== ($chmod = $config->getFileMode())) {
$logger->log(
BuildLogger::QUESTION_MARK_PREFIX,
"Setting file permissions to <comment>$chmod</comment>"
);
chmod($path, $chmod);
}
}
private function createStub(Configuration $config, ?string $main, bool $checkRequirements, BuildLogger $logger): StubGenerator
{
$stub = StubGenerator::create()
->alias($config->getAlias())
->index($main)
->intercept($config->isInterceptFileFuncs())
->checkRequirements($checkRequirements)
;
if (null !== ($shebang = $config->getShebang())) {
$logger->log(
BuildLogger::MINUS_PREFIX,
sprintf(
'Using shebang line: %s',
$shebang
)
);
$stub->shebang($shebang);
} else {
$logger->log(
BuildLogger::MINUS_PREFIX,
'No shebang line'
);
}
if (null !== ($bannerPath = $config->getStubBannerPath())) {
$logger->log(
BuildLogger::MINUS_PREFIX,
sprintf(
'Using custom banner from file: %s',
$bannerPath
)
);
$stub->banner($config->getStubBannerContents());
} elseif (null !== ($banner = $config->getStubBannerContents())) {
$logger->log(
BuildLogger::MINUS_PREFIX,
'Using banner:'
);
$bannerLines = explode("\n", $banner);
foreach ($bannerLines as $bannerLine) {
$logger->log(
BuildLogger::CHEVRON_PREFIX,
$bannerLine
);
}
$stub->banner($banner);
}
return $stub;
}
private function logMap(MapFile $fileMapper, BuildLogger $logger): void
{
$map = $fileMapper->getMap();
if ([] === $map) {
return;
}
$logger->log(
BuildLogger::QUESTION_MARK_PREFIX,
'Mapping paths'
);
foreach ($map as $item) {
foreach ($item as $match => $replace) {
if ('' === $match) {
$match = '(all)';
$replace .= '/';
}
$logger->log(
BuildLogger::MINUS_PREFIX,
sprintf(
'%s <info>></info> %s',
$match,
$replace
)
);
}
}
}
}