Compiler.php 8.9 KB

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