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)]
    return versions

def version2sortable(version):

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

def cmp_versions(a, b):

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

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


['', '', '', '', '']

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
Powered by WordPress