Skip to content

Instantly share code, notes, and snippets.

@hashemi
Created December 23, 2015 18:09
Show Gist options
  • Save hashemi/48bb448e19909e568625 to your computer and use it in GitHub Desktop.
Save hashemi/48bb448e19909e568625 to your computer and use it in GitHub Desktop.
# This python script uninstalls packages
# installed using the OS X .pkg format.
#
# Run the script, passing the name of the
# pkg as the first command line argument.
#
# Depends on send2trash:
# $ pip install send2trash
#
# (c) Ahmad Alhashemi, 2015
from os.path import *
from os import listdir
from send2trash import send2trash as trash
from subprocess import run, PIPE
from sys import argv
try:
package_name = argv[1]
except:
exit('Usage: {} [PACKAGE NAME]'.format(argv[0]))
pkgutil_run = run(['pkgutil', '--files', package_name], stdout=PIPE, universal_newlines=True)
try:
pkgutil_run.check_returncode()
except:
exit('Exit: pkgutil error')
links = []
files = []
dirs = []
for filename in pkgutil_run.stdout.split():
filename = abspath(join('/', filename.strip()))
if islink(filename):
links.append(filename)
elif isdir(filename):
dirs.append(filename)
elif isfile(filename):
files.append(filename)
trashed_files = []
untrashed_files = []
for filename in files:
print('Trashing file {}'.format(filename))
try:
trash(filename)
trashed_files.append(filename)
except:
untrashed_files.append(filename)
nonempty_dirs = []
trashed_dirs = []
untrashed_dirs = []
for dirname in dirs:
if len(listdir(dirname)) == 0:
print('Trashing empty directory {}')
try:
trash(dirname)
trashed_dirs.append(dirname)
except:
untrashed_dirs.append(dirname)
else:
nonempty_dirs.append(dirname)
def display_failures(failures, summary):
failure_count = len(failures)
if failure_count > 0:
print(summary.format(count=failure_count))
for failure in failures:
print('\t' + failure)
display_failures(nonempty_dirs, 'Left {count} non-empty directories:')
display_failures(untrashed_dirs, 'Unable to trash {count} directories:')
display_failures(untrashed_files, 'Unable to trash {count} files:')
print('Trashed {} files and {} emtpy directories.'.format(len(trashed_files), len(trashed_dirs)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment