RootPackageLoader.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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\Package\Loader;
  12. use Composer\Package\BasePackage;
  13. use Composer\Package\AliasPackage;
  14. use Composer\Config;
  15. use Composer\Factory;
  16. use Composer\Package\Version\VersionParser;
  17. use Composer\Repository\RepositoryManager;
  18. use Composer\Repository\Vcs\HgDriver;
  19. use Composer\IO\NullIO;
  20. use Composer\Util\ProcessExecutor;
  21. use Composer\Util\Git as GitUtil;
  22. /**
  23. * ArrayLoader built for the sole purpose of loading the root package
  24. *
  25. * Sets additional defaults and loads repositories
  26. *
  27. * @author Jordi Boggiano <j.boggiano@seld.be>
  28. */
  29. class RootPackageLoader extends ArrayLoader
  30. {
  31. private $manager;
  32. private $config;
  33. private $process;
  34. public function __construct(RepositoryManager $manager, Config $config, VersionParser $parser = null, ProcessExecutor $process = null)
  35. {
  36. $this->manager = $manager;
  37. $this->config = $config;
  38. $this->process = $process ?: new ProcessExecutor();
  39. parent::__construct($parser);
  40. }
  41. public function load(array $config, $class = 'Composer\Package\RootPackage')
  42. {
  43. if (!isset($config['name'])) {
  44. $config['name'] = '__root__';
  45. }
  46. if (!isset($config['version'])) {
  47. // override with env var if available
  48. if (getenv('COMPOSER_ROOT_VERSION')) {
  49. $version = getenv('COMPOSER_ROOT_VERSION');
  50. } else {
  51. $version = $this->guessVersion($config);
  52. }
  53. if (!$version) {
  54. $version = '1.0.0';
  55. }
  56. $config['version'] = $version;
  57. }
  58. $realPackage = $package = parent::load($config, $class);
  59. if ($realPackage instanceof AliasPackage) {
  60. $realPackage = $package->getAliasOf();
  61. }
  62. if (isset($config['minimum-stability'])) {
  63. $realPackage->setMinimumStability(VersionParser::normalizeStability($config['minimum-stability']));
  64. }
  65. $aliases = array();
  66. $stabilityFlags = array();
  67. $references = array();
  68. foreach (array('require', 'require-dev') as $linkType) {
  69. if (isset($config[$linkType])) {
  70. $linkInfo = BasePackage::$supportedLinkTypes[$linkType];
  71. $method = 'get'.ucfirst($linkInfo['method']);
  72. $links = array();
  73. foreach ($realPackage->$method() as $link) {
  74. $links[$link->getTarget()] = $link->getConstraint()->getPrettyString();
  75. }
  76. $aliases = $this->extractAliases($links, $aliases);
  77. $stabilityFlags = $this->extractStabilityFlags($links, $stabilityFlags, $realPackage->getMinimumStability());
  78. $references = $this->extractReferences($links, $references);
  79. }
  80. }
  81. $realPackage->setAliases($aliases);
  82. $realPackage->setStabilityFlags($stabilityFlags);
  83. $realPackage->setReferences($references);
  84. if (isset($config['prefer-stable'])) {
  85. $realPackage->setPreferStable((bool) $config['prefer-stable']);
  86. }
  87. $repos = Factory::createDefaultRepositories(null, $this->config, $this->manager);
  88. foreach ($repos as $repo) {
  89. $this->manager->addRepository($repo);
  90. }
  91. $realPackage->setRepositories($this->config->getRepositories());
  92. return $package;
  93. }
  94. private function extractAliases(array $requires, array $aliases)
  95. {
  96. foreach ($requires as $reqName => $reqVersion) {
  97. if (preg_match('{^([^,\s#]+)(?:#[^ ]+)? +as +([^,\s]+)$}', $reqVersion, $match)) {
  98. $aliases[] = array(
  99. 'package' => strtolower($reqName),
  100. 'version' => $this->versionParser->normalize($match[1], $reqVersion),
  101. 'alias' => $match[2],
  102. 'alias_normalized' => $this->versionParser->normalize($match[2], $reqVersion),
  103. );
  104. }
  105. }
  106. return $aliases;
  107. }
  108. private function extractStabilityFlags(array $requires, array $stabilityFlags, $minimumStability)
  109. {
  110. $stabilities = BasePackage::$stabilities;
  111. $minimumStability = $stabilities[$minimumStability];
  112. foreach ($requires as $reqName => $reqVersion) {
  113. // parse explicit stability flags to the most unstable
  114. if (preg_match('{^[^,\s]*?@('.implode('|', array_keys($stabilities)).')$}i', $reqVersion, $match)) {
  115. $name = strtolower($reqName);
  116. $stability = $stabilities[VersionParser::normalizeStability($match[1])];
  117. if (isset($stabilityFlags[$name]) && $stabilityFlags[$name] > $stability) {
  118. continue;
  119. }
  120. $stabilityFlags[$name] = $stability;
  121. continue;
  122. }
  123. // infer flags for requirements that have an explicit -dev or -beta version specified but only
  124. // for those that are more unstable than the minimumStability or existing flags
  125. $reqVersion = preg_replace('{^([^,\s@]+) as .+$}', '$1', $reqVersion);
  126. if (preg_match('{^[^,\s@]+$}', $reqVersion) && 'stable' !== ($stabilityName = VersionParser::parseStability($reqVersion))) {
  127. $name = strtolower($reqName);
  128. $stability = $stabilities[$stabilityName];
  129. if ((isset($stabilityFlags[$name]) && $stabilityFlags[$name] > $stability) || ($minimumStability > $stability)) {
  130. continue;
  131. }
  132. $stabilityFlags[$name] = $stability;
  133. }
  134. }
  135. return $stabilityFlags;
  136. }
  137. private function extractReferences(array $requires, array $references)
  138. {
  139. foreach ($requires as $reqName => $reqVersion) {
  140. $reqVersion = preg_replace('{^([^,\s@]+) as .+$}', '$1', $reqVersion);
  141. if (preg_match('{^[^,\s@]+?#([a-f0-9]+)$}', $reqVersion, $match) && 'dev' === ($stabilityName = VersionParser::parseStability($reqVersion))) {
  142. $name = strtolower($reqName);
  143. $references[$name] = $match[1];
  144. }
  145. }
  146. return $references;
  147. }
  148. private function guessVersion(array $config)
  149. {
  150. if (function_exists('proc_open')) {
  151. $version = $this->guessGitVersion($config);
  152. if (null !== $version) {
  153. return $version;
  154. }
  155. return $this->guessHgVersion($config);
  156. }
  157. }
  158. private function guessGitVersion(array $config)
  159. {
  160. $util = new GitUtil;
  161. $util->cleanEnv();
  162. // try to fetch current version from git tags
  163. if (0 === $this->process->execute('git describe --exact-match --tags', $output)) {
  164. try {
  165. return $this->versionParser->normalize(trim($output));
  166. } catch (\Exception $e) {
  167. }
  168. }
  169. // try to fetch current version from git branch
  170. if (0 === $this->process->execute('git branch --no-color --no-abbrev -v', $output)) {
  171. $branches = array();
  172. $isFeatureBranch = false;
  173. $version = null;
  174. // find current branch and collect all branch names
  175. foreach ($this->process->splitLines($output) as $branch) {
  176. if ($branch && preg_match('{^(?:\* ) *(\(no branch\)|\(detached from [a-f0-9]+\)|\S+) *([a-f0-9]+) .*$}', $branch, $match)) {
  177. if ($match[1] === '(no branch)' || substr($match[1], 0, 10) === '(detached ') {
  178. $version = 'dev-'.$match[2];
  179. $isFeatureBranch = true;
  180. } else {
  181. $version = $this->versionParser->normalizeBranch($match[1]);
  182. $isFeatureBranch = 0 === strpos($version, 'dev-');
  183. if ('9999999-dev' === $version) {
  184. $version = 'dev-'.$match[1];
  185. }
  186. }
  187. }
  188. if ($branch && !preg_match('{^ *[^/]+/HEAD }', $branch)) {
  189. if (preg_match('{^(?:\* )? *(\S+) *([a-f0-9]+) .*$}', $branch, $match)) {
  190. $branches[] = $match[1];
  191. }
  192. }
  193. }
  194. if (!$isFeatureBranch) {
  195. return $version;
  196. }
  197. // try to find the best (nearest) version branch to assume this feature's version
  198. $version = $this->guessFeatureVersion($config, $version, $branches, 'git rev-list %candidate%..%branch%');
  199. return $version;
  200. }
  201. }
  202. private function guessHgVersion(array $config)
  203. {
  204. // try to fetch current version from hg branch
  205. if (0 === $this->process->execute('hg branch', $output)) {
  206. $branch = trim($output);
  207. $version = $this->versionParser->normalizeBranch($branch);
  208. $isFeatureBranch = 0 === strpos($version, 'dev-');
  209. if ('9999999-dev' === $version) {
  210. $version = 'dev-'.$branch;
  211. }
  212. if (!$isFeatureBranch) {
  213. return $version;
  214. }
  215. // re-use the HgDriver to fetch branches (this properly includes bookmarks)
  216. $config = array('url' => getcwd());
  217. $driver = new HgDriver($config, new NullIO(), $this->config, $this->process);
  218. $branches = array_keys($driver->getBranches());
  219. // try to find the best (nearest) version branch to assume this feature's version
  220. $version = $this->guessFeatureVersion($config, $version, $branches, 'hg log -r "not ancestors(\'%candidate%\') and ancestors(\'%branch%\')" --template "{node}\\n"');
  221. return $version;
  222. }
  223. }
  224. private function guessFeatureVersion(array $config, $version, array $branches, $scmCmdline)
  225. {
  226. // ignore feature branches if they have no branch-alias or self.version is used
  227. // and find the branch they came from to use as a version instead
  228. if ((isset($config['extra']['branch-alias']) && !isset($config['extra']['branch-alias'][$version]))
  229. || strpos(json_encode($config), '"self.version"')
  230. ) {
  231. $branch = preg_replace('{^dev-}', '', $version);
  232. $length = PHP_INT_MAX;
  233. foreach ($branches as $candidate) {
  234. // do not compare against other feature branches
  235. if ($candidate === $branch || !preg_match('{^(master|trunk|default|develop|\d+\..+)$}', $candidate, $match)) {
  236. continue;
  237. }
  238. $cmdLine = str_replace(array('%candidate%', '%branch%'), array($candidate, $branch), $scmCmdline);
  239. if (0 !== $this->process->execute($cmdLine, $output)) {
  240. continue;
  241. }
  242. if (strlen($output) < $length) {
  243. $length = strlen($output);
  244. $version = $this->versionParser->normalizeBranch($candidate);
  245. if ('9999999-dev' === $version) {
  246. $version = 'dev-'.$match[1];
  247. }
  248. }
  249. }
  250. }
  251. return $version;
  252. }
  253. }