forked from lra/mackup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mackup.py
executable file
·708 lines (538 loc) · 21.6 KB
/
mackup.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
#!/usr/bin/env python
"""
Keep you Mac application settings in sync
Copyright (C) 2013 Laurent Raufaste <http://glop.org/>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
###########
# Imports #
###########
import argparse
import base64
import os.path
import shutil
import stat
import sys
import tempfile
#######################
# Commonly used paths #
#######################
PREFERENCES = 'Library/Preferences/'
APP_SUPPORT = 'Library/Application Support/'
#################
# Configuration #
#################
# Applications supported
# Format:
# Application Name: List of files (relative path from the user's home)
SUPPORTED_APPS = {
'Adium': [APP_SUPPORT + 'Adium 2.0',
PREFERENCES + 'com.adiumX.adiumX.plist'],
'Bash': ['.bash_aliases',
'.bash_logout',
'.bashrc',
'.profile',
'.bash_profile',
'.inputrc'],
'Boto': ['.boto'],
'Byobu': ['.byobu',
'.byoburc',
'.byoburc.tmux',
'.byoburc.screen'],
'ControlPlane': [PREFERENCES + 'com.dustinrue.ControlPlane.plist'],
'Emacs': ['.emacs',
'.emacs.d'],
'Fish': ['.config/fish'],
'GeekTool': [
PREFERENCES + 'org.tynsoe.GeekTool.plist',
PREFERENCES + 'org.tynsoe.geeklet.file.plist',
PREFERENCES + 'org.tynsoe.geeklet.image.plist',
PREFERENCES + 'org.tynsoe.geeklet.shell.plist',
PREFERENCES + 'org.tynsoe.geektool3.plist'],
'Git': ['.gitconfig',
'.gitignore_global'],
'GnuPG': ['.gnupg'],
'iTerm2': [PREFERENCES + 'com.googlecode.iterm2.plist'],
'Keymo': [PREFERENCES + 'com.manytricks.Keymo.plist'],
'KeyRemap4MacBook': [
PREFERENCES + 'org.pqrs.KeyRemap4MacBook.plist',
PREFERENCES + 'org.pqrs.KeyRemap4MacBook.multitouchextension.plist',
APP_SUPPORT + 'KeyRemap4MacBook/private.xml'],
'LimeChat': [PREFERENCES + 'net.limechat.LimeChat-AppStore.plist'],
'MacOSX': ['.MacOSX'],
'MacVim': [PREFERENCES + 'org.vim.MacVim.LSSharedFileList.plist',
PREFERENCES + 'org.vim.MacVim.plist'],
'Many Tricks Licenses': [APP_SUPPORT + 'Many Tricks/Licenses'],
'Mercurial': ['.hgrc',
'.hgignore_global'],
'MPV':['.mpv/channels.conf',
'.mpv/config',
'.mpv/input.conf'],
'MercuryMover': [PREFERENCES + 'com.heliumfoot.MyWiAgent.plist'],
'Oh My Zsh': ['.oh-my-zsh'],
'PCKeyboardHack': [PREFERENCES + 'org.pqrs.PCKeyboardHack.plist'],
'Pow': ['.powconfig',
'.powenv',
'.powrc'],
'Quicksilver': [PREFERENCES + 'com.blacktree.Quicksilver.plist',
APP_SUPPORT + 'Quicksilver'],
'Rails': ['.railsrc'],
'Ruby': ['.gemrc',
'.irbrc'],
'Ruby Version': ['.ruby-version'],
'Pentadactyl': ['.pentadactyl',
'.pentadactylrc'],
'S3cmd': ['.s3cfg'],
'Sequel Pro': [APP_SUPPORT + 'Sequel Pro/Data'],
'SizeUp': [PREFERENCES + 'com.irradiatedsoftware.SizeUp.plist',
APP_SUPPORT + 'SizeUp/SizeUp.sizeuplicense'],
'Slate': ['.slate',
APP_SUPPORT + 'com.slate.Slate'],
'SSH': ['.ssh'],
'Sublime Text 2': [APP_SUPPORT + 'Sublime Text 2/Installed Packages',
APP_SUPPORT + 'Sublime Text 2/Packages',
APP_SUPPORT + 'Sublime Text 2/Pristine Packages'],
'Sublime Text 3': [APP_SUPPORT + 'Sublime Text 3/Installed Packages',
APP_SUPPORT + 'Sublime Text 3/Packages'],
'Subversion': ['.subversion'],
'TextMate': [APP_SUPPORT + 'TextMate',
PREFERENCES + 'com.macromates.textmate.plist'],
'Tmux': ['.tmux.conf'],
'Ventrilo': [PREFERENCES + 'Ventrilo'],
'Vim': ['.gvimrc',
'.vim',
'.vimrc'],
'Vimperator': ['.vimperator',
'.vimperatorrc'],
'Witch': [PREFERENCES + 'com.manytricks.Witch.plist'],
'X11': ['.Xresources',
'.fonts'],
'XEmacs': ['.xemacs'],
'Zsh': ['.zshenv',
'.zprofile',
'.zshrc',
'.zlogin',
'.zlogout'],
}
#############
# Constants #
#############
# Current version
VERSION = '0.3.1'
# Mode used to backup files to Dropbox
BACKUP_MODE = 'backup'
# Mode used to restore files from Dropbox
RESTORE_MODE = 'restore'
# Mode used to remove Mackup and reset and config file
UNINSTALL_MODE = 'uninstall'
###########
# 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)
def uninstall(self):
"""
Uninstall Mackup.
Restore any file where it was before the 1st Mackup backup.
Algorithm:
for each file in config
if mackup/file exists
if home/file exists
delete home/file
copy mackup/file home/file
delete the mackup folder
print how to delete mackup
"""
# 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 mackup file exists
if (os.path.isfile(mackup_filepath)
or os.path.isdir(mackup_filepath)):
# Check if there is a corresponding file in the home folder
if os.path.exists(home_filepath):
# If there is, delete it as we are gonna copy the Dropbox
# one there
delete(home_filepath)
# Copy the Dropbox file to the home folder
copy(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"
" <http://www.dropbox.com/>"))
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"
" <http://www.dropbox.com/>"))
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 + ' <Yes|No>')
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: "
epilog += ', '.join(sorted(SUPPORTED_APPS.iterkeys()))
epilog += "\n\nMackup requires a fully synced Dropbox folder."
# Setup the global parser
parser = argparse.ArgumentParser(
description=("Mackup {}\n"
"Keep you application settings in sync.\n"
"Copyright (C) 2013 Laurent Raufaste <http://glop.org/>\n"
.format(VERSION)),
epilog=epilog,
formatter_class=argparse.RawDescriptionHelpFormatter)
# Add the required arg
parser.add_argument("mode",
choices=[BACKUP_MODE, RESTORE_MODE, UNINSTALL_MODE],
help=("Backup will sync your conf files to Dropbox,"
" use this the 1st time you use Mackup.\n"
"Restore will link the conf files already in"
" Dropbox on your system, use it on any new"
" system you use.\n"
"Uninstall will reset everything as it was"
" before using Mackup."))
# 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()
elif args.mode == UNINSTALL_MODE:
# Check the env where the command is being run
mackup.check_for_usable_restore_env()
if confirm("You are going to uninstall Mackup.\n"
"Every configuration file, setting and dotfile managed"
" by Mackup will be unlinked and moved back to their"
" original place, in your home folder.\n"
"Are you sure ?"):
for app_name in SUPPORTED_APPS:
app = ApplicationProfile(mackup, SUPPORTED_APPS[app_name])
app.uninstall()
# Delete the Mackup folder in Dropbox
# Don't delete this as there might be other Macs that aren't
# uninstalled yet
# delete(mackup.mackup_folder)
print ("\n"
"All your files have been put back into place. You can now"
" safely uninstall Mackup.\n"
"If you installed it by hand, you should only have to"
" launch this command:\n"
"\n"
"\tsudo rm {}\n"
"\n"
"Thanks for using Mackup !"
.format(os.path.abspath(__file__)))
else:
raise ValueError("Unsupported mode: {}".format(args.mode))
# Delete the tmp folder
mackup.clean_temp_folder()
if __name__ == "__main__":
main()