PageRenderTime 633ms CodeModel.GetById 8ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Composer/Compiler.php

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