Skip to content

Instantly share code, notes, and snippets.

@aidilfbk
Created August 17, 2013 19:03
Show Gist options
  • Save aidilfbk/6258289 to your computer and use it in GitHub Desktop.
Save aidilfbk/6258289 to your computer and use it in GitHub Desktop.
Small python script to delete any empty OS X Safari localstorage files By default, it runs a "simulated delete" Execute with --deleteForReal to actually delete
#!/usr/bin/env python
############################################################
# SafariLocalStorageCleanup.py (18 Aug 2013)
# small script to delete any empty Safari localstorage databases
# default mode runs a "simulated delete"
# run with --deleteForReal to actually delete
############################################################
import sqlite3, sys, os, os.path, platform
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
def disable(self):
self.HEADER = ''
self.OKBLUE = ''
self.OKGREEN = ''
self.WARNING = ''
self.FAIL = ''
self.ENDC = ''
if platform.system() != "Darwin":
print bcolors.FAIL+"Only OS X supported."+bcolors.ENDC
exit()
actuallyDelete = "--deleteForReal" in sys.argv
lsFolder = os.path.expanduser("~/Library/Safari/LocalStorage/")
errorTextPrefix = bcolors.FAIL+"READ ERROR: "+bcolors.ENDC
if actuallyDelete:
deleteTextPrefix = bcolors.OKBLUE+"DELETING: "+bcolors.ENDC
else:
deleteTextPrefix = bcolors.OKBLUE+"SIMULATED DELETE: "+bcolors.ENDC
for root, _, files in os.walk(lsFolder):
for filename in files:
fullpath = os.path.join(root, filename)
if not filename.endswith("localstorage"):
continue
try:
conn = sqlite3.connect(fullpath)
cur = conn.cursor()
cur.execute("SELECT COUNT(key) FROM ItemTable")
count = cur.fetchone()[0]
except sqlite3.OperationalError:
print errorTextPrefix+filename
continue
finally:
conn.close()
if count == 0:
print deleteTextPrefix+filename
if actuallyDelete:
os.remove(fullpath)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment