Version.pm 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. # Copyright © Colin Watson <cjwatson@debian.org>
  2. # Copyright © Ian Jackson <iwj@debian.org>
  3. # Copyright © 2007 Don Armstrong <don@donarmstrong.com>.
  4. # Copyright © 2009 Raphaël Hertzog <hertzog@debian.org>
  5. #
  6. # This program is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation; either version 2 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. package Dpkg::Version;
  19. use strict;
  20. use warnings;
  21. our $VERSION = '1.01';
  22. use Dpkg::ErrorHandling;
  23. use Dpkg::Gettext;
  24. use Carp;
  25. use Exporter qw(import);
  26. our @EXPORT = qw(version_compare version_compare_relation
  27. version_normalize_relation version_compare_string
  28. version_compare_part version_split_digits version_check
  29. REL_LT REL_LE REL_EQ REL_GE REL_GT);
  30. use constant {
  31. REL_LT => '<<',
  32. REL_LE => '<=',
  33. REL_EQ => '=',
  34. REL_GE => '>=',
  35. REL_GT => '>>',
  36. };
  37. use overload
  38. '<=>' => \&comparison,
  39. 'cmp' => \&comparison,
  40. '""' => sub { return $_[0]->as_string(); },
  41. 'bool' => sub { return $_[0]->as_string() if $_[0]->is_valid(); },
  42. 'fallback' => 1;
  43. =encoding utf8
  44. =head1 NAME
  45. Dpkg::Version - handling and comparing dpkg-style version numbers
  46. =head1 DESCRIPTION
  47. The Dpkg::Version module provides pure-Perl routines to compare
  48. dpkg-style version numbers (as used in Debian packages) and also
  49. an object oriented interface overriding perl operators
  50. to do the right thing when you compare Dpkg::Version object between
  51. them.
  52. =head1 OBJECT INTERFACE
  53. =over 4
  54. =item my $v = Dpkg::Version->new($version, %opts)
  55. Create a new Dpkg::Version object corresponding to the version indicated in
  56. the string (scalar) $version. By default it will accepts any string
  57. and consider it as a valid version. If you pass the option "check => 1",
  58. it will return undef if the version is invalid (see version_check for
  59. details).
  60. You can always call $v->is_valid() later on to verify that the version is
  61. valid.
  62. =cut
  63. sub new {
  64. my ($this, $ver, %opts) = @_;
  65. my $class = ref($this) || $this;
  66. $ver = "$ver" if ref($ver); # Try to stringify objects
  67. if ($opts{check}) {
  68. return unless version_check($ver);
  69. }
  70. my $self = {};
  71. if ($ver =~ /^([^:]*):(.+)$/) {
  72. $self->{epoch} = $1;
  73. $ver = $2;
  74. } else {
  75. $self->{epoch} = 0;
  76. $self->{no_epoch} = 1;
  77. }
  78. if ($ver =~ /(.*)-(.*)$/) {
  79. $self->{version} = $1;
  80. $self->{revision} = $2;
  81. } else {
  82. $self->{version} = $ver;
  83. $self->{revision} = 0;
  84. $self->{no_revision} = 1;
  85. }
  86. return bless $self, $class;
  87. }
  88. =item boolean evaluation
  89. When the Dpkg::Version object is used in a boolean evaluation (for example
  90. in "if ($v)" or "$v || 'default'") it returns its string representation
  91. if the version stored is valid ($v->is_valid()) and undef otherwise.
  92. =item $v->is_valid()
  93. Returns true if the version is valid, false otherwise.
  94. =cut
  95. sub is_valid {
  96. my ($self) = @_;
  97. return scalar version_check($self);
  98. }
  99. =item $v->epoch(), $v->version(), $v->revision()
  100. Returns the corresponding part of the full version string.
  101. =cut
  102. sub epoch {
  103. my $self = shift;
  104. return $self->{epoch};
  105. }
  106. sub version {
  107. my $self = shift;
  108. return $self->{version};
  109. }
  110. sub revision {
  111. my $self = shift;
  112. return $self->{revision};
  113. }
  114. =item $v->is_native()
  115. Returns true if the version is native, false if it has a revision.
  116. =cut
  117. sub is_native {
  118. my $self = shift;
  119. return $self->{no_revision};
  120. }
  121. =item $v1 <=> $v2, $v1 < $v2, $v1 <= $v2, $v1 > $v2, $v1 >= $v2
  122. Numerical comparison of various versions numbers. One of the two operands
  123. needs to be a Dpkg::Version, the other one can be anything provided that
  124. its string representation is a version number.
  125. =cut
  126. sub comparison {
  127. my ($a, $b, $inverted) = @_;
  128. if (not ref($b) or not $b->isa('Dpkg::Version')) {
  129. $b = Dpkg::Version->new($b);
  130. }
  131. ($a, $b) = ($b, $a) if $inverted;
  132. my $r = version_compare_part($a->epoch(), $b->epoch());
  133. return $r if $r;
  134. $r = version_compare_part($a->version(), $b->version());
  135. return $r if $r;
  136. return version_compare_part($a->revision(), $b->revision());
  137. }
  138. =item "$v", $v->as_string(), $v->as_string(%options)
  139. Accepts an optional option hash reference, affecting the string conversion.
  140. Options:
  141. =over 8
  142. =item omit_epoch (defaults to 0)
  143. Omit the epoch, if present, in the output string.
  144. =item omit_revision (defaults to 0)
  145. Omit the revision, if present, in the output string.
  146. =back
  147. Returns the string representation of the version number.
  148. =cut
  149. sub as_string {
  150. my ($self, %opts) = @_;
  151. my $no_epoch = $opts{omit_epoch} || $self->{no_epoch};
  152. my $no_revision = $opts{omit_revision} || $self->{no_revision};
  153. my $str = '';
  154. $str .= $self->{epoch} . ':' unless $no_epoch;
  155. $str .= $self->{version};
  156. $str .= '-' . $self->{revision} unless $no_revision;
  157. return $str;
  158. }
  159. =back
  160. =head1 FUNCTIONS
  161. All the functions are exported by default.
  162. =over 4
  163. =item version_compare($a, $b)
  164. Returns -1 if $a is earlier than $b, 0 if they are equal and 1 if $a
  165. is later than $b.
  166. If $a or $b are not valid version numbers, it dies with an error.
  167. =cut
  168. sub version_compare($$) {
  169. my ($a, $b) = @_;
  170. my $va = Dpkg::Version->new($a, check => 1);
  171. defined($va) || error(_g('%s is not a valid version'), "$a");
  172. my $vb = Dpkg::Version->new($b, check => 1);
  173. defined($vb) || error(_g('%s is not a valid version'), "$b");
  174. return $va <=> $vb;
  175. }
  176. =item version_compare_relation($a, $rel, $b)
  177. Returns the result (0 or 1) of the given comparison operation. This
  178. function is implemented on top of version_compare().
  179. Allowed values for $rel are the exported constants REL_GT, REL_GE,
  180. REL_EQ, REL_LE, REL_LT. Use version_normalize_relation() if you
  181. have an input string containing the operator.
  182. =cut
  183. sub version_compare_relation($$$) {
  184. my ($a, $op, $b) = @_;
  185. my $res = version_compare($a, $b);
  186. if ($op eq REL_GT) {
  187. return $res > 0;
  188. } elsif ($op eq REL_GE) {
  189. return $res >= 0;
  190. } elsif ($op eq REL_EQ) {
  191. return $res == 0;
  192. } elsif ($op eq REL_LE) {
  193. return $res <= 0;
  194. } elsif ($op eq REL_LT) {
  195. return $res < 0;
  196. } else {
  197. croak "unsupported relation for version_compare_relation(): '$op'";
  198. }
  199. }
  200. =item my $rel = version_normalize_relation($rel_string)
  201. Returns the normalized constant of the relation $rel (a value
  202. among REL_GT, REL_GE, REL_EQ, REL_LE and REL_LT). Supported
  203. relations names in input are: "gt", "ge", "eq", "le", "lt", ">>", ">=",
  204. "=", "<=", "<<". ">" and "<" are also supported but should not be used as
  205. they are obsolete aliases of ">=" and "<=".
  206. =cut
  207. sub version_normalize_relation($) {
  208. my $op = shift;
  209. warning('relation %s is deprecated: use %s or %s',
  210. $op, "$op$op", "$op=") if ($op eq '>' or $op eq '<');
  211. if ($op eq '>>' or $op eq 'gt') {
  212. return REL_GT;
  213. } elsif ($op eq '>=' or $op eq 'ge' or $op eq '>') {
  214. return REL_GE;
  215. } elsif ($op eq '=' or $op eq 'eq') {
  216. return REL_EQ;
  217. } elsif ($op eq '<=' or $op eq 'le' or $op eq '<') {
  218. return REL_LE;
  219. } elsif ($op eq '<<' or $op eq 'lt') {
  220. return REL_LT;
  221. } else {
  222. croak "bad relation '$op'";
  223. }
  224. }
  225. =item version_compare_string($a, $b)
  226. String comparison function used for comparing non-numerical parts of version
  227. numbers. Returns -1 if $a is earlier than $b, 0 if they are equal and 1 if $a
  228. is later than $b.
  229. The "~" character always sort lower than anything else. Digits sort lower
  230. than non-digits. Among remaining characters alphabetic characters (A-Za-z)
  231. sort lower than the other ones. Within each range, the ASCII decimal value
  232. of the character is used to sort between characters.
  233. =cut
  234. sub _version_order {
  235. my ($x) = @_;
  236. if ($x eq '~') {
  237. return -1;
  238. } elsif ($x =~ /^\d$/) {
  239. return $x * 1 + 1;
  240. } elsif ($x =~ /^[A-Za-z]$/) {
  241. return ord($x);
  242. } else {
  243. return ord($x) + 256;
  244. }
  245. }
  246. sub version_compare_string($$) {
  247. my @a = map { _version_order($_) } split(//, shift);
  248. my @b = map { _version_order($_) } split(//, shift);
  249. while (1) {
  250. my ($a, $b) = (shift @a, shift @b);
  251. return 0 if not defined($a) and not defined($b);
  252. $a ||= 0; # Default order for "no character"
  253. $b ||= 0;
  254. return 1 if $a > $b;
  255. return -1 if $a < $b;
  256. }
  257. }
  258. =item version_compare_part($a, $b)
  259. Compare two corresponding sub-parts of a version number (either upstream
  260. version or debian revision).
  261. Each parameter is split by version_split_digits() and resulting items
  262. are compared together. As soon as a difference happens, it returns -1 if
  263. $a is earlier than $b, 0 if they are equal and 1 if $a is later than $b.
  264. =cut
  265. sub version_compare_part($$) {
  266. my @a = version_split_digits(shift);
  267. my @b = version_split_digits(shift);
  268. while (1) {
  269. my ($a, $b) = (shift @a, shift @b);
  270. return 0 if not defined($a) and not defined($b);
  271. $a ||= 0; # Default value for lack of version
  272. $b ||= 0;
  273. if ($a =~ /^\d+$/ and $b =~ /^\d+$/) {
  274. # Numerical comparison
  275. my $cmp = $a <=> $b;
  276. return $cmp if $cmp;
  277. } else {
  278. # String comparison
  279. my $cmp = version_compare_string($a, $b);
  280. return $cmp if $cmp;
  281. }
  282. }
  283. }
  284. =item my @items = version_split_digits($version)
  285. Splits a string in items that are each entirely composed either
  286. of digits or of non-digits. For instance for "1.024~beta1+svn234" it would
  287. return ("1", ".", "024", "~beta", "1", "+svn", "234").
  288. =cut
  289. sub version_split_digits($) {
  290. return split(/(?<=\d)(?=\D)|(?<=\D)(?=\d)/, $_[0]);
  291. }
  292. =item my ($ok, $msg) = version_check($version)
  293. =item my $ok = version_check($version)
  294. Checks the validity of $version as a version number. Returns 1 in $ok
  295. if the version is valid, 0 otherwise. In the latter case, $msg
  296. contains a description of the problem with the $version scalar.
  297. =cut
  298. sub version_check($) {
  299. my $version = shift;
  300. my $str;
  301. if (defined $version) {
  302. $str = "$version";
  303. $version = Dpkg::Version->new($str) unless ref($version);
  304. }
  305. if (not defined($str) or not length($str)) {
  306. my $msg = _g('version number cannot be empty');
  307. return (0, $msg) if wantarray;
  308. return 0;
  309. }
  310. if ($version->version() =~ m/^[^\d]/) {
  311. my $msg = _g('version number does not start with digit');
  312. return (0, $msg) if wantarray;
  313. return 0;
  314. }
  315. if ($str =~ m/([^-+:.0-9a-zA-Z~])/o) {
  316. my $msg = sprintf(_g("version number contains illegal character `%s'"), $1);
  317. return (0, $msg) if wantarray;
  318. return 0;
  319. }
  320. if ($version->epoch() !~ /^\d*$/) {
  321. my $msg = sprintf(_g('epoch part of the version number ' .
  322. "is not a number: '%s'"), $version->epoch());
  323. return (0, $msg) if wantarray;
  324. return 0;
  325. }
  326. return (1, '') if wantarray;
  327. return 1;
  328. }
  329. =back
  330. =head1 CHANGES
  331. =head2 Version 1.01
  332. New argument: Accept an options argument in $v->as_string().
  333. New method: $v->is_native().
  334. =head1 AUTHOR
  335. Don Armstrong <don@donarmstrong.com>, Colin Watson
  336. <cjwatson@debian.org> and Raphaël Hertzog <hertzog@debian.org>, based on
  337. the implementation in F<dpkg/lib/version.c> by Ian Jackson and others.
  338. =cut
  339. 1;