Problem solving, python rocks

So I was helping one Canola2 user to uninstall the old version and for some strange reason apt-get remove libeet0 libevas0 libecore0 libembryo0 libdownloadmanager0 was breaking with "Abort" message. Ok, use dpkg instead, I said, but since we now have split packages for all the libs we use, you'll end with a dependency nightmare.

Solution? Hack a quick script to get dpkg errors, parse them and generate a new command line with proper ordering:

#!/usr/bin/python

import sys

pkgs = {}

infile = open(sys.argv[1])
pkg = None
for line in infile:
    line = line[:-1] # chomp n
    tokens = line.split()
    head = tokens[0]
    if head == "dpkg:":
        if tokens[1] != "dependency":
            continue
        pkg = tokens[-1][:-1]
        pkgs.setdefault(pkg, set())
    elif head in ("Package", "dpkg", "dependency"):
        continue
    elif head == "Errors":
        break # follows a list of problematic packages
    else:
        if tokens[1:3] == ['depends', 'on']:
            pkgs[pkg].add(head)

def unique_extend(lst, extent):
    for e in extent:
        if e not in lst:
            lst.append(e)

def rm_pkg(p, pkgs):
    rm_list = []
    try:
        ddeps = pkgs[p]
    except KeyError:
        return [] # no deps!

    for d in ddeps:
        unique_extend(rm_list, rm_pkg(d, pkgs) + [d])
    return rm_list

rm_list = []
for p in pkgs:
    unique_extend(rm_list, rm_pkg(p, pkgs) + [p])

print "dpkg --purge", " ".join(rm_list)

Not that efficient, but simple enough.