VersionParser.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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\Version;
  12. use Composer\Package\BasePackage;
  13. use Composer\Package\PackageInterface;
  14. use Composer\Package\Link;
  15. use Composer\Package\LinkConstraint\EmptyConstraint;
  16. use Composer\Package\LinkConstraint\MultiConstraint;
  17. use Composer\Package\LinkConstraint\VersionConstraint;
  18. /**
  19. * Version parser
  20. *
  21. * @author Jordi Boggiano <j.boggiano@seld.be>
  22. */
  23. class VersionParser
  24. {
  25. private static $modifierRegex = '[._-]?(?:(stable|beta|b|RC|alpha|a|patch|pl|p)(?:[.-]?(\d+))?)?([.-]?dev)?';
  26. /**
  27. * Returns the stability of a version
  28. *
  29. * @param string $version
  30. * @return string
  31. */
  32. public static function parseStability($version)
  33. {
  34. $version = preg_replace('{#.+$}i', '', $version);
  35. if ('dev-' === substr($version, 0, 4) || '-dev' === substr($version, -4)) {
  36. return 'dev';
  37. }
  38. preg_match('{'.self::$modifierRegex.'$}i', strtolower($version), $match);
  39. if (!empty($match[3])) {
  40. return 'dev';
  41. }
  42. if (!empty($match[1])) {
  43. if ('beta' === $match[1] || 'b' === $match[1]) {
  44. return 'beta';
  45. }
  46. if ('alpha' === $match[1] || 'a' === $match[1]) {
  47. return 'alpha';
  48. }
  49. if ('rc' === $match[1]) {
  50. return 'RC';
  51. }
  52. }
  53. return 'stable';
  54. }
  55. public static function normalizeStability($stability)
  56. {
  57. $stability = strtolower($stability);
  58. return $stability === 'rc' ? 'RC' : $stability;
  59. }
  60. public static function formatVersion(PackageInterface $package, $truncate = true)
  61. {
  62. if (!$package->isDev() || !in_array($package->getSourceType(), array('hg', 'git'))) {
  63. return $package->getPrettyVersion();
  64. }
  65. // if source reference is a sha1 hash -- truncate
  66. if ($truncate && strlen($package->getSourceReference()) === 40) {
  67. return $package->getPrettyVersion() . ' ' . substr($package->getSourceReference(), 0, 7);
  68. }
  69. return $package->getPrettyVersion() . ' ' . $package->getSourceReference();
  70. }
  71. /**
  72. * Normalizes a version string to be able to perform comparisons on it
  73. *
  74. * @param string $version
  75. * @param string $fullVersion optional complete version string to give more context
  76. * @throws \UnexpectedValueException
  77. * @return string
  78. */
  79. public function normalize($version, $fullVersion = null)
  80. {
  81. $version = trim($version);
  82. if (null === $fullVersion) {
  83. $fullVersion = $version;
  84. }
  85. // ignore aliases and just assume the alias is required instead of the source
  86. if (preg_match('{^([^,\s]+) +as +([^,\s]+)$}', $version, $match)) {
  87. $version = $match[1];
  88. }
  89. // ignore build metadata
  90. if (preg_match('{^([^,\s+]+)\+[^\s]+$}', $version, $match)) {
  91. $version = $match[1];
  92. }
  93. // match master-like branches
  94. if (preg_match('{^(?:dev-)?(?:master|trunk|default)$}i', $version)) {
  95. return '9999999-dev';
  96. }
  97. if ('dev-' === strtolower(substr($version, 0, 4))) {
  98. return 'dev-'.substr($version, 4);
  99. }
  100. // match classical versioning
  101. if (preg_match('{^v?(\d{1,3})(\.\d+)?(\.\d+)?(\.\d+)?'.self::$modifierRegex.'$}i', $version, $matches)) {
  102. $version = $matches[1]
  103. .(!empty($matches[2]) ? $matches[2] : '.0')
  104. .(!empty($matches[3]) ? $matches[3] : '.0')
  105. .(!empty($matches[4]) ? $matches[4] : '.0');
  106. $index = 5;
  107. } elseif (preg_match('{^v?(\d{4}(?:[.:-]?\d{2}){1,6}(?:[.:-]?\d{1,3})?)'.self::$modifierRegex.'$}i', $version, $matches)) { // match date-based versioning
  108. $version = preg_replace('{\D}', '-', $matches[1]);
  109. $index = 2;
  110. } elseif (preg_match('{^v?(\d{4,})(\.\d+)?(\.\d+)?(\.\d+)?'.self::$modifierRegex.'$}i', $version, $matches)) {
  111. $version = $matches[1]
  112. .(!empty($matches[2]) ? $matches[2] : '.0')
  113. .(!empty($matches[3]) ? $matches[3] : '.0')
  114. .(!empty($matches[4]) ? $matches[4] : '.0');
  115. $index = 5;
  116. }
  117. // add version modifiers if a version was matched
  118. if (isset($index)) {
  119. if (!empty($matches[$index])) {
  120. if ('stable' === $matches[$index]) {
  121. return $version;
  122. }
  123. $version .= '-' . $this->expandStability($matches[$index]) . (!empty($matches[$index+1]) ? $matches[$index+1] : '');
  124. }
  125. if (!empty($matches[$index+2])) {
  126. $version .= '-dev';
  127. }
  128. return $version;
  129. }
  130. // match dev branches
  131. if (preg_match('{(.*?)[.-]?dev$}i', $version, $match)) {
  132. try {
  133. return $this->normalizeBranch($match[1]);
  134. } catch (\Exception $e) {
  135. }
  136. }
  137. $extraMessage = '';
  138. if (preg_match('{ +as +'.preg_quote($version).'$}', $fullVersion)) {
  139. $extraMessage = ' in "'.$fullVersion.'", the alias must be an exact version';
  140. } elseif (preg_match('{^'.preg_quote($version).' +as +}', $fullVersion)) {
  141. $extraMessage = ' in "'.$fullVersion.'", the alias source must be an exact version, if it is a branch name you should prefix it with dev-';
  142. }
  143. throw new \UnexpectedValueException('Invalid version string "'.$version.'"'.$extraMessage);
  144. }
  145. /**
  146. * Extract numeric prefix from alias, if it is in numeric format, suitable for
  147. * version comparison
  148. *
  149. * @param string $branch Branch name (e.g. 2.1.x-dev)
  150. * @return string|false Numeric prefix if present (e.g. 2.1.) or false
  151. */
  152. public function parseNumericAliasPrefix($branch) {
  153. if(preg_match('/^(?<version>(\d+\\.)*\d+).x-dev$/i', $branch, $matches)) {
  154. return $matches['version'].".";
  155. } else {
  156. return false;
  157. }
  158. }
  159. /**
  160. * Normalizes a branch name to be able to perform comparisons on it
  161. *
  162. * @param string $name
  163. * @return string
  164. */
  165. public function normalizeBranch($name)
  166. {
  167. $name = trim($name);
  168. if (in_array($name, array('master', 'trunk', 'default'))) {
  169. return $this->normalize($name);
  170. }
  171. if (preg_match('#^v?(\d+)(\.(?:\d+|[xX*]))?(\.(?:\d+|[xX*]))?(\.(?:\d+|[xX*]))?$#i', $name, $matches)) {
  172. $version = '';
  173. for ($i = 1; $i < 5; $i++) {
  174. $version .= isset($matches[$i]) ? str_replace(array('*', 'X'), 'x', $matches[$i]) : '.x';
  175. }
  176. return str_replace('x', '9999999', $version).'-dev';
  177. }
  178. return 'dev-'.$name;
  179. }
  180. /**
  181. * @param string $source source package name
  182. * @param string $sourceVersion source package version (pretty version ideally)
  183. * @param string $description link description (e.g. requires, replaces, ..)
  184. * @param array $links array of package name => constraint mappings
  185. * @return Link[]
  186. */
  187. public function parseLinks($source, $sourceVersion, $description, $links)
  188. {
  189. $res = array();
  190. foreach ($links as $target => $constraint) {
  191. if ('self.version' === $constraint) {
  192. $parsedConstraint = $this->parseConstraints($sourceVersion);
  193. } else {
  194. $parsedConstraint = $this->parseConstraints($constraint);
  195. }
  196. $res[strtolower($target)] = new Link($source, $target, $parsedConstraint, $description, $constraint);
  197. }
  198. return $res;
  199. }
  200. /**
  201. * Parses as constraint string into LinkConstraint objects
  202. *
  203. * @param string $constraints
  204. * @return \Composer\Package\LinkConstraint\LinkConstraintInterface
  205. */
  206. public function parseConstraints($constraints)
  207. {
  208. $prettyConstraint = $constraints;
  209. if (preg_match('{^([^,\s]*?)@('.implode('|', array_keys(BasePackage::$stabilities)).')$}i', $constraints, $match)) {
  210. $constraints = empty($match[1]) ? '*' : $match[1];
  211. }
  212. if (preg_match('{^(dev-[^,\s@]+?|[^,\s@]+?\.x-dev)#.+$}i', $constraints, $match)) {
  213. $constraints = $match[1];
  214. }
  215. $orConstraints = preg_split('{\s*\|\|?\s*}', trim($constraints));
  216. $orGroups = array();
  217. foreach ($orConstraints as $constraints) {
  218. $andConstraints = preg_split('{(?<!^|as|[=>< ,]) *(?<!-)[, ](?!-) *(?!,|as|$)}', $constraints);
  219. if (count($andConstraints) > 1) {
  220. $constraintObjects = array();
  221. foreach ($andConstraints as $constraint) {
  222. $constraintObjects = array_merge($constraintObjects, $this->parseConstraint($constraint));
  223. }
  224. } else {
  225. $constraintObjects = $this->parseConstraint($andConstraints[0]);
  226. }
  227. if (1 === count($constraintObjects)) {
  228. $constraint = $constraintObjects[0];
  229. } else {
  230. $constraint = new MultiConstraint($constraintObjects);
  231. }
  232. $orGroups[] = $constraint;
  233. }
  234. if (1 === count($orGroups)) {
  235. $constraint = $orGroups[0];
  236. } else {
  237. $constraint = new MultiConstraint($orGroups, false);
  238. }
  239. $constraint->setPrettyString($prettyConstraint);
  240. return $constraint;
  241. }
  242. private function parseConstraint($constraint)
  243. {
  244. if (preg_match('{^([^,\s]+?)@('.implode('|', array_keys(BasePackage::$stabilities)).')$}i', $constraint, $match)) {
  245. $constraint = $match[1];
  246. if ($match[2] !== 'stable') {
  247. $stabilityModifier = $match[2];
  248. }
  249. }
  250. if (preg_match('{^[xX*](\.[xX*])*$}i', $constraint)) {
  251. return array(new EmptyConstraint);
  252. }
  253. $versionRegex = '(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:\.(\d+))?'.self::$modifierRegex;
  254. // match tilde constraints
  255. // like wildcard constraints, unsuffixed tilde constraints say that they must be greater than the previous
  256. // version, to ensure that unstable instances of the current version are allowed.
  257. // however, if a stability suffix is added to the constraint, then a >= match on the current version is
  258. // used instead
  259. if (preg_match('{^~>?'.$versionRegex.'$}i', $constraint, $matches)) {
  260. if (substr($constraint, 0, 2) === '~>') {
  261. throw new \UnexpectedValueException(
  262. 'Could not parse version constraint '.$constraint.': '.
  263. 'Invalid operator "~>", you probably meant to use the "~" operator'
  264. );
  265. }
  266. // Work out which position in the version we are operating at
  267. if (isset($matches[4]) && '' !== $matches[4]) {
  268. $position = 4;
  269. } elseif (isset($matches[3]) && '' !== $matches[3]) {
  270. $position = 3;
  271. } elseif (isset($matches[2]) && '' !== $matches[2]) {
  272. $position = 2;
  273. } else {
  274. $position = 1;
  275. }
  276. // Calculate the stability suffix
  277. $stabilitySuffix = '';
  278. if (!empty($matches[5])) {
  279. $stabilitySuffix .= '-' . $this->expandStability($matches[5]) . (!empty($matches[6]) ? $matches[6] : '');
  280. }
  281. if (!empty($matches[7])) {
  282. $stabilitySuffix .= '-dev';
  283. }
  284. if (!$stabilitySuffix) {
  285. $stabilitySuffix = "-dev";
  286. }
  287. $lowVersion = $this->manipulateVersionString($matches, $position, 0) . $stabilitySuffix;
  288. $lowerBound = new VersionConstraint('>=', $lowVersion);
  289. // For upper bound, we increment the position of one more significance,
  290. // but highPosition = 0 would be illegal
  291. $highPosition = max(1, $position - 1);
  292. $highVersion = $this->manipulateVersionString($matches, $highPosition, 1) . '-dev';
  293. $upperBound = new VersionConstraint('<', $highVersion);
  294. return array(
  295. $lowerBound,
  296. $upperBound
  297. );
  298. }
  299. // match caret constraints
  300. if (preg_match('{^\^'.$versionRegex.'($)}i', $constraint, $matches)) {
  301. // Work out which position in the version we are operating at
  302. if ('0' !== $matches[1] || '' === $matches[2]) {
  303. $position = 1;
  304. } elseif ('0' !== $matches[2] || '' === $matches[3]) {
  305. $position = 2;
  306. } else {
  307. $position = 3;
  308. }
  309. // Calculate the stability suffix
  310. $stabilitySuffix = '';
  311. if (empty($matches[5]) && empty($matches[7])) {
  312. $stabilitySuffix .= '-dev';
  313. }
  314. $lowVersion = $this->normalize(substr($constraint . $stabilitySuffix, 1));
  315. $lowerBound = new VersionConstraint('>=', $lowVersion);
  316. // For upper bound, we increment the position of one more significance,
  317. // but highPosition = 0 would be illegal
  318. $highVersion = $this->manipulateVersionString($matches, $position, 1) . '-dev';
  319. $upperBound = new VersionConstraint('<', $highVersion);
  320. return array(
  321. $lowerBound,
  322. $upperBound
  323. );
  324. }
  325. // match wildcard constraints
  326. if (preg_match('{^(\d+)(?:\.(\d+))?(?:\.(\d+))?\.[xX*]$}', $constraint, $matches)) {
  327. if (isset($matches[3]) && '' !== $matches[3]) {
  328. $position = 3;
  329. } elseif (isset($matches[2]) && '' !== $matches[2]) {
  330. $position = 2;
  331. } else {
  332. $position = 1;
  333. }
  334. $lowVersion = $this->manipulateVersionString($matches, $position) . "-dev";
  335. $highVersion = $this->manipulateVersionString($matches, $position, 1) . "-dev";
  336. if ($lowVersion === "0.0.0.0-dev") {
  337. return array(new VersionConstraint('<', $highVersion));
  338. }
  339. return array(
  340. new VersionConstraint('>=', $lowVersion),
  341. new VersionConstraint('<', $highVersion),
  342. );
  343. }
  344. // match hyphen constraints
  345. if (preg_match('{^(?P<from>'.$versionRegex.') +- +(?P<to>'.$versionRegex.')($)}i', $constraint, $matches)) {
  346. // Calculate the stability suffix
  347. $lowStabilitySuffix = '';
  348. if (empty($matches[6]) && empty($matches[8])) {
  349. $lowStabilitySuffix = '-dev';
  350. }
  351. $lowVersion = $this->normalize($matches['from']);
  352. $lowerBound = new VersionConstraint('>=', $lowVersion . $lowStabilitySuffix);
  353. $highVersion = $matches[10];
  354. if ((!empty($matches[11]) && !empty($matches[12])) || !empty($matches[14]) || !empty($matches[16])) {
  355. $highVersion = $this->normalize($matches['to']);
  356. $upperBound = new VersionConstraint('<=', $highVersion);
  357. } else {
  358. $highMatch = array('', $matches[10], $matches[11], $matches[12], $matches[13]);
  359. $highVersion = $this->manipulateVersionString($highMatch, empty($matches[11]) ? 1 : 2, 1) . '-dev';
  360. $upperBound = new VersionConstraint('<', $highVersion);
  361. }
  362. return array(
  363. $lowerBound,
  364. $upperBound
  365. );
  366. }
  367. // match operators constraints
  368. if (preg_match('{^(<>|!=|>=?|<=?|==?)?\s*(.*)}', $constraint, $matches)) {
  369. try {
  370. $version = $this->normalize($matches[2]);
  371. if (!empty($stabilityModifier) && $this->parseStability($version) === 'stable') {
  372. $version .= '-' . $stabilityModifier;
  373. } elseif ('<' === $matches[1]) {
  374. if (!preg_match('/-' . self::$modifierRegex . '$/', strtolower($matches[2]))) {
  375. $version .= '-dev';
  376. }
  377. }
  378. return array(new VersionConstraint($matches[1] ?: '=', $version));
  379. } catch (\Exception $e) {
  380. }
  381. }
  382. $message = 'Could not parse version constraint '.$constraint;
  383. if (isset($e)) {
  384. $message .= ': '. $e->getMessage();
  385. }
  386. throw new \UnexpectedValueException($message);
  387. }
  388. /**
  389. * Increment, decrement, or simply pad a version number.
  390. *
  391. * Support function for {@link parseConstraint()}
  392. *
  393. * @param array $matches Array with version parts in array indexes 1,2,3,4
  394. * @param int $position 1,2,3,4 - which segment of the version to decrement
  395. * @param int $increment
  396. * @param string $pad The string to pad version parts after $position
  397. * @return string The new version
  398. */
  399. private function manipulateVersionString($matches, $position, $increment = 0, $pad = '0')
  400. {
  401. for ($i = 4; $i > 0; $i--) {
  402. if ($i > $position) {
  403. $matches[$i] = $pad;
  404. } elseif ($i == $position && $increment) {
  405. $matches[$i] += $increment;
  406. // If $matches[$i] was 0, carry the decrement
  407. if ($matches[$i] < 0) {
  408. $matches[$i] = $pad;
  409. $position--;
  410. // Return null on a carry overflow
  411. if ($i == 1) {
  412. return;
  413. }
  414. }
  415. }
  416. }
  417. return $matches[1] . '.' . $matches[2] . '.' . $matches[3] . '.' . $matches[4];
  418. }
  419. private function expandStability($stability)
  420. {
  421. $stability = strtolower($stability);
  422. switch ($stability) {
  423. case 'a':
  424. return 'alpha';
  425. case 'b':
  426. return 'beta';
  427. case 'p':
  428. case 'pl':
  429. return 'patch';
  430. case 'rc':
  431. return 'RC';
  432. default:
  433. return $stability;
  434. }
  435. }
  436. /**
  437. * Parses a name/version pairs and returns an array of pairs + the
  438. *
  439. * @param array $pairs a set of package/version pairs separated by ":", "=" or " "
  440. * @return array[] array of arrays containing a name and (if provided) a version
  441. */
  442. public function parseNameVersionPairs(array $pairs)
  443. {
  444. $pairs = array_values($pairs);
  445. $result = array();
  446. for ($i = 0, $count = count($pairs); $i < $count; $i++) {
  447. $pair = preg_replace('{^([^=: ]+)[=: ](.*)$}', '$1 $2', trim($pairs[$i]));
  448. if (false === strpos($pair, ' ') && isset($pairs[$i+1]) && false === strpos($pairs[$i+1], '/')) {
  449. $pair .= ' '.$pairs[$i+1];
  450. $i++;
  451. }
  452. if (strpos($pair, ' ')) {
  453. list($name, $version) = explode(" ", $pair, 2);
  454. $result[] = array('name' => $name, 'version' => $version);
  455. } else {
  456. $result[] = array('name' => $pair);
  457. }
  458. }
  459. return $result;
  460. }
  461. }