# Copyright (c) 2009 ActiveState Software Inc.
# See http://www.activestate.com/activepython/license/ for licensing
# information.

import pkg_resources


def compare_release_version(pkg1, pkg2):
    """Compare two packages based on their release version on PyPI
    """
    # Currently we use setuptools version parser to compare versions
    # In future, PyPM should slowly migrate towards RationalVersion:
    # http://wiki.python.org/moin/Distutils/VersionComparison
    return cmp(pkg_resources.parse_version(pkg1.version),
               pkg_resources.parse_version(pkg2.version))
    

def compare_version(pkg1, pkg2):
    """Compare two packages based on the PyPM version
    """
    if pkg1.name != pkg2.name:
        raise ValueError, "Can compare only packages with *same* name."

    # First compare release version
    diff = compare_release_version(pkg1, pkg2)
    if diff == 0:
        return cmp(int(pkg1.pkg_version),
                   int(pkg2.pkg_version))
    else:
        return diff

def sort_packages_by_version(packages):
    """Sort packages in reverse version order (latest comes first)
    """
    def reverse_cmp(f):
        return lambda x,y: -1 * f(x,y)

    packages.sort(cmp=reverse_cmp(compare_version))
    
