-
Notifications
You must be signed in to change notification settings - Fork 16
/
CompileCommand.php
264 lines (220 loc) 路 9.87 KB
/
CompileCommand.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
<?php
namespace Castor\Console\Command;
use Castor\PathHelper;
use Castor\PlatformHelper;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Path;
use Symfony\Component\Process\Process;
use Symfony\Contracts\HttpClient\HttpClientInterface;
/**
* @internal
*/
class CompileCommand extends Command
{
// When something **important** related to the compilation changed, increase
// this version to invalide the cache
private const CACHE_VERSION = '1';
public function __construct(
private readonly HttpClientInterface $httpClient,
private readonly Filesystem $fs
) {
parent::__construct();
}
protected function configure(): void
{
$this
->setName('castor:compile')
->setAliases(['compile'])
->addArgument('phar-path', InputArgument::REQUIRED, 'Path to phar to compile along PHP')
->addOption('binary-path', null, InputOption::VALUE_REQUIRED, 'Path to compiled static binary. It can be the parent dirname too', PathHelper::getRoot())
->addOption('os', null, InputOption::VALUE_REQUIRED, 'Target OS for PHP compilation', 'linux', ['linux', 'macos'])
->addOption('arch', null, InputOption::VALUE_REQUIRED, 'Target architecture for PHP compilation', 'x86_64', ['x86_64', 'aarch64'])
->addOption('php-version', null, InputOption::VALUE_REQUIRED, 'PHP version in major.minor format', '8.3')
->addOption('php-extensions', null, InputOption::VALUE_REQUIRED, 'PHP extensions required, in a comma-separated format. Defaults are the minimum required to run a basic "Hello World" task in Castor.', 'mbstring,phar,posix,tokenizer,curl')
->addOption('php-rebuild', null, InputOption::VALUE_NONE, 'Ignore cache and force PHP build compilation.')
->setHidden(true)
;
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$this->validateInput($input);
$io = new SymfonyStyle($input, $output);
$io->section('Compiling PHP and your Castor app phar into a static binary');
$phpBuildCacheKey = $this->generatePHPBuildCacheKey($input);
$spcBinaryPath = PlatformHelper::getCacheDirectory() . '/castor-php-static-compiler/' . $phpBuildCacheKey . '/spc';
$spcBinaryDir = \dirname($spcBinaryPath);
$this->setupSPC(
$spcBinaryDir,
$spcBinaryPath,
$io,
$input->getOption('os'),
$input->getOption('arch'),
);
if (!$this->fs->exists($spcBinaryDir . '/buildroot/bin/micro.sfx') || $input->getOption('php-rebuild')) {
$this->installPHPBuildTools($spcBinaryPath, $spcBinaryDir, $io);
$phpExtensions = $input->getOption('php-extensions');
$this->downloadPHPSourceDeps(
$spcBinaryPath,
$phpExtensions,
$input->getOption('php-version'),
$spcBinaryDir,
$io
);
$this->buildPHP(
$spcBinaryPath,
$phpExtensions,
$input->getOption('arch'),
$spcBinaryDir,
$io
);
}
$binaryPath = $this->getBinaryPath($input);
$this->mergePHPandPHARIntoSingleExecutable(
$spcBinaryPath,
$input->getArgument('phar-path'),
$binaryPath,
$spcBinaryDir,
$io
);
$io->success(sprintf('Your Castor app has been compiled into a static binary in "%s"', $binaryPath));
return Command::SUCCESS;
}
private function validateInput(InputInterface $input): void
{
$os = $input->getOption('os');
if (!\in_array($os, ['linux', 'macos'])) {
throw new \InvalidArgumentException('Currently supported target OS are one of "linux" or "macos"');
}
$arch = $input->getOption('arch');
if (!\in_array($arch, ['x86_64', 'aarch64'])) {
throw new \InvalidArgumentException('Target architecture must be one of "x86_64" or "aarch64"');
}
if (!is_file($input->getArgument('phar-path'))) {
throw new \InvalidArgumentException(sprintf('The phar file "%s" does not exist.', $input->getArgument('phar-path')));
}
$input->setArgument('phar-path', Path::makeAbsolute($input->getArgument('phar-path'), getcwd() ?: PathHelper::getRoot()));
}
private function downloadSPC(string $spcSourceUrl, string $spcBinaryDestination, SymfonyStyle $io): void
{
$response = $this->httpClient->request('GET', $spcSourceUrl);
$contentLength = $response->getHeaders()['content-length'][0] ?? 0;
$outputStream = fopen($spcBinaryDestination, 'w');
$progressBar = $io->createProgressBar((int) $contentLength);
if (false === $outputStream) {
throw new \RuntimeException(sprintf('Failed to open file "%s" for writing.', $spcBinaryDestination));
}
foreach ($this->httpClient->stream($response) as $chunk) {
fwrite($outputStream, $chunk->getContent());
$progressBar->advance(\strlen($chunk->getContent()));
}
fclose($outputStream);
chmod($spcBinaryDestination, 0o755);
$progressBar->finish();
}
private function installPHPBuildTools(string $spcBinaryPath, string $spcBinaryDir, SymfonyStyle $io): void
{
$installSPCDepsProcess = new Process(
command: [$spcBinaryPath, 'doctor', '--auto-fix'],
cwd: $spcBinaryDir,
timeout: null,
);
$io->text('Running command: ' . $installSPCDepsProcess->getCommandLine());
$installSPCDepsProcess->mustRun(fn ($type, $buffer) => print $buffer);
}
private function downloadPHPSourceDeps(string $spcBinaryPath, mixed $phpExtensions, mixed $phpVersion, string $spcBinaryDir, SymfonyStyle $io): void
{
$downloadProcess = new Process(
command: [
$spcBinaryPath, 'download',
'--for-extensions=' . $phpExtensions,
'--with-php=' . $phpVersion,
],
cwd: $spcBinaryDir,
timeout: null,
);
$io->text('Running command: ' . $downloadProcess->getCommandLine());
$downloadProcess->mustRun(fn ($type, $buffer) => print $buffer);
}
private function buildPHP(string $spcBinaryPath, mixed $phpExtensions, mixed $arch, string $spcBinaryDir, SymfonyStyle $io): void
{
$buildProcess = new Process(
command: [
$spcBinaryPath, 'build', $phpExtensions,
'--build-micro',
'--with-micro-fake-cli',
'--arch=' . $arch,
],
cwd: $spcBinaryDir,
timeout: null,
);
$io->text('Running command: ' . $buildProcess->getCommandLine());
$buildProcess->mustRun(fn ($type, $buffer) => print $buffer);
}
private function mergePHPandPHARIntoSingleExecutable(string $spcBinaryPath, string $pharFilePath, string $appBinaryFilePath, string $spcBinaryDir, SymfonyStyle $io): void
{
if (!$this->fs->isAbsolutePath($pharFilePath)) {
$pharFilePath = PathHelper::getRoot() . '/' . $pharFilePath;
}
$mergePHPandPHARProcess = new Process(
[
$spcBinaryPath,
'micro:combine', $pharFilePath,
'--output=' . $appBinaryFilePath,
],
cwd: $spcBinaryDir,
timeout: null,
);
$io->text('Running command: ' . $mergePHPandPHARProcess->getCommandLine());
$mergePHPandPHARProcess->mustRun(fn ($type, $buffer) => print $buffer);
}
private function setupSPC(string $spcBinaryDir, string $spcBinaryPath, SymfonyStyle $io, mixed $os, mixed $arch): void
{
$this->fs->mkdir($spcBinaryDir, 0o755);
if ($this->fs->exists($spcBinaryPath)) {
$io->text(sprintf('Using the static-php-cli (spc) tool from "%s"', $spcBinaryPath));
} else {
$spcSourceUrl = sprintf('https://dl.static-php.dev/static-php-cli/spc-bin/nightly/spc-%s-%s', $os, $arch);
$io->text(sprintf('Downloading the static-php-cli (spc) tool from "%s" to "%s"', $spcSourceUrl, $spcBinaryPath));
$this->downloadSPC($spcSourceUrl, $spcBinaryPath, $io);
$io->newLine(2);
}
}
private function getBinaryPath(InputInterface $input): string
{
$binaryPath = $input->getOption('binary-path');
if (!Path::isAbsolute($binaryPath)) {
$binaryPath = Path::makeAbsolute($binaryPath, getcwd() ?: PathHelper::getRoot());
}
if (!is_dir($binaryPath)) {
return $binaryPath;
}
$p = new Process([\PHP_BINARY, $input->getArgument('phar-path'), 'list', '--format', 'json']);
$p->mustRun();
$appName = json_decode($p->getOutput(), true)['application']['name'];
return sprintf(
'%s/%s.%s.%s',
$binaryPath,
$appName,
$input->getOption('os'),
$input->getOption('arch'),
);
}
private function generatePHPBuildCacheKey(InputInterface $input): string
{
$c = hash_init('sha256');
foreach (['os', 'arch', 'php-version'] as $phpBuildOption) {
hash_update($c, $input->getOption($phpBuildOption));
}
$phpExtensions = explode(',', $input->getOption('php-extensions'));
sort($phpExtensions);
hash_update($c, implode(',', $phpExtensions));
hash_update($c, self::CACHE_VERSION);
return hash_final($c);
}
}