VersionParser.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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. * Normalizes a branch name to be able to perform comparisons on it
  147. *
  148. * @param string $name
  149. * @return string
  150. */
  151. public function normalizeBranch($name)
  152. {
  153. $name = trim($name);
  154. if (in_array($name, array('master', 'trunk', 'default'))) {
  155. return $this->normalize($name);
  156. }
  157. if (preg_match('#^v?(\d+)(\.(?:\d+|[xX*]))?(\.(?:\d+|[xX*]))?(\.(?:\d+|[xX*]))?$#i', $name, $matches)) {
  158. $version = '';
  159. for ($i = 1; $i < 5; $i++) {
  160. $version .= isset($matches[$i]) ? str_replace(array('*', 'X'), 'x', $matches[$i]) : '.x';
  161. }
  162. return str_replace('x', '9999999', $version).'-dev';
  163. }
  164. return 'dev-'.$name;
  165. }
  166. /**
  167. * @param string $source source package name
  168. * @param string $sourceVersion source package version (pretty version ideally)
  169. * @param string $description link description (e.g. requires, replaces, ..)
  170. * @param array $links array of package name => constraint mappings
  171. * @return Link[]
  172. */
  173. public function parseLinks($source, $sourceVersion, $description, $links)
  174. {
  175. $res = array();
  176. foreach ($links as $target => $constraint) {
  177. if ('self.version' === $constraint) {
  178. $parsedConstraint = $this->parseConstraints($sourceVersion);
  179. } else {
  180. $parsedConstraint = $this->parseConstraints($constraint);
  181. }
  182. $res[strtolower($target)] = new Link($source, $target, $parsedConstraint, $description, $constraint);
  183. }
  184. return $res;
  185. }
  186. /**
  187. * Parses as constraint string into LinkConstraint objects
  188. *
  189. * @param string $constraints
  190. * @return \Composer\Package\LinkConstraint\LinkConstraintInterface
  191. */
  192. public function parseConstraints($constraints)
  193. {
  194. $prettyConstraint = $constraints;
  195. if (preg_match('{^([^,\s]*?)@('.implode('|', array_keys(BasePackage::$stabilities)).')$}i', $constraints, $match)) {
  196. $constraints = empty($match[1]) ? '*' : $match[1];
  197. }
  198. if (preg_match('{^(dev-[^,\s@]+?|[^,\s@]+?\.x-dev)#.+$}i', $constraints, $match)) {
  199. $constraints = $match[1];
  200. }
  201. $orConstraints = preg_split('{\s*\|\|?\s*}', trim($constraints));
  202. $orGroups = array();
  203. foreach ($orConstraints as $constraints) {
  204. $andConstraints = preg_split('{(?<!^|as|[=>< ,]) *(?<!-)[, ](?!-) *(?!,|as|$)}', $constraints);
  205. if (count($andConstraints) > 1) {
  206. $constraintObjects = array();
  207. foreach ($andConstraints as $constraint) {
  208. $constraintObjects = array_merge($constraintObjects, $this->parseConstraint($constraint));
  209. }
  210. } else {
  211. $constraintObjects = $this->parseConstraint($andConstraints[0]);
  212. }
  213. if (1 === count($constraintObjects)) {
  214. $constraint = $constraintObjects[0];
  215. } else {
  216. $constraint = new MultiConstraint($constraintObjects);
  217. }
  218. $orGroups[] = $constraint;
  219. }
  220. if (1 === count($orGroups)) {
  221. $constraint = $orGroups[0];
  222. } else {
  223. $constraint = new MultiConstraint($orGroups, false);
  224. }
  225. $constraint->setPrettyString($prettyConstraint);
  226. return $constraint;
  227. }
  228. private function parseConstraint($constraint)
  229. {
  230. if (preg_match('{^([^,\s]+?)@('.implode('|', array_keys(BasePackage::$stabilities)).')$}i', $constraint, $match)) {
  231. $constraint = $match[1];
  232. if ($match[2] !== 'stable') {
  233. $stabilityModifier = $match[2];
  234. }
  235. }
  236. if (preg_match('{^[xX*](\.[xX*])*$}i', $constraint)) {
  237. return array(new EmptyConstraint);
  238. }
  239. $versionRegex = '(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:\.(\d+))?'.self::$modifierRegex;
  240. // match tilde constraints
  241. // like wildcard constraints, unsuffixed tilde constraints say that they must be greater than the previous
  242. // version, to ensure that unstable instances of the current version are allowed.
  243. // however, if a stability suffix is added to the constraint, then a >= match on the current version is
  244. // used instead
  245. if (preg_match('{^~>?'.$versionRegex.'$}i', $constraint, $matches)) {
  246. if (substr($constraint, 0, 2) === '~>') {
  247. throw new \UnexpectedValueException(
  248. 'Could not parse version constraint '.$constraint.': '.
  249. 'Invalid operator "~>", you probably meant to use the "~" operator'
  250. );
  251. }
  252. // Work out which position in the version we are operating at
  253. if (isset($matches[4]) && '' !== $matches[4]) {
  254. $position = 4;
  255. } elseif (isset($matches[3]) && '' !== $matches[3]) {
  256. $position = 3;
  257. } elseif (isset($matches[2]) && '' !== $matches[2]) {
  258. $position = 2;
  259. } else {
  260. $position = 1;
  261. }
  262. // Calculate the stability suffix
  263. $stabilitySuffix = '';
  264. if (!empty($matches[5])) {
  265. $stabilitySuffix .= '-' . $this->expandStability($matches[5]) . (!empty($matches[6]) ? $matches[6] : '');
  266. }
  267. if (!empty($matches[7])) {
  268. $stabilitySuffix .= '-dev';
  269. }
  270. if (!$stabilitySuffix) {
  271. $stabilitySuffix = "-dev";
  272. }
  273. $lowVersion = $this->manipulateVersionString($matches, $position, 0) . $stabilitySuffix;
  274. $lowerBound = new VersionConstraint('>=', $lowVersion);
  275. // For upper bound, we increment the position of one more significance,
  276. // but highPosition = 0 would be illegal
  277. $highPosition = max(1, $position - 1);
  278. $highVersion = $this->manipulateVersionString($matches, $highPosition, 1) . '-dev';
  279. $upperBound = new VersionConstraint('<', $highVersion);
  280. return array(
  281. $lowerBound,
  282. $upperBound
  283. );
  284. }
  285. // match caret constraints
  286. if (preg_match('{^\^'.$versionRegex.'($)}i', $constraint, $matches)) {
  287. // Work out which position in the version we are operating at
  288. if ('0' !== $matches[1] || '' === $matches[2]) {
  289. $position = 1;
  290. } elseif ('0' !== $matches[2] || '' === $matches[3]) {
  291. $position = 2;
  292. } else {
  293. $position = 3;
  294. }
  295. // Calculate the stability suffix
  296. $stabilitySuffix = '';
  297. if (empty($matches[5]) && empty($matches[7])) {
  298. $stabilitySuffix .= '-dev';
  299. }
  300. $lowVersion = $this->normalize(substr($constraint . $stabilitySuffix, 1));
  301. $lowerBound = new VersionConstraint('>=', $lowVersion);
  302. // For upper bound, we increment the position of one more significance,
  303. // but highPosition = 0 would be illegal
  304. $highVersion = $this->manipulateVersionString($matches, $position, 1) . '-dev';
  305. $upperBound = new VersionConstraint('<', $highVersion);
  306. return array(
  307. $lowerBound,
  308. $upperBound
  309. );
  310. }
  311. // match wildcard constraints
  312. if (preg_match('{^(\d+)(?:\.(\d+))?(?:\.(\d+))?\.[xX*]$}', $constraint, $matches)) {
  313. if (isset($matches[3]) && '' !== $matches[3]) {
  314. $position = 3;
  315. } elseif (isset($matches[2]) && '' !== $matches[2]) {
  316. $position = 2;
  317. } else {
  318. $position = 1;
  319. }
  320. $lowVersion = $this->manipulateVersionString($matches, $position) . "-dev";
  321. $highVersion = $this->manipulateVersionString($matches, $position, 1) . "-dev";
  322. if ($lowVersion === "0.0.0.0-dev") {
  323. return array(new VersionConstraint('<', $highVersion));
  324. }
  325. return array(
  326. new VersionConstraint('>=', $lowVersion),
  327. new VersionConstraint('<', $highVersion),
  328. );
  329. }
  330. // match hyphen constraints
  331. if (preg_match('{^(?P<from>'.$versionRegex.') +- +(?P<to>'.$versionRegex.')($)}i', $constraint, $matches)) {
  332. // Calculate the stability suffix
  333. $lowStabilitySuffix = '';
  334. if (empty($matches[6]) && empty($matches[8])) {
  335. $lowStabilitySuffix = '-dev';
  336. }
  337. $lowVersion = $this->normalize($matches['from']);
  338. $lowerBound = new VersionConstraint('>=', $lowVersion . $lowStabilitySuffix);
  339. $highVersion = $matches[10];
  340. if ((!empty($matches[11]) && !empty($matches[12])) || !empty($matches[14]) || !empty($matches[16])) {
  341. $highVersion = $this->normalize($matches['to']);
  342. $upperBound = new VersionConstraint('<=', $highVersion);
  343. } else {
  344. $highMatch = array('', $matches[10], $matches[11], $matches[12], $matches[13]);
  345. $highVersion = $this->manipulateVersionString($highMatch, empty($matches[11]) ? 1 : 2, 1) . '-dev';
  346. $upperBound = new VersionConstraint('<', $highVersion);
  347. }
  348. return array(
  349. $lowerBound,
  350. $upperBound
  351. );
  352. }
  353. // match operators constraints
  354. if (preg_match('{^(<>|!=|>=?|<=?|==?)?\s*(.*)}', $constraint, $matches)) {
  355. try {
  356. $version = $this->normalize($matches[2]);
  357. if (!empty($stabilityModifier) && $this->parseStability($version) === 'stable') {
  358. $version .= '-' . $stabilityModifier;
  359. } elseif ('<' === $matches[1]) {
  360. if (!preg_match('/-' . self::$modifierRegex . '$/', strtolower($matches[2]))) {
  361. $version .= '-dev';
  362. }
  363. }
  364. return array(new VersionConstraint($matches[1] ?: '=', $version));
  365. } catch (\Exception $e) {
  366. }
  367. }
  368. $message = 'Could not parse version constraint '.$constraint;
  369. if (isset($e)) {
  370. $message .= ': '. $e->getMessage();
  371. }
  372. throw new \UnexpectedValueException($message);
  373. }
  374. /**
  375. * Increment, decrement, or simply pad a version number.
  376. *
  377. * Support function for {@link parseConstraint()}
  378. *
  379. * @param array $matches Array with version parts in array indexes 1,2,3,4
  380. * @param int $position 1,2,3,4 - which segment of the version to decrement
  381. * @param int $increment
  382. * @param string $pad The string to pad version parts after $position
  383. * @return string The new version
  384. */
  385. private function manipulateVersionString($matches, $position, $increment = 0, $pad = '0')
  386. {
  387. for ($i = 4; $i > 0; $i--) {
  388. if ($i > $position) {
  389. $matches[$i] = $pad;
  390. } elseif ($i == $position && $increment) {
  391. $matches[$i] += $increment;
  392. // If $matches[$i] was 0, carry the decrement
  393. if ($matches[$i] < 0) {
  394. $matches[$i] = $pad;
  395. $position--;
  396. // Return null on a carry overflow
  397. if ($i == 1) {
  398. return;
  399. }
  400. }
  401. }
  402. }
  403. return $matches[1] . '.' . $matches[2] . '.' . $matches[3] . '.' . $matches[4];
  404. }
  405. private function expandStability($stability)
  406. {
  407. $stability = strtolower($stability);
  408. switch ($stability) {
  409. case 'a':
  410. return 'alpha';
  411. case 'b':
  412. return 'beta';
  413. case 'p':
  414. case 'pl':
  415. return 'patch';
  416. case 'rc':
  417. return 'RC';
  418. default:
  419. return $stability;
  420. }
  421. }
  422. /**
  423. * Parses a name/version pairs and returns an array of pairs + the
  424. *
  425. * @param array $pairs a set of package/version pairs separated by ":", "=" or " "
  426. * @return array[] array of arrays containing a name and (if provided) a version
  427. */
  428. public function parseNameVersionPairs(array $pairs)
  429. {
  430. $pairs = array_values($pairs);
  431. $result = array();
  432. for ($i = 0, $count = count($pairs); $i < $count; $i++) {
  433. $pair = preg_replace('{^([^=: ]+)[=: ](.*)$}', '$1 $2', trim($pairs[$i]));
  434. if (false === strpos($pair, ' ') && isset($pairs[$i+1]) && false === strpos($pairs[$i+1], '/')) {
  435. $pair .= ' '.$pairs[$i+1];
  436. $i++;
  437. }
  438. if (strpos($pair, ' ')) {
  439. list($name, $version) = explode(" ", $pair, 2);
  440. $result[] = array('name' => $name, 'version' => $version);
  441. } else {
  442. $result[] = array('name' => $pair);
  443. }
  444. }
  445. return $result;
  446. }
  447. }