oglive-builder/boottools/apt.py

66 lines
1.6 KiB
Python

#!/usr/bin/python3
import apt
import apt.progress.base
import apt_pkg
import shutil
import os
def clean():
apt_cache = apt.Cache()
apt_pkg.init()
cache_dir = apt_pkg.config.find_dir ('Dir::Cache::archives')
for fn in os.listdir (cache_dir):
file_path = os.path.join (cache_dir, fn)
try:
if os.path.isfile (file_path):
os.unlink (file_path)
elif os.path.isdir (file_path):
shutil.rmtree (file_path)
except Exception as e:
print (f'Failed to delete {file_path}. Reason: {e}')
def autoremove():
apt_cache = apt.Cache()
for pkg in apt_cache:
if pkg.is_installed and pkg.is_auto_removable:
pkg.mark_delete()
try:
apt_cache.commit()
except Exception as e:
print ('installation failed: {}'.format (str (e)))
def remove (pkgs):
apt_cache = apt.Cache()
for p in pkgs:
if p in apt_cache:
apt_cache[p].mark_delete()
try:
apt_cache.commit()
except Exception as e:
print ('removal failed: {}'.format (str (e)))
def update():
apt_cache = apt.Cache()
apt_cache.update()
def upgrade():
apt_cache = apt.Cache()
apt_cache.upgrade()
def cache_search (pkgs):
apt_cache = apt.Cache()
res = {}
for p in pkgs:
res[p] = True if p in apt_cache else False
return res
def install (pkgs, opts={}):
opts_list = []
for k in opts: opts_list += ['-o', f'{k}={opts[k]}']
print ('about to install these packages: "{}"'.format (' '.join (pkgs)))
import subprocess
subprocess.run (['apt-get', '--yes', 'install'] + pkgs + opts_list)