Compiler.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer;
  12. use Composer\Json\JsonFile;
  13. use Composer\Spdx\SpdxLicenses;
  14. use Composer\CaBundle\CaBundle;
  15. use Symfony\Component\Finder\Finder;
  16. use Symfony\Component\Process\Process;
  17. use Seld\PharUtils\Timestamps;
  18. use Seld\PharUtils\Linter;
  19. /**
  20. * The Compiler class compiles composer into a phar
  21. *
  22. * @author Fabien Potencier <fabien@symfony.com>
  23. * @author Jordi Boggiano <j.boggiano@seld.be>
  24. */
  25. class Compiler
  26. {
  27. private $version;
  28. private $branchAliasVersion = '';
  29. private $versionDate;
  30. /**
  31. * Compiles composer into a single phar file
  32. *
  33. * @param string $pharFile The full path to the file to create
  34. * @throws \RuntimeException
  35. */
  36. public function compile($pharFile = 'composer.phar')
  37. {
  38. if (file_exists($pharFile)) {
  39. unlink($pharFile);
  40. }
  41. $process = new Process('git log --pretty="%H" -n1 HEAD', __DIR__);
  42. if ($process->run() != 0) {
  43. 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.');
  44. }
  45. $this->version = trim($process->getOutput());
  46. $process = new Process('git log -n1 --pretty=%ci HEAD', __DIR__);
  47. if ($process->run() != 0) {
  48. 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.');
  49. }
  50. $this->versionDate = new \DateTime(trim($process->getOutput()));
  51. $this->versionDate->setTimezone(new \DateTimeZone('UTC'));
  52. $process = new Process('git describe --tags --exact-match HEAD');
  53. if ($process->run() == 0) {
  54. $this->version = trim($process->getOutput());
  55. } else {
  56. // get branch-alias defined in composer.json for dev-master (if any)
  57. $localConfig = __DIR__.'/../../composer.json';
  58. $file = new JsonFile($localConfig);
  59. $localConfig = $file->read();
  60. if (isset($localConfig['extra']['branch-alias']['dev-master'])) {
  61. $this->branchAliasVersion = $localConfig['extra']['branch-alias']['dev-master'];
  62. }
  63. }
  64. $phar = new \Phar($pharFile, 0, 'composer.phar');
  65. $phar->setSignatureAlgorithm(\Phar::SHA1);
  66. $phar->startBuffering();
  67. $finderSort = function ($a, $b) {
  68. return strcmp(strtr($a->getRealPath(), '\\', '/'), strtr($b->getRealPath(), '\\', '/'));
  69. };
  70. $finder = new Finder();
  71. $finder->files()
  72. ->ignoreVCS(true)
  73. ->name('*.php')
  74. ->notName('Compiler.php')
  75. ->notName('ClassLoader.php')
  76. ->in(__DIR__.'/..')
  77. ->sort($finderSort)
  78. ;
  79. foreach ($finder as $file) {
  80. $this->addFile($phar, $file);
  81. }
  82. $this->addFile($phar, new \SplFileInfo(__DIR__ . '/Autoload/ClassLoader.php'), false);
  83. $finder = new Finder();
  84. $finder->files()
  85. ->name('*.json')
  86. ->in(__DIR__.'/../../res')
  87. ->in(SpdxLicenses::getResourcesDir())
  88. ->sort($finderSort)
  89. ;
  90. foreach ($finder as $file) {
  91. $this->addFile($phar, $file, false);
  92. }
  93. $this->addFile($phar, new \SplFileInfo(__DIR__ . '/../../vendor/symfony/console/Resources/bin/hiddeninput.exe'), false);
  94. $finder = new Finder();
  95. $finder->files()
  96. ->ignoreVCS(true)
  97. ->name('*.php')
  98. ->name('LICENSE')
  99. ->exclude('Tests')
  100. ->exclude('tests')
  101. ->exclude('docs')
  102. ->in(__DIR__.'/../../vendor/symfony/')
  103. ->in(__DIR__.'/../../vendor/seld/jsonlint/')
  104. ->in(__DIR__.'/../../vendor/justinrainbow/json-schema/')
  105. ->in(__DIR__.'/../../vendor/composer/spdx-licenses/')
  106. ->in(__DIR__.'/../../vendor/composer/semver/')
  107. ->in(__DIR__.'/../../vendor/composer/ca-bundle/')
  108. ->in(__DIR__.'/../../vendor/composer/xdebug-handler/')
  109. ->in(__DIR__.'/../../vendor/psr/')
  110. ->in(__DIR__.'/../../vendor/react/')
  111. ->sort($finderSort)
  112. ;
  113. foreach ($finder as $file) {
  114. $this->addFile($phar, $file);
  115. }
  116. $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/autoload.php'));
  117. $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/autoload_namespaces.php'));
  118. $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/autoload_psr4.php'));
  119. $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/autoload_classmap.php'));
  120. $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/autoload_files.php'));
  121. $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/autoload_real.php'));
  122. $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/autoload_static.php'));
  123. if (file_exists(__DIR__.'/../../vendor/composer/platform_check.php')) {
  124. $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/platform_check.php'));
  125. }
  126. if (file_exists(__DIR__.'/../../vendor/composer/include_paths.php')) {
  127. $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/include_paths.php'));
  128. }
  129. $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/ClassLoader.php'));
  130. $this->addFile($phar, new \SplFileInfo(CaBundle::getBundledCaBundlePath()), false);
  131. $this->addComposerBin($phar);
  132. // Stubs
  133. $phar->setStub($this->getStub());
  134. $phar->stopBuffering();
  135. // disabled for interoperability with systems without gzip ext
  136. // $phar->compressFiles(\Phar::GZ);
  137. $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../LICENSE'), false);
  138. unset($phar);
  139. // re-sign the phar with reproducible timestamp / signature
  140. $util = new Timestamps($pharFile);
  141. $util->updateTimestamps($this->versionDate);
  142. $util->save($pharFile, \Phar::SHA1);
  143. Linter::lint($pharFile);
  144. }
  145. /**
  146. * @param \SplFileInfo $file
  147. * @return string
  148. */
  149. private function getRelativeFilePath($file)
  150. {
  151. $realPath = $file->getRealPath();
  152. $pathPrefix = dirname(dirname(__DIR__)).DIRECTORY_SEPARATOR;
  153. $pos = strpos($realPath, $pathPrefix);
  154. $relativePath = ($pos !== false) ? substr_replace($realPath, '', $pos, strlen($pathPrefix)) : $realPath;
  155. return strtr($relativePath, '\\', '/');
  156. }
  157. private function addFile($phar, $file, $strip = true)
  158. {
  159. $path = $this->getRelativeFilePath($file);
  160. $content = file_get_contents($file);
  161. if ($strip) {
  162. $content = $this->stripWhitespace($content);
  163. } elseif ('LICENSE' === basename($file)) {
  164. $content = "\n".$content."\n";
  165. }
  166. if ($path === 'src/Composer/Composer.php') {
  167. $content = str_replace('@package_version@', $this->version, $content);
  168. $content = str_replace('@package_branch_alias_version@', $this->branchAliasVersion, $content);
  169. $content = str_replace('@release_date@', $this->versionDate->format('Y-m-d H:i:s'), $content);
  170. $content = preg_replace('{SOURCE_VERSION = \'[^\']+\';}', 'SOURCE_VERSION = \'\';', $content);
  171. }
  172. $phar->addFromString($path, $content);
  173. }
  174. private function addComposerBin($phar)
  175. {
  176. $content = file_get_contents(__DIR__.'/../../bin/composer');
  177. $content = preg_replace('{^#!/usr/bin/env php\s*}', '', $content);
  178. $phar->addFromString('bin/composer', $content);
  179. }
  180. /**
  181. * Removes whitespace from a PHP source string while preserving line numbers.
  182. *
  183. * @param string $source A PHP string
  184. * @return string The PHP string with the whitespace removed
  185. */
  186. private function stripWhitespace($source)
  187. {
  188. if (!function_exists('token_get_all')) {
  189. return $source;
  190. }
  191. $output = '';
  192. foreach (token_get_all($source) as $token) {
  193. if (is_string($token)) {
  194. $output .= $token;
  195. } elseif (in_array($token[0], array(T_COMMENT, T_DOC_COMMENT))) {
  196. $output .= str_repeat("\n", substr_count($token[1], "\n"));
  197. } elseif (T_WHITESPACE === $token[0]) {
  198. // reduce wide spaces
  199. $whitespace = preg_replace('{[ \t]+}', ' ', $token[1]);
  200. // normalize newlines to \n
  201. $whitespace = preg_replace('{(?:\r\n|\r|\n)}', "\n", $whitespace);
  202. // trim leading spaces
  203. $whitespace = preg_replace('{\n +}', "\n", $whitespace);
  204. $output .= $whitespace;
  205. } else {
  206. $output .= $token[1];
  207. }
  208. }
  209. return $output;
  210. }
  211. private function getStub()
  212. {
  213. $stub = <<<'EOF'
  214. #!/usr/bin/env php
  215. <?php
  216. /*
  217. * This file is part of Composer.
  218. *
  219. * (c) Nils Adermann <naderman@naderman.de>
  220. * Jordi Boggiano <j.boggiano@seld.be>
  221. *
  222. * For the full copyright and license information, please view
  223. * the license that is located at the bottom of this file.
  224. */
  225. // Avoid APC causing random fatal errors per https://github.com/composer/composer/issues/264
  226. 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)) {
  227. if (version_compare(phpversion('apc'), '3.0.12', '>=')) {
  228. ini_set('apc.cache_by_default', 0);
  229. } else {
  230. fwrite(STDERR, 'Warning: APC <= 3.0.12 may cause fatal errors when running composer commands.'.PHP_EOL);
  231. fwrite(STDERR, 'Update APC, or set apc.enable_cli or apc.cache_by_default to 0 in your php.ini.'.PHP_EOL);
  232. }
  233. }
  234. Phar::mapPhar('composer.phar');
  235. EOF;
  236. // add warning once the phar is older than 60 days
  237. if (preg_match('{^[a-f0-9]+$}', $this->version)) {
  238. $warningTime = $this->versionDate->format('U') + 60 * 86400;
  239. $stub .= "define('COMPOSER_DEV_WARNING_TIME', $warningTime);\n";
  240. }
  241. return $stub . <<<'EOF'
  242. require 'phar://composer.phar/bin/composer';
  243. __HALT_COMPILER();
  244. EOF;
  245. }
  246. }