Created
December 31, 2015 05:34
-
-
Save yrps/1380e64478c17d037240 to your computer and use it in GitHub Desktop.
remove non-existent files from user's recently-used.xbel (XFCE4)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
def parseArgs(): | |
from sys import stderr | |
import argparse | |
from os.path import expanduser, isfile | |
parser = argparse.ArgumentParser() | |
parser.add_argument( | |
'-f', '--file', help='file to be cleaned', | |
default='~/.local/share/recently-used.xbel' | |
) | |
args = parser.parse_args() | |
ru_file = expanduser(args.file) | |
if not isfile(ru_file): | |
print('file does not exist or is not readable: {}'.format(ru_file), | |
file=stderr) | |
exit(1) | |
return ru_file | |
def parseFile(ru_file): | |
import xml.etree.ElementTree as ET | |
from urllib.request import urlopen | |
from urllib.error import URLError | |
tree = ET.parse(ru_file) | |
bad_bookmarks = [] | |
n_total = 0 | |
for bookmark in tree.getroot().findall('bookmark'): | |
fullpath = bookmark.get('href') | |
n_total += 1 | |
try: | |
urlopen(fullpath) | |
except URLError: | |
bad_bookmarks.append(bookmark) | |
return tree, n_total, bad_bookmarks | |
def promptCleanup(n_total, bad_bookmarks): | |
n_bad = len(bad_bookmarks) | |
print('Scanned {} bookmarks; found {} errors'.format(n_total, n_bad)) | |
if n_bad is 0: | |
return False | |
print('\n'.join([b.get('href') for b in bad_bookmarks])) | |
return input('\nRemove from recently used list? (y/N) ').casefold( | |
).find('y') == 0 | |
def cleanAndSave(bad_bookmarks, ru_file): | |
from os import rename, stat, chown, chmod | |
root = tree.getroot() | |
for bad_bookmark in bad_bookmarks: | |
root.remove(bad_bookmark) | |
status = stat(ru_file) | |
rename(ru_file, ru_file + '.old') | |
tree.write(ru_file, encoding='UTF-8', xml_declaration=True) | |
chmod(ru_file, status.st_mode) | |
chown(ru_file, status.st_uid, status.st_gid) | |
ru_file = parseArgs() | |
tree, n_total, bad_bookmarks = parseFile(ru_file) | |
if not promptCleanup(n_total, bad_bookmarks): | |
exit(0) | |
cleanAndSave(bad_bookmarks, ru_file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment