#!/usr/bin/env python """Keep you Mac application settings in sync""" ########### # Imports # ########### import argparse import base64 import os.path import shutil import stat import sys import tempfile ################# # Configuration # ################# # Applications supported # Format: # Application Name: List of files (absolute path from the user's home) SUPPORTED_APPS = { 'Bash': ['.bash_aliases', '.bash_logout', '.bashrc', '.profile'], 'Boto': ['.boto'], 'Git': ['.gitconfig'], 'GnuPG': ['.gnupg'], 'MacOSX': ['.MacOSX'], 'Mercurial': ['.hgrc'], 'S3cmd': ['.s3cfg'], 'Sequel Pro': ['Library/Application Support/Sequel Pro/Data'], 'SSH': ['.ssh'], 'Sublime Text 2': [ 'Library/Application Support/Sublime Text 2/Installed Packages', 'Library/Application Support/Sublime Text 2/Packages', 'Library/Application Support/Sublime Text 2/Pristine Packages'], 'Vim': ['.vim', '.vimrc'], 'X11': ['.Xresources', '.fonts'], } ############# # Constants # ############# # Current version VERSION = '0.1' # Mode used to backup files to Dropbox BACKUP_MODE = 'backup' # Mode used to restore files from Dropbox RESTORE_MODE = 'restore' ########### # Classes # ########### class ApplicationProfile(object): """Instantiate this class with application specific data""" def __init__(self, mackup, files): """ Create an ApplicationProfile instance Args: mackup (Mackup) files (list) """ assert isinstance(mackup, Mackup) assert isinstance(files, list) self.mackup = mackup self.files = files def backup(self): """ Backup the application config files Algorithm: if exists home/file if home/file is a real file if exists mackup/file are you sure ? if sure rm mackup/file mv home/file mackup/file link mackup/file home/file else mv home/file mackup/file link mackup/file home/file """ # For each file used by the application for filename in self.files: # Get the full path of each file filepath = os.path.join(os.environ['HOME'], filename) mackup_filepath = os.path.join(self.mackup.mackup_folder, filename) # If the file exists and is not already a link pointing to Mackup if ((os.path.isfile(filepath) or os.path.isdir(filepath)) and not (os.path.islink(filepath) and (os.path.isfile(mackup_filepath) or os.path.isdir(mackup_filepath)) and os.path.samefile(filepath, mackup_filepath))): print "Backing up {}...".format(filename) # Check if we already have a backup if os.path.exists(mackup_filepath): # Name it right if os.path.isfile(mackup_filepath): file_type = 'file' elif os.path.isdir(mackup_filepath): file_type = 'folder' elif os.path.islink(mackup_filepath): file_type = 'link' else: raise ValueError("Unsupported file: {}" .format(mackup_filepath)) # Ask the user if he really want to replace it if confirm("A {} named {} already exists in the backup." "\nOr you sure that your want to replace it ?" .format(file_type, mackup_filepath)): # Delete the file in Mackup delete(mackup_filepath) # Copy the file copy(filepath, mackup_filepath) # Delete the file in the home delete(filepath) # Link the backuped file to its original place link(mackup_filepath, filepath) else: # Copy the file copy(filepath, mackup_filepath) # Delete the file in the home delete(filepath) # Link the backuped file to its original place link(mackup_filepath, filepath) def restore(self): """ Restore the application config files Algorithm: if exists mackup/file if exists home/file are you sure ? if sure rm home/file link mackup/file home/file else link mackup/file home/file """ # For each file used by the application for filename in self.files: # Get the full path of each file mackup_filepath = os.path.join(self.mackup.mackup_folder, filename) home_filepath = os.path.join(os.environ['HOME'], filename) # If the file exists and is not already pointing to the mackup file if ((os.path.isfile(mackup_filepath) or os.path.isdir(mackup_filepath)) and not (os.path.islink(home_filepath) and os.path.samefile(mackup_filepath, home_filepath))): print "Restoring {}...".format(filename) # Check if there is already a file in the home folder if os.path.exists(home_filepath): # Name it right if os.path.isfile(home_filepath): file_type = 'file' elif os.path.isdir(home_filepath): file_type = 'folder' elif os.path.islink(home_filepath): file_type = 'link' else: raise ValueError("Unsupported file: {}" .format(mackup_filepath)) if confirm("You already have a {} named {} in your home." "\nDo you want to replace it with your backup ?" .format(file_type, filename)): delete(home_filepath) link(mackup_filepath, home_filepath) else: link(mackup_filepath, home_filepath) class Mackup(object): """Main Mackup class""" def __init__(self): """Mackup Constructor""" try: self.dropbox_folder = get_dropbox_folder_location() except IOError: error(("Unable to find the Dropbox folder." " If Dropbox is not installed and running, go for it on" " ")) self.mackup_folder = self.dropbox_folder + '/Mackup' self.temp_folder = tempfile.mkdtemp(prefix="mackup_tmp_") def _check_for_usable_environment(self): """Check if the current env is usable and has everything's required""" # Do we have a home folder ? if not os.path.isdir(self.dropbox_folder): error(("Unable to find the Dropbox folder." " If Dropbox is not installed and running, go for it on" " ")) def check_for_usable_backup_env(self): """Check if the current env can be used to back up files""" self._check_for_usable_environment() self.create_mackup_home() def check_for_usable_restore_env(self): """Check if the current env can be used to restore files""" self._check_for_usable_environment() if not os.path.isdir(self.mackup_folder): error("Unable to find the Mackup folder: {}\n" "You might want to backup some files or get your Dropbox" " folder synced first." .format(self.mackup_folder)) def clean_temp_folder(self): """Delete the temp folder and files created while running""" shutil.rmtree(self.temp_folder) def create_mackup_home(self): """If the Mackup home folder does not exist, create it""" if not os.path.isdir(self.mackup_folder): if confirm("Mackup needs a folder to store your configuration " " files\nDo you want to create it now ? <{}>" .format(self.mackup_folder)): os.mkdir(self.mackup_folder) else: error("Mackup can't do anything without a home =(") #################### # Useful functions # #################### def confirm(question): """ Ask the user if he really want something to happen Args: question(str): What can happen Returns: (boolean): Confirmed or not """ while True: answer = raw_input(question + ' ') if answer == 'Yes': confirmed = True break if answer == 'No': confirmed = False break return confirmed def delete(filepath): """ Delete the given file, directory or link. Should support undelete later on. Args: filepath (str): Absolute full path to a file. e.g. /path/to/file """ if os.path.isfile(filepath) or os.path.islink(filepath): os.remove(filepath) elif os.path.isdir(filepath): shutil.rmtree(filepath) def copy(src, dst): """ Copy a file or a folder (recursively) from src to dst. For simplicity sake, both src and dst must be absolute path and must include the filename of the file or folder. Also do not include any trailing slash. e.g. copy('/path/to/src_file', '/path/to/dst_file') or copy('/path/to/src_folder', '/path/to/dst_folder') But not: copy('/path/to/src_file', 'path/to/') or copy('/path/to/src_folder/', '/path/to/dst_folder') Args: src (str): Source file or folder dst (str): Destination file or folder """ assert isinstance(src, str) assert os.path.exists(src) assert isinstance(dst, str) # Create the path to the dst file if it does not exists abs_path = os.path.dirname(os.path.abspath(dst)) if not os.path.isdir(abs_path): os.makedirs(abs_path) # We need to copy a single file if os.path.isfile(src): # Copy the src file to dst shutil.copy(src, dst) # The file should be 0600 # We need to copy a whole folder elif os.path.isdir(src): shutil.copytree(src, dst) # What the heck is this ? else: raise ValueError("Unsupported file: {}".format(src)) # Set the good mode to the file or folder recursively chmod(dst) def link(target, link): """ Create a link to a target file or a folder. For simplicity sake, both target and link must be absolute path and must include the filename of the file or folder. Also do not include any trailing slash. e.g. link('/path/to/file', '/path/to/link') But not: link('/path/to/file', 'path/to/') or link('/path/to/folder/', '/path/to/link') Args: target (str): file or folder the link will point to link (str): Link to create """ assert isinstance(target, str) assert os.path.exists(target) assert isinstance(link, str) # Create the path to the link if it does not exists abs_path = os.path.dirname(os.path.abspath(link)) if not os.path.isdir(abs_path): os.makedirs(abs_path) # Make sure the file or folder recursively has the good mode chmod(target) # Create the link to target os.symlink(target, link) def chmod(target): """ Recursively set the chmod for files to 0600 and 0700 for folders. It's ok unless we need something more specific. Args: target (str): Root file or folder """ assert isinstance(target, str) assert os.path.exists(target) file_mode = stat.S_IRUSR | stat.S_IWUSR folder_mode = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR if os.path.isfile(target): os.chmod(target, file_mode) elif os.path.isdir(target): # chmod the root item os.chmod(target, folder_mode) # chmod recursively in the folder it it's one for root, dirs, files in os.walk(target): for cur_dir in dirs: os.chmod(os.path.join(root, cur_dir), folder_mode) for cur_file in files: os.chmod(os.path.join(root, cur_file), file_mode) else: raise ValueError("Unsupported file type: {}".format(target)) def error(message): """ Throw an error with the given message and immediatly quit. Args: message(str): The message to display. """ sys.exit("Error: {}".format(message)) def parse_cmdline_args(): """ Setup the engine that's gonna parse the command line arguments Returns: (argparse.Namespace) """ # Format some epilog text epilog = "Supported applications:\n" for app in sorted(SUPPORTED_APPS.iterkeys()): epilog = epilog + " - {}\n".format(app) epilog += "\nMackup requires a fully synced Dropbox folder." # Setup the global parser parser = argparse.ArgumentParser( description=("Mackup {}\n" "Keep you application settings in sync." .format(VERSION)), epilog=epilog, formatter_class=argparse.RawDescriptionHelpFormatter) # Add the required arg parser.add_argument("mode", choices=[BACKUP_MODE, RESTORE_MODE], help=("Backup your conf files to Dropbox or restore" " your files locally from Dropbox")) # Parse the command line and return the parsed options return parser.parse_args() def get_dropbox_folder_location(): """ Try to locate the Dropbox folder Returns: (str) Full path to the current Dropbox folder """ host_db_path = os.environ['HOME'] + '/.dropbox/host.db' with open(host_db_path, 'r') as f: data = f.read().split() dropbox_home = base64.b64decode(data[1]) return dropbox_home ################ # Main Program # ################ def main(): """Main function""" # Get the command line arg args = parse_cmdline_args() mackup = Mackup() if args.mode == BACKUP_MODE: # Check the env where the command is being run mackup.check_for_usable_backup_env() for app_name in SUPPORTED_APPS: app = ApplicationProfile(mackup, SUPPORTED_APPS[app_name]) app.backup() elif args.mode == RESTORE_MODE: # Check the env where the command is being run mackup.check_for_usable_restore_env() for app_name in SUPPORTED_APPS: app = ApplicationProfile(mackup, SUPPORTED_APPS[app_name]) app.restore() else: raise ValueError("Unsupported mode: {}".format(args.mode)) # Delete the tmp folder mackup.clean_temp_folder() if __name__ == "__main__": main()