###################################################################### # Copyright (c) 2007, Petteri Aimonen # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice and this list of conditions. # * Redistributions in binary form must reproduce the above copyright # notice and this list of conditions in the documentation and/or other # materials provided with the distribution. import os import shutil import datetime import settings def backuppath(date = None): '''Return backup file name for datetime.date instance date, or if date is None, for today.''' if not date: date = datetime.date.today() filename = date.strftime("backup-%Y-%m-%d.db") backupdir = settings.parser.get('DEFAULT', 'backupdir') return os.path.join(backupdir, filename) def cleanbackups(): '''Clean old backups. Get backupdir and the number of backups to keep from ConfigParser.''' backupdir = settings.parser.get('DEFAULT', 'backupdir') count = settings.parser.get('DEFAULT', 'keepbackups') files = os.listdir(backupdir) files = [f for f in files if f.startswith('backup-') and f.endswith('.db')] files.sort() # Oldest first if len(files) <= count: return removefiles = files[:(len(files) - count)] for f in removefiles: os.remove(os.path.join(backupdir, f)) def dobackup(): '''Backup database. Get database location and backupdir from ConfigParser.''' backupdir = settings.parser.get('DEFAULT', 'backupdir') if not os.path.isdir(backupdir): os.mkdir(backupdir) dst = backuppath() src = settings.parser.get('DEFAULT', 'dbfile') if os.path.isfile(dst): return # We already have a backup for today shutil.copyfile(src, dst)