-
-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathBuildCommand.php
271 lines (214 loc) · 7.25 KB
/
BuildCommand.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
<?php
declare(strict_types=1);
/**
* This file is part of Laravel Zero.
*
* (c) Nuno Maduro <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace LaravelZero\Framework\Commands;
use Illuminate\Console\Application as Artisan;
use Illuminate\Support\Facades\File;
use RuntimeException;
use Symfony\Component\Console\Command\SignalableCommandInterface;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Process\Process;
use Throwable;
use function Laravel\Prompts\text;
final class BuildCommand extends Command implements SignalableCommandInterface
{
/**
* {@inheritdoc}
*/
protected $signature = 'app:build
{name? : The build name}
{--build-version= : The build version, if not provided it will be asked}
{--timeout=300 : The timeout in seconds or 0 to disable}';
/**
* {@inheritdoc}
*/
protected $description = 'Build a single file executable';
/**
* Holds the configuration on is original state.
*/
private static ?string $config = null;
/**
* Holds the box.json on is original state.
*/
private static ?string $box = null;
/**
* Holds the command original output.
*/
private OutputInterface $originalOutput;
public function handle()
{
$this->title('Building process');
$this->build($this->input->getArgument('name') ?? $this->getBinary());
}
/**
* {@inheritdoc}
*/
public function run(InputInterface $input, OutputInterface $output): int
{
return parent::run($input, $this->originalOutput = $output);
}
/** @return array<int, int> */
public function getSubscribedSignals(): array
{
if (defined('SIGINT')) {
return [\SIGINT];
}
return [];
}
/** {@inheritdoc} */
public function handleSignal(int $signal, int|false $previousExitCode = 0): int
{
if (defined('SIGINT') && $signal === \SIGINT) {
if (self::$config !== null) {
$this->clear();
}
}
return self::SUCCESS;
}
/**
* Builds the application into a single file.
*/
private function build(string $name): void
{
/*
* We prepare the application for a build, moving it to production. Then,
* after compile all the code to a single file, we move the built file
* to the builds folder with the correct permissions.
*/
$exception = null;
try {
$this->prepare()->compile($name);
} catch (Throwable $exception) {
//
}
$this->clear();
if ($exception !== null) {
throw $exception;
}
$this->output->writeln(
sprintf(' Compiled successfully: <fg=green>%s</>', $this->app->buildsPath($name))
);
}
private function compile(string $name): BuildCommand
{
if (! File::exists($this->app->buildsPath())) {
File::makeDirectory($this->app->buildsPath());
}
$boxBinary = windows_os() ? '.\box.bat' : './box';
$process = new Process(
array_merge([$boxBinary, 'compile', '--working-dir='.base_path(), '--config='.base_path('box.json')], $this->getExtraBoxOptions()),
dirname(__DIR__, 2).'/bin',
null,
null,
$this->getTimeout()
);
/** @phpstan-ignore-next-line This is an instance of `ConsoleOutputInterface` */
$section = tap($this->originalOutput->section())->write('');
$progressBar = new ProgressBar(
$this->output->getVerbosity() > OutputInterface::VERBOSITY_NORMAL ? new NullOutput : $section, 25
);
$progressBar->setProgressCharacter("\xF0\x9F\x8D\xBA");
$process->start();
foreach ($process as $type => $data) {
$progressBar->advance();
if ($this->output->getVerbosity() > OutputInterface::VERBOSITY_NORMAL) {
$process::OUT === $type ? $this->info("$data") : $this->error("$data");
}
}
$progressBar->finish();
$section->clear();
$this->task(' 2. <fg=yellow>Compile</> into a single file');
$this->output->newLine();
$pharPath = $this->app->basePath($this->getBinary()).'.phar';
if (! File::exists($pharPath)) {
throw new RuntimeException('Failed to compile the application.');
}
File::move($pharPath, $this->app->buildsPath($name));
return $this;
}
private function prepare(): BuildCommand
{
$configFile = $this->app->configPath('app.php');
self::$config = File::get($configFile);
$config = include $configFile;
$config['env'] = 'production';
$version = $this->option('build-version') ?: text('Build version?', default: $config['version']);
$config['version'] = $version;
$boxFile = $this->app->basePath('box.json');
self::$box = File::get($boxFile);
$this->task(
' 1. Moving application to <fg=yellow>production mode</>',
function () use ($configFile, $config) {
File::put($configFile, '<?php return '.var_export($config, true).';'.PHP_EOL);
}
);
$boxContents = json_decode(self::$box, true);
$boxContents['main'] = $this->getBinary();
File::put($boxFile, json_encode($boxContents));
File::put($configFile, '<?php return '.var_export($config, true).';'.PHP_EOL);
return $this;
}
private function clear(): void
{
if (self::$config !== null) {
File::put($this->app->configPath('app.php'), self::$config);
self::$config = null;
}
if (self::$box !== null) {
File::put($this->app->basePath('box.json'), self::$box);
self::$box = null;
}
}
/**
* Returns the artisan binary.
*/
private function getBinary(): string
{
return str_replace(["'", '"'], '', Artisan::artisanBinary());
}
/**
* Returns a valid timeout value. Non-positive values are converted to null,
* meaning no timeout.
*
*
* @throws \InvalidArgumentException
*/
private function getTimeout(): ?float
{
if (! is_numeric($this->option('timeout'))) {
throw new \InvalidArgumentException('The timeout value must be a number.');
}
$timeout = (float) $this->option('timeout');
return $timeout > 0 ? $timeout : null;
}
private function getExtraBoxOptions(): array
{
$extraBoxOptions = [];
if ($this->output->isDebug()) {
$extraBoxOptions[] = '--debug';
}
return $extraBoxOptions;
}
/**
* Makes sure that the `clear` is performed even
* if the command fails.
*
* @return void
*/
public function __destruct()
{
if (self::$config !== null) {
$this->clear();
}
}
}