-
-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
Compiler.php
292 lines (249 loc) · 9.95 KB
/
Compiler.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
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer;
use Composer\Json\JsonFile;
use Composer\Spdx\SpdxLicenses;
use Composer\CaBundle\CaBundle;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Process\Process;
use Seld\PharUtils\Timestamps;
use Seld\PharUtils\Linter;
/**
* The Compiler class compiles composer into a phar
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class Compiler
{
private $version;
private $branchAliasVersion = '';
private $versionDate;
/**
* Compiles composer into a single phar file
*
* @param string $pharFile The full path to the file to create
* @throws \RuntimeException
*/
public function compile($pharFile = 'composer.phar')
{
if (file_exists($pharFile)) {
unlink($pharFile);
}
$process = new Process('git log --pretty="%H" -n1 HEAD', __DIR__);
if ($process->run() != 0) {
throw new \RuntimeException('Can\'t run git log. You must ensure to run compile from composer git repository clone and that git binary is available.');
}
$this->version = trim($process->getOutput());
$process = new Process('git log -n1 --pretty=%ci HEAD', __DIR__);
if ($process->run() != 0) {
throw new \RuntimeException('Can\'t run git log. You must ensure to run compile from composer git repository clone and that git binary is available.');
}
$this->versionDate = new \DateTime(trim($process->getOutput()));
$this->versionDate->setTimezone(new \DateTimeZone('UTC'));
$process = new Process('git describe --tags --exact-match HEAD');
if ($process->run() == 0) {
$this->version = trim($process->getOutput());
} else {
// get branch-alias defined in composer.json for dev-master (if any)
$localConfig = __DIR__.'/../../composer.json';
$file = new JsonFile($localConfig);
$localConfig = $file->read();
if (isset($localConfig['extra']['branch-alias']['dev-master'])) {
$this->branchAliasVersion = $localConfig['extra']['branch-alias']['dev-master'];
}
}
$phar = new \Phar($pharFile, 0, 'composer.phar');
$phar->setSignatureAlgorithm(\Phar::SHA1);
$phar->startBuffering();
$finderSort = function ($a, $b) {
return strcmp(strtr($a->getRealPath(), '\\', '/'), strtr($b->getRealPath(), '\\', '/'));
};
// Add Composer sources
$finder = new Finder();
$finder->files()
->ignoreVCS(true)
->name('*.php')
->notName('Compiler.php')
->notName('ClassLoader.php')
->in(__DIR__.'/..')
->sort($finderSort)
;
foreach ($finder as $file) {
$this->addFile($phar, $file);
}
// Add ClassLoader separately to make sure it retains the docblocks as it will get copied into projects
$this->addFile($phar, new \SplFileInfo(__DIR__ . '/Autoload/ClassLoader.php'), false);
// Add Composer resources
$finder = new Finder();
$finder->files()
->in(__DIR__.'/../../res')
->sort($finderSort)
;
foreach ($finder as $file) {
$this->addFile($phar, $file, false);
}
// Add vendor files
$finder = new Finder();
$finder->files()
->ignoreVCS(true)
->notPath('/\/(composer\.(json|lock)|[A-Z]+\.md|\.gitignore|phpunit\.xml\.dist|phpstan\.neon\.dist|phpstan-config\.neon)$/')
->notPath('symfony/debug/Resources/ext/')
->notPath('justinrainbow/json-schema/demo/')
->notPath('justinrainbow/json-schema/dist/')
->notPath('composer/installed.json')
->notPath('composer/LICENSE')
->exclude('Tests')
->exclude('tests')
->exclude('docs')
->exclude('bin')
->in(__DIR__.'/../../vendor/')
->sort($finderSort)
;
$extraFiles = array(
realpath(__DIR__ . '/../../vendor/composer/spdx-licenses/res/spdx-exceptions.json'),
realpath(__DIR__ . '/../../vendor/composer/spdx-licenses/res/spdx-licenses.json'),
realpath(CaBundle::getBundledCaBundlePath()),
realpath(__DIR__ . '/../../vendor/symfony/console/Resources/bin/hiddeninput.exe'),
realpath(__DIR__ . '/../../vendor/symfony/polyfill-mbstring/Resources/mb_convert_variables.php8'),
);
foreach ($finder as $file) {
if (!preg_match('{(/LICENSE|\.php)$}', $file) && !in_array(realpath($file), $extraFiles, true)) {
throw new \RuntimeException('Unexpected file should be added to the allow or deny lists: '.$file);
}
if (preg_match('{\.php[\d.]*$}', $file)) {
$this->addFile($phar, $file);
} else {
$this->addFile($phar, $file, false);
}
}
// Add bin/composer
$this->addComposerBin($phar);
// Stubs
$phar->setStub($this->getStub());
$phar->stopBuffering();
// disabled for interoperability with systems without gzip ext
// $phar->compressFiles(\Phar::GZ);
$this->addFile($phar, new \SplFileInfo(__DIR__.'/../../LICENSE'), false);
unset($phar);
// re-sign the phar with reproducible timestamp / signature
$util = new Timestamps($pharFile);
$util->updateTimestamps($this->versionDate);
$util->save($pharFile, \Phar::SHA1);
Linter::lint($pharFile);
}
/**
* @param \SplFileInfo $file
* @return string
*/
private function getRelativeFilePath($file)
{
$realPath = $file->getRealPath();
$pathPrefix = dirname(dirname(__DIR__)).DIRECTORY_SEPARATOR;
$pos = strpos($realPath, $pathPrefix);
$relativePath = ($pos !== false) ? substr_replace($realPath, '', $pos, strlen($pathPrefix)) : $realPath;
return strtr($relativePath, '\\', '/');
}
private function addFile($phar, $file, $strip = true)
{
$path = $this->getRelativeFilePath($file);
$content = file_get_contents($file);
if ($strip) {
$content = $this->stripWhitespace($content);
} elseif ('LICENSE' === basename($file)) {
$content = "\n".$content."\n";
}
if ($path === 'src/Composer/Composer.php') {
$content = strtr(
$content,
array(
'@package_version@' => $this->version,
'@package_branch_alias_version@' => $this->branchAliasVersion,
'@release_date@' => $this->versionDate->format('Y-m-d H:i:s')
)
);
$content = preg_replace('{SOURCE_VERSION = \'[^\']+\';}', 'SOURCE_VERSION = \'\';', $content);
}
$phar->addFromString($path, $content);
}
private function addComposerBin($phar)
{
$content = file_get_contents(__DIR__.'/../../bin/composer');
$content = preg_replace('{^#!/usr/bin/env php\s*}', '', $content);
$phar->addFromString('bin/composer', $content);
}
/**
* Removes whitespace from a PHP source string while preserving line numbers.
*
* @param string $source A PHP string
* @return string The PHP string with the whitespace removed
*/
private function stripWhitespace($source)
{
if (!function_exists('token_get_all')) {
return $source;
}
$output = '';
foreach (token_get_all($source) as $token) {
if (is_string($token)) {
$output .= $token;
} elseif (in_array($token[0], array(T_COMMENT, T_DOC_COMMENT))) {
$output .= str_repeat("\n", substr_count($token[1], "\n"));
} elseif (T_WHITESPACE === $token[0]) {
// reduce wide spaces
$whitespace = preg_replace('{[ \t]+}', ' ', $token[1]);
// normalize newlines to \n
$whitespace = preg_replace('{(?:\r\n|\r|\n)}', "\n", $whitespace);
// trim leading spaces
$whitespace = preg_replace('{\n +}', "\n", $whitespace);
$output .= $whitespace;
} else {
$output .= $token[1];
}
}
return $output;
}
private function getStub()
{
$stub = <<<'EOF'
#!/usr/bin/env php
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view
* the license that is located at the bottom of this file.
*/
// Avoid APC causing random fatal errors per https://github.com/composer/composer/issues/264
if (extension_loaded('apc') && filter_var(ini_get('apc.enable_cli'), FILTER_VALIDATE_BOOLEAN) && filter_var(ini_get('apc.cache_by_default'), FILTER_VALIDATE_BOOLEAN)) {
if (version_compare(phpversion('apc'), '3.0.12', '>=')) {
ini_set('apc.cache_by_default', 0);
} else {
fwrite(STDERR, 'Warning: APC <= 3.0.12 may cause fatal errors when running composer commands.'.PHP_EOL);
fwrite(STDERR, 'Update APC, or set apc.enable_cli or apc.cache_by_default to 0 in your php.ini.'.PHP_EOL);
}
}
Phar::mapPhar('composer.phar');
EOF;
// add warning once the phar is older than 60 days
if (preg_match('{^[a-f0-9]+$}', $this->version)) {
$warningTime = $this->versionDate->format('U') + 60 * 86400;
$stub .= "define('COMPOSER_DEV_WARNING_TIME', $warningTime);\n";
}
return $stub . <<<'EOF'
require 'phar://composer.phar/bin/composer';
__HALT_COMPILER();
EOF;
}
}