Compiler.php 10 KB

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