Compiler.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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. * @throws \RuntimeException
  32. * @param string $pharFile The full path to the file to create
  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. ->sort($finderSort)
  106. ;
  107. foreach ($finder as $file) {
  108. $this->addFile($phar, $file);
  109. }
  110. $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/autoload.php'));
  111. $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/autoload_namespaces.php'));
  112. $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/autoload_psr4.php'));
  113. $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/autoload_classmap.php'));
  114. $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/autoload_real.php'));
  115. if (file_exists(__DIR__.'/../../vendor/composer/include_paths.php')) {
  116. $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/include_paths.php'));
  117. }
  118. $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/ClassLoader.php'));
  119. $this->addComposerBin($phar);
  120. // Stubs
  121. $phar->setStub($this->getStub());
  122. $phar->stopBuffering();
  123. // disabled for interoperability with systems without gzip ext
  124. // $phar->compressFiles(\Phar::GZ);
  125. $this->addFile($phar, new \SplFileInfo(__DIR__.'/../../LICENSE'), false);
  126. unset($phar);
  127. // re-sign the phar with reproducible timestamp / signature
  128. $util = new Timestamps($pharFile);
  129. $util->updateTimestamps($this->versionDate);
  130. $util->save($pharFile, \Phar::SHA1);
  131. }
  132. private function addFile($phar, $file, $strip = true)
  133. {
  134. $path = strtr(str_replace(dirname(dirname(__DIR__)).DIRECTORY_SEPARATOR, '', $file->getRealPath()), '\\', '/');
  135. $content = file_get_contents($file);
  136. if ($strip) {
  137. $content = $this->stripWhitespace($content);
  138. } elseif ('LICENSE' === basename($file)) {
  139. $content = "\n".$content."\n";
  140. }
  141. if ($path === 'src/Composer/Composer.php') {
  142. $content = str_replace('@package_version@', $this->version, $content);
  143. $content = str_replace('@package_branch_alias_version@', $this->branchAliasVersion, $content);
  144. $content = str_replace('@release_date@', $this->versionDate->format('Y-m-d H:i:s'), $content);
  145. }
  146. $phar->addFromString($path, $content);
  147. }
  148. private function addComposerBin($phar)
  149. {
  150. $content = file_get_contents(__DIR__.'/../../bin/composer');
  151. $content = preg_replace('{^#!/usr/bin/env php\s*}', '', $content);
  152. $phar->addFromString('bin/composer', $content);
  153. }
  154. /**
  155. * Removes whitespace from a PHP source string while preserving line numbers.
  156. *
  157. * @param string $source A PHP string
  158. * @return string The PHP string with the whitespace removed
  159. */
  160. private function stripWhitespace($source)
  161. {
  162. if (!function_exists('token_get_all')) {
  163. return $source;
  164. }
  165. $output = '';
  166. foreach (token_get_all($source) as $token) {
  167. if (is_string($token)) {
  168. $output .= $token;
  169. } elseif (in_array($token[0], array(T_COMMENT, T_DOC_COMMENT))) {
  170. $output .= str_repeat("\n", substr_count($token[1], "\n"));
  171. } elseif (T_WHITESPACE === $token[0]) {
  172. // reduce wide spaces
  173. $whitespace = preg_replace('{[ \t]+}', ' ', $token[1]);
  174. // normalize newlines to \n
  175. $whitespace = preg_replace('{(?:\r\n|\r|\n)}', "\n", $whitespace);
  176. // trim leading spaces
  177. $whitespace = preg_replace('{\n +}', "\n", $whitespace);
  178. $output .= $whitespace;
  179. } else {
  180. $output .= $token[1];
  181. }
  182. }
  183. return $output;
  184. }
  185. private function getStub()
  186. {
  187. $stub = <<<'EOF'
  188. #!/usr/bin/env php
  189. <?php
  190. /*
  191. * This file is part of Composer.
  192. *
  193. * (c) Nils Adermann <naderman@naderman.de>
  194. * Jordi Boggiano <j.boggiano@seld.be>
  195. *
  196. * For the full copyright and license information, please view
  197. * the license that is located at the bottom of this file.
  198. */
  199. // Avoid APC causing random fatal errors per https://github.com/composer/composer/issues/264
  200. if (extension_loaded('apc') && ini_get('apc.enable_cli') && ini_get('apc.cache_by_default')) {
  201. if (version_compare(phpversion('apc'), '3.0.12', '>=')) {
  202. ini_set('apc.cache_by_default', 0);
  203. } else {
  204. fwrite(STDERR, 'Warning: APC <= 3.0.12 may cause fatal errors when running composer commands.'.PHP_EOL);
  205. fwrite(STDERR, 'Update APC, or set apc.enable_cli or apc.cache_by_default to 0 in your php.ini.'.PHP_EOL);
  206. }
  207. }
  208. Phar::mapPhar('composer.phar');
  209. EOF;
  210. // add warning once the phar is older than 60 days
  211. if (preg_match('{^[a-f0-9]+$}', $this->version)) {
  212. $warningTime = $this->versionDate->format('U') + 60 * 86400;
  213. $stub .= "define('COMPOSER_DEV_WARNING_TIME', $warningTime);\n";
  214. }
  215. return $stub . <<<'EOF'
  216. require 'phar://composer.phar/bin/composer';
  217. __HALT_COMPILER();
  218. EOF;
  219. }
  220. }