break db load into smaller functions, load backup if opening primary db fails

pull/131/head
William Ting 12 years ago
parent 626fa8b080
commit 05026ff54e

@ -104,19 +104,44 @@ class Database:
Try to open the database file, recovering from backup if needed.
"""
if os.path.exists(self.filename):
try:
with open(self.filename, 'r') as f:
for line in f.readlines():
weight, path = line[:-1].split("\t", 1)
path = decode(path, 'utf-8')
self.data[path] = float(weight)
elif os.path.exists(self.filename + '.bak'):
except (IOError, EOFError):
self.load_backup(error_recovery)
else:
self.load_backup(error_recovery)
def load_backup(self, error_recovery = False):
"""
Loads database from backup file.
"""
if os.path.exists(self.filename + '.bak'):
if not error_recovery:
print('Problem with autojump database,\
trying to recover from backup...', file=sys.stderr)
shutil.copy(self.filename + '.bak', self.filename)
return self.load(True)
else:
# migration code, autojump_py last used in v17
self.migrate()
def maintenance(self):
"""
Trims and decays database entries when exceeding settings.
"""
if sum(self.data.values()) > MAX_KEYWEIGHT:
self.decay()
if len(self.data) > MAX_STORED_PATHS:
self.trim()
self.save()
def migrate(self):
"""
Migrates database from old format autojump_py, last used in release-v17.
"""
self.filename = get_db_file('autojump_py')
if os.path.exists(self.filename):
try: # fix to get optimised pickle in python < 3
@ -140,16 +165,6 @@ class Database:
pass
return {} # if everything fails, return an empty dictionary
def maintenance(self):
"""
Trims and decays database entries when exceeding settings.
"""
if sum(self.data.values()) > MAX_KEYWEIGHT:
self.decay()
if len(self.data) > MAX_STORED_PATHS:
self.trim()
self.save()
def purge(self):
"""
Deletes all entries that no longer exist on system.

@ -91,7 +91,7 @@ class TestAutojump(unittest.TestCase):
os.remove(fname)
os.remove(fname + '.bak')
def test_db_load_migrate(self):
def test_db_migration(self):
ORIG_CONFIG_DIR = autojump.CONFIG_DIR
try:
# setup
@ -101,8 +101,8 @@ class TestAutojump(unittest.TestCase):
fname = CONFIG_DIR + '/autojump_py'
db = autojump.Database(fname)
db.add('/1')
shutil.copy(fname, fname + '.bak')
db.add('/2')
shutil.copy(fname, fname + '.bak')
# test
missing_fname = '/tmp/autojump_test_db_load_missing_' + str(random.randint(0,32678)) + '.txt'

Loading…
Cancel
Save