VersionParser.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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. // match master-like branches
  90. if (preg_match('{^(?:dev-)?(?:master|trunk|default)$}i', $version)) {
  91. return '9999999-dev';
  92. }
  93. if ('dev-' === strtolower(substr($version, 0, 4))) {
  94. return 'dev-'.substr($version, 4);
  95. }
  96. // match classical versioning
  97. if (preg_match('{^v?(\d{1,3})(\.\d+)?(\.\d+)?(\.\d+)?'.self::$modifierRegex.'$}i', $version, $matches)) {
  98. $version = $matches[1]
  99. .(!empty($matches[2]) ? $matches[2] : '.0')
  100. .(!empty($matches[3]) ? $matches[3] : '.0')
  101. .(!empty($matches[4]) ? $matches[4] : '.0');
  102. $index = 5;
  103. } elseif (preg_match('{^v?(\d{4}(?:[.:-]?\d{2}){1,6}(?:[.:-]?\d{1,3})?)'.self::$modifierRegex.'$}i', $version, $matches)) { // match date-based versioning
  104. $version = preg_replace('{\D}', '-', $matches[1]);
  105. $index = 2;
  106. } elseif (preg_match('{^v?(\d{4,})(\.\d+)?(\.\d+)?(\.\d+)?'.self::$modifierRegex.'$}i', $version, $matches)) {
  107. $version = $matches[1]
  108. .(!empty($matches[2]) ? $matches[2] : '.0')
  109. .(!empty($matches[3]) ? $matches[3] : '.0')
  110. .(!empty($matches[4]) ? $matches[4] : '.0');
  111. $index = 5;
  112. }
  113. // add version modifiers if a version was matched
  114. if (isset($index)) {
  115. if (!empty($matches[$index])) {
  116. if ('stable' === $matches[$index]) {
  117. return $version;
  118. }
  119. $version .= '-' . $this->expandStability($matches[$index]) . (!empty($matches[$index+1]) ? $matches[$index+1] : '');
  120. }
  121. if (!empty($matches[$index+2])) {
  122. $version .= '-dev';
  123. }
  124. return $version;
  125. }
  126. // match dev branches
  127. if (preg_match('{(.*?)[.-]?dev$}i', $version, $match)) {
  128. try {
  129. return $this->normalizeBranch($match[1]);
  130. } catch (\Exception $e) {
  131. }
  132. }
  133. $extraMessage = '';
  134. if (preg_match('{ +as +'.preg_quote($version).'$}', $fullVersion)) {
  135. $extraMessage = ' in "'.$fullVersion.'", the alias must be an exact version';
  136. } elseif (preg_match('{^'.preg_quote($version).' +as +}', $fullVersion)) {
  137. $extraMessage = ' in "'.$fullVersion.'", the alias source must be an exact version, if it is a branch name you should prefix it with dev-';
  138. }
  139. throw new \UnexpectedValueException('Invalid version string "'.$version.'"'.$extraMessage);
  140. }
  141. /**
  142. * Normalizes a branch name to be able to perform comparisons on it
  143. *
  144. * @param string $name
  145. * @return string
  146. */
  147. public function normalizeBranch($name)
  148. {
  149. $name = trim($name);
  150. if (in_array($name, array('master', 'trunk', 'default'))) {
  151. return $this->normalize($name);
  152. }
  153. if (preg_match('#^v?(\d+)(\.(?:\d+|[x*]))?(\.(?:\d+|[x*]))?(\.(?:\d+|[x*]))?$#i', $name, $matches)) {
  154. $version = '';
  155. for ($i = 1; $i < 5; $i++) {
  156. $version .= isset($matches[$i]) ? str_replace('*', 'x', $matches[$i]) : '.x';
  157. }
  158. return str_replace('x', '9999999', $version).'-dev';
  159. }
  160. return 'dev-'.$name;
  161. }
  162. /**
  163. * @param string $source source package name
  164. * @param string $sourceVersion source package version (pretty version ideally)
  165. * @param string $description link description (e.g. requires, replaces, ..)
  166. * @param array $links array of package name => constraint mappings
  167. * @return Link[]
  168. */
  169. public function parseLinks($source, $sourceVersion, $description, $links)
  170. {
  171. $res = array();
  172. foreach ($links as $target => $constraint) {
  173. if ('self.version' === $constraint) {
  174. $parsedConstraint = $this->parseConstraints($sourceVersion);
  175. } else {
  176. $parsedConstraint = $this->parseConstraints($constraint);
  177. }
  178. $res[strtolower($target)] = new Link($source, $target, $parsedConstraint, $description, $constraint);
  179. }
  180. return $res;
  181. }
  182. /**
  183. * Parses as constraint string into LinkConstraint objects
  184. *
  185. * @param string $constraints
  186. * @return \Composer\Package\LinkConstraint\LinkConstraintInterface
  187. */
  188. public function parseConstraints($constraints)
  189. {
  190. $prettyConstraint = $constraints;
  191. if (preg_match('{^([^,\s]*?)@('.implode('|', array_keys(BasePackage::$stabilities)).')$}i', $constraints, $match)) {
  192. $constraints = empty($match[1]) ? '*' : $match[1];
  193. }
  194. if (preg_match('{^(dev-[^,\s@]+?|[^,\s@]+?\.x-dev)#.+$}i', $constraints, $match)) {
  195. $constraints = $match[1];
  196. }
  197. $orConstraints = preg_split('{\s*\|\s*}', trim($constraints));
  198. $orGroups = array();
  199. foreach ($orConstraints as $constraints) {
  200. $andConstraints = preg_split('{(?<!as|[=><])\s*[, ]+\s*(?!as)}', $constraints);
  201. if (count($andConstraints) > 1) {
  202. $constraintObjects = array();
  203. foreach ($andConstraints as $constraint) {
  204. $constraintObjects = array_merge($constraintObjects, $this->parseConstraint($constraint));
  205. }
  206. } else {
  207. $constraintObjects = $this->parseConstraint($andConstraints[0]);
  208. }
  209. if (1 === count($constraintObjects)) {
  210. $constraint = $constraintObjects[0];
  211. } else {
  212. $constraint = new MultiConstraint($constraintObjects);
  213. }
  214. $orGroups[] = $constraint;
  215. }
  216. if (1 === count($orGroups)) {
  217. $constraint = $orGroups[0];
  218. } else {
  219. $constraint = new MultiConstraint($orGroups, false);
  220. }
  221. $constraint->setPrettyString($prettyConstraint);
  222. return $constraint;
  223. }
  224. private function parseConstraint($constraint)
  225. {
  226. if (preg_match('{^([^,\s]+?)@('.implode('|', array_keys(BasePackage::$stabilities)).')$}i', $constraint, $match)) {
  227. $constraint = $match[1];
  228. if ($match[2] !== 'stable') {
  229. $stabilityModifier = $match[2];
  230. }
  231. }
  232. if (preg_match('{^[x*](\.[x*])*$}i', $constraint)) {
  233. return array(new EmptyConstraint);
  234. }
  235. // match tilde constraints
  236. // like wildcard constraints, unsuffixed tilde constraints say that they must be greater than the previous
  237. // version, to ensure that unstable instances of the current version are allowed.
  238. // however, if a stability suffix is added to the constraint, then a >= match on the current version is
  239. // used instead
  240. if (preg_match('{^~>?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:\.(\d+))?'.self::$modifierRegex.'?$}i', $constraint, $matches)) {
  241. if (substr($constraint, 0, 2) === '~>') {
  242. throw new \UnexpectedValueException(
  243. 'Could not parse version constraint '.$constraint.': '.
  244. 'Invalid operator "~>", you probably meant to use the "~" operator'
  245. );
  246. }
  247. // Work out which position in the version we are operating at
  248. if (isset($matches[4]) && '' !== $matches[4]) {
  249. $position = 4;
  250. } elseif (isset($matches[3]) && '' !== $matches[3]) {
  251. $position = 3;
  252. } elseif (isset($matches[2]) && '' !== $matches[2]) {
  253. $position = 2;
  254. } else {
  255. $position = 1;
  256. }
  257. // Calculate the stability suffix
  258. $stabilitySuffix = '';
  259. if (!empty($matches[5])) {
  260. $stabilitySuffix .= '-' . $this->expandStability($matches[5]) . (!empty($matches[6]) ? $matches[6] : '');
  261. }
  262. if (!empty($matches[7])) {
  263. $stabilitySuffix .= '-dev';
  264. }
  265. if (!$stabilitySuffix) {
  266. $stabilitySuffix = "-dev";
  267. }
  268. $lowVersion = $this->manipulateVersionString($matches, $position, 0) . $stabilitySuffix;
  269. $lowerBound = new VersionConstraint('>=', $lowVersion);
  270. // For upper bound, we increment the position of one more significance,
  271. // but highPosition = 0 would be illegal
  272. $highPosition = max(1, $position - 1);
  273. $highVersion = $this->manipulateVersionString($matches, $highPosition, 1) . '-dev';
  274. $upperBound = new VersionConstraint('<', $highVersion);
  275. return array(
  276. $lowerBound,
  277. $upperBound
  278. );
  279. }
  280. // match wildcard constraints
  281. if (preg_match('{^(\d+)(?:\.(\d+))?(?:\.(\d+))?\.[x*]$}', $constraint, $matches)) {
  282. if (isset($matches[3]) && '' !== $matches[3]) {
  283. $position = 3;
  284. } elseif (isset($matches[2]) && '' !== $matches[2]) {
  285. $position = 2;
  286. } else {
  287. $position = 1;
  288. }
  289. $lowVersion = $this->manipulateVersionString($matches, $position) . "-dev";
  290. $highVersion = $this->manipulateVersionString($matches, $position, 1) . "-dev";
  291. if ($lowVersion === "0.0.0.0-dev") {
  292. return array(new VersionConstraint('<', $highVersion));
  293. }
  294. return array(
  295. new VersionConstraint('>=', $lowVersion),
  296. new VersionConstraint('<', $highVersion),
  297. );
  298. }
  299. // match operators constraints
  300. if (preg_match('{^(<>|!=|>=?|<=?|==?)?\s*(.*)}', $constraint, $matches)) {
  301. try {
  302. $version = $this->normalize($matches[2]);
  303. if (!empty($stabilityModifier) && $this->parseStability($version) === 'stable') {
  304. $version .= '-' . $stabilityModifier;
  305. } elseif ('<' === $matches[1]) {
  306. if (!preg_match('/-' . self::$modifierRegex . '$/', strtolower($matches[2]))) {
  307. $version .= '-dev';
  308. }
  309. }
  310. return array(new VersionConstraint($matches[1] ?: '=', $version));
  311. } catch (\Exception $e) {
  312. }
  313. }
  314. $message = 'Could not parse version constraint '.$constraint;
  315. if (isset($e)) {
  316. $message .= ': '. $e->getMessage();
  317. }
  318. throw new \UnexpectedValueException($message);
  319. }
  320. /**
  321. * Increment, decrement, or simply pad a version number.
  322. *
  323. * Support function for {@link parseConstraint()}
  324. *
  325. * @param array $matches Array with version parts in array indexes 1,2,3,4
  326. * @param int $position 1,2,3,4 - which segment of the version to decrement
  327. * @param int $increment
  328. * @param string $pad The string to pad version parts after $position
  329. * @return string The new version
  330. */
  331. private function manipulateVersionString($matches, $position, $increment = 0, $pad = '0')
  332. {
  333. for ($i = 4; $i > 0; $i--) {
  334. if ($i > $position) {
  335. $matches[$i] = $pad;
  336. } elseif ($i == $position && $increment) {
  337. $matches[$i] += $increment;
  338. // If $matches[$i] was 0, carry the decrement
  339. if ($matches[$i] < 0) {
  340. $matches[$i] = $pad;
  341. $position--;
  342. // Return null on a carry overflow
  343. if ($i == 1) {
  344. return;
  345. }
  346. }
  347. }
  348. }
  349. return $matches[1] . '.' . $matches[2] . '.' . $matches[3] . '.' . $matches[4];
  350. }
  351. private function expandStability($stability)
  352. {
  353. $stability = strtolower($stability);
  354. switch ($stability) {
  355. case 'a':
  356. return 'alpha';
  357. case 'b':
  358. return 'beta';
  359. case 'p':
  360. case 'pl':
  361. return 'patch';
  362. case 'rc':
  363. return 'RC';
  364. default:
  365. return $stability;
  366. }
  367. }
  368. /**
  369. * Parses a name/version pairs and returns an array of pairs + the
  370. *
  371. * @param array $pairs a set of package/version pairs separated by ":", "=" or " "
  372. * @return array[] array of arrays containing a name and (if provided) a version
  373. */
  374. public function parseNameVersionPairs(array $pairs)
  375. {
  376. $pairs = array_values($pairs);
  377. $result = array();
  378. for ($i = 0, $count = count($pairs); $i < $count; $i++) {
  379. $pair = preg_replace('{^([^=: ]+)[=: ](.*)$}', '$1 $2', trim($pairs[$i]));
  380. if (false === strpos($pair, ' ') && isset($pairs[$i+1]) && false === strpos($pairs[$i+1], '/')) {
  381. $pair .= ' '.$pairs[$i+1];
  382. $i++;
  383. }
  384. if (strpos($pair, ' ')) {
  385. list($name, $version) = explode(" ", $pair, 2);
  386. $result[] = array('name' => $name, 'version' => $version);
  387. } else {
  388. $result[] = array('name' => $pair);
  389. }
  390. }
  391. return $result;
  392. }
  393. }