Skip to content

Instantly share code, notes, and snippets.

@sjolsen
Created June 1, 2023 01:43
Show Gist options
  • Save sjolsen/2e32edb4872b5a0528237f090270dc87 to your computer and use it in GitHub Desktop.
Save sjolsen/2e32edb4872b5a0528237f090270dc87 to your computer and use it in GitHub Desktop.
List installed packages that APT can't figure out aren't needed
import apt
import networkx as nx
def is_root(pkg: apt.package.Package) -> bool:
if not pkg.is_installed:
return False
if not pkg.is_auto_installed:
return True
if pkg.essential:
return True
v = pkg.installed
if v.priority in ('required', 'important'):
return True
return False
def main():
c = apt.cache.Cache()
c.open()
installed = set(name for name in c.keys() if c[name].is_installed)
deps = nx.DiGraph()
for name in installed:
pkg = c[name]
if is_root(pkg):
deps.add_edge((), name)
for dep in pkg.installed.get_dependencies('PreDepends', 'Depends', 'Recommends'):
for bdep in dep.or_dependencies:
deps.add_edge(name, bdep.name)
for vname in pkg.installed.provides:
deps.add_edge(vname, name)
needed = set(nx.descendants(deps, ()))
unneeded = installed - needed
for pkg in sorted(unneeded):
print(pkg)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment