-
-
Save tonyskapunk/6e1b4abd491be1424cb03b704c3c9829 to your computer and use it in GitHub Desktop.
LooseVersion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
import apt | |
from json import dumps | |
from distutils.version import LooseVersion | |
def cmp_to_key(mycmp): | |
'Convert a cmp= function into a key= function' | |
class K: | |
def __init__(self, obj, *args): | |
self.obj = obj | |
def __lt__(self, other): | |
return mycmp(self.obj, other.obj) < 0 | |
def __gt__(self, other): | |
return mycmp(self.obj, other.obj) > 0 | |
def __eq__(self, other): | |
return mycmp(self.obj, other.obj) == 0 | |
def __le__(self, other): | |
return mycmp(self.obj, other.obj) <= 0 | |
def __ge__(self, other): | |
return mycmp(self.obj, other.obj) >= 0 | |
def __ne__(self, other): | |
return mycmp(self.obj, other.obj) != 0 | |
return K | |
kernels = {} | |
# Regex for images | |
kernel_image_regex = '^linux-image-.*$' | |
kernel_header_regex = '^linux-(\w+-)?headers-.*$' | |
apt_cache = apt.Cache() | |
# Loop through all the packages | |
for pkg_name in apt_cache.keys(): | |
pkg = apt_cache[pkg_name] | |
# Add to the kernels just installed and those in the kernel section | |
if (pkg.is_installed | |
and ( | |
('kernel' in pkg.section | |
and re.match(kernel_image_regex, pkg_name)) | |
or re.match(kernel_header_regex, pkg_name))): | |
kernels.setdefault(pkg.installed.version, []).append(pkg.name) | |
# Print kernels, unsorted and sorted | |
print('Versions and packages:\n{}'.format(dumps(kernels, indent=4, sort_keys=True))) | |
kernel_versions = list(kernels.copy().keys()) | |
print('Unsorted kernel/headers version:\n {}'.format(kernel_versions)) | |
try: | |
sorted_kernel_list = sorted(kernel_versions, key=LooseVersion) | |
print('Using LooseVersion:\n {}'.format(sorted_kernel_list)) | |
except TypeError: | |
sorted_kernel_list = sorted(kernel_versions, key=cmp_to_key(apt.apt_pkg.version_compare)) | |
print('Using apt.apt_pkg.version:\n {}'.format(sorted_kernel_list)) | |
print('Reversed list using apt:\n {}'.format( | |
sorted(kernel_versions, key=cmp_to_key(apt.apt_pkg.version_compare), reverse=True))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment