Compiler.php 9.1 KB

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