Skip to content

Instantly share code, notes, and snippets.

@yuryshulaev
Last active November 6, 2021 16:20
Show Gist options
  • Save yuryshulaev/328eca092960f31db345897e71d77ae2 to your computer and use it in GitHub Desktop.
Save yuryshulaev/328eca092960f31db345897e71d77ae2 to your computer and use it in GitHub Desktop.
Alpine Linux: List installed apk packages sorted by size
#!/usr/bin/env python3
import subprocess
UNITS = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB']
def human_readable_size_to_bytes(size_str):
size, unit = size_line.split()
return int(size) * (1 << (UNITS.index(unit) * 10))
def chunks(lst, n):
for i in range(0, len(lst), n):
yield lst[i:i + n]
installed = dict(line.split(' - ', 1) for line in subprocess.check_output(['apk', 'info', '-vv'], text=True).splitlines())
lines = subprocess.check_output(['apk', 'info', '--size', '*'], text=True).splitlines()
package_sizes = {}
for name_line, size_line, _ in chunks(lines, 3):
name = name_line.split(maxsplit=1)[0]
if name not in installed or name in package_sizes:
continue
package_sizes[name] = human_readable_size_to_bytes(size_line)
total = 0
for name, size in sorted(package_sizes.items(), key=lambda item: item[1]):
print(f'{size:,}', name, '-', installed[name])
total += size
print(f'{total:,}', '(total)')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment