Compiler.php 9.9 KB

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