2008-03-06

Sorting package version strings

Interesting less trivial than expected problem (solved): sorting package version numbers:

import re
import rpm

def get_package_version(name):
    """Return version string of installed package."""

    # note: ts can take an argument that is the root of the installation
    #       typically with a var/lib/rpm directory underneath it.
    transaction_set = rpm.ts()

    versions = [header['provideversion'][0]
                for header in transaction_set.dbMatch('name', name)]
    versions.sort(cmp_versions)
    return versions

def version2sortable(version):

    parts = re.split(r'(\d+)', version)
    fields = []
    for part in parts:
        try:
            part = int(part)
        except ValueError:
            pass
        fields.append(part)
    return tuple(fields)

def cmp_versions(a, b):

    return cmp(version2sortable(a), version2sortable(b))

if __name__ == '__main__':
    print get_package_version('kernel')

Output:

['2.6.23.8-63.fc8', '2.6.23.9-85.fc8', '2.6.23.14-107.fc8', '2.6.23.14-115.fc8', '2.6.23.15-137.fc8']

Note: WordPress is screwing up the markup on the code blocks above. If you have any tips on how to fix this please drop me a line.
Update: Using pre/blockquote hack for now and will try out a code highlighter plug-in when I get the chance. Thanks Tim and Lindsay! :-)

Filed under: fedora,Python — twegener @ 22:04

3 Comments »

  1. Tim,

    Try:

    http://wordpress.org/extend/plugins/wp-codebox/

    Comment by timsamoff — 2008-03-07 @ 2:30

  2. I recommend putting your code fragments in a

    . Makes it a lot easier to style your code differently to the rest of the content on your site.

    Syntax highlighting is a bit more difficult, but there are a bunch of WordPress plugins out there that can help you.

    Comment by Lindsay Holmwood — 2008-03-07 @ 6:46

  3. Hah, ok, that didn’t work. What I was trying to say was put them in a <blockquote><pre> combo.

    Comment by Lindsay Holmwood — 2008-03-07 @ 6:48

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress

-->