Blame SOURCES/rpmsort

7b79ae
#! /usr/bin/perl -w
7b79ae
7b79ae
# This program is free software; you can redistribute it and/or
7b79ae
# modify it under the terms of the GNU General Public License
7b79ae
# as published by the Free Software Foundation; either version 2
7b79ae
# of the License, or (at your option) any later version.
7b79ae
#
7b79ae
# This program is distributed in the hope that it will be useful,
7b79ae
# but WITHOUT ANY WARRANTY; without even the implied warranty of
7b79ae
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
7b79ae
# GNU General Public License for more details.
7b79ae
#
7b79ae
# You should have received a copy of the GNU General Public License
7b79ae
# along with this program; if not, write to the Free Software
7b79ae
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,
7b79ae
# USA.
7b79ae
7b79ae
use Getopt::Long qw(:config gnu_getopt);
7b79ae
7b79ae
sub rpm_cmp_versions {
7b79ae
    my ($evr1, $evr2) = @_;
7b79ae
7b79ae
    sub _rpm_cmp {
7b79ae
	my ($s1, $s2) = @_;
7b79ae
7b79ae
	return defined $s1 <=> defined $s2
7b79ae
	    unless defined $s1 && defined $s2;
7b79ae
7b79ae
	my ($r, $x1, $x2);
7b79ae
	do {
7b79ae
	    $s1 =~ s/^[^a-zA-Z0-9]+//;
7b79ae
	    $s2 =~ s/^[^a-zA-Z0-9]+//;
7b79ae
	    if ($s1 =~ /^\d/ || $s2 =~ /^\d/) {
7b79ae
		$s1 =~ s/^0*(\d*)//;  $x1 = $1;
7b79ae
		$s2 =~ s/^0*(\d*)//;  $x2 = $1;
7b79ae
		$r = length $x1 <=> length $x2 || $x1 cmp $x2;
7b79ae
	    } else {
7b79ae
		$s1 =~ s/^([a-zA-Z]*)//;  $x1 = $1;
7b79ae
		$s2 =~ s/^([a-zA-Z]*)//;  $x2 = $1;
7b79ae
		return 0
7b79ae
		    if $x1 eq '' && $x2 eq '';
7b79ae
		$r = $x1 cmp $x2;
7b79ae
	    }
7b79ae
	} until $r;
7b79ae
	return $r;
7b79ae
    }
7b79ae
7b79ae
    my ($e1, $v1, $r1) = $evr1 =~ /^(?:(\d*):)?(.*?)(?:-([^-]*))?$/;
7b79ae
    my ($e2, $v2, $r2) = $evr2 =~ /^(?:(\d*):)?(.*?)(?:-([^-]*))?$/;
7b79ae
    my $r = _rpm_cmp($e1 || 0, $e2 || 0);
7b79ae
    $r = _rpm_cmp($v1, $v2)
7b79ae
	unless $r;
7b79ae
    $r = _rpm_cmp($r1, $r2)
7b79ae
	unless $r;
7b79ae
    return $r;
7b79ae
}
7b79ae
7b79ae
my $reorder = sub { return @_ };
7b79ae
my $key = 0;
7b79ae
7b79ae
GetOptions ("r|reverse"	    => sub { $reorder = sub { return reverse @_ } },
7b79ae
	    "k|key=i"	    => \$key)
7b79ae
or do {
7b79ae
    print STDERR "Usage\n";
7b79ae
    exit 1;
7b79ae
};
7b79ae
7b79ae
if ($key == 0) {
7b79ae
    # Sort by entire lines
7b79ae
    map { print } &$reorder(sort { rpm_cmp_versions($a, $b) } <>);
7b79ae
} else {
7b79ae
    # Sort by field $key
7b79ae
    my @data = map { [(split)[$key-1], $_] } <>;
7b79ae
    map { print } &$reorder(map { $_->[1] }
7b79ae
        sort { rpm_cmp_versions($a->[0], $b->[0]) } @data);
7b79ae
}