forked from lra/mackup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mackup.py
executable file
·1214 lines (909 loc) · 39 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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/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 json
import os
import platform
import shutil
import stat
import subprocess
import sys
import tempfile
# Py3k compatible
try:
import configparser
except ImportError:
import ConfigParser as configparser
#######################
# Commonly used paths #
#######################
MACKUP_DB_PATH = 'Mackup'
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 = {
'ABBY FineReader for ScanSnap': [PREFERENCES + 'com.abbyy.FineReaderForScanSnap.plist'],
'Ack': ['.ackrc'],
'Adium': [APP_SUPPORT + 'Adium 2.0',
PREFERENCES + 'com.adiumX.adiumX.plist'],
'Adobe Lightroom': [
APP_SUPPORT + 'Adobe/Lightroom/Develop Presets',
APP_SUPPORT + 'Adobe/Lightroom/Export Actions',
APP_SUPPORT + 'Adobe/Lightroom/Export Presets',
APP_SUPPORT + 'Adobe/Lightroom/Filename Templates',
APP_SUPPORT + 'Adobe/Lightroom/Filter Presets',
APP_SUPPORT + 'Adobe/Lightroom/Import Presets',
APP_SUPPORT + 'Adobe/Lightroom/Keyword Sets',
APP_SUPPORT + 'Adobe/Lightroom/Label Sets',
APP_SUPPORT + 'Adobe/Lightroom/Local Adjustment Presets',
APP_SUPPORT + 'Adobe/Lightroom/Locations',
APP_SUPPORT + 'Adobe/Lightroom/Metadata Presets',
APP_SUPPORT + 'Adobe/Lightroom/Modules',
APP_SUPPORT + 'Adobe/Lightroom/Plugins',
APP_SUPPORT + 'Adobe/Lightroom/Watermarks'],
'AppCode 2': [APP_SUPPORT + 'appCode20',
PREFERENCES + 'appCode20'],
'Bartender': [PREFERENCES + 'com.surteesstudios.Bartender.plist'],
'Bash': ['.bash_aliases',
'.bash_logout',
'.bashrc',
'.profile',
'.bash_profile',
'.inputrc'],
'Bash it': ['.bash_it'],
'BetterSnapTool': [
PREFERENCES + 'com.hegenberg.BetterSnapTool.plist',
APP_SUPPORT + 'BetterSnapTool'],
'BetterTouchTool': [
PREFERENCES + 'com.hegenberg.BetterTouchTool.plist',
APP_SUPPORT + 'BetterTouchTool'],
'BibDesk': [PREFERENCES + 'edu.ucsd.cs.mmccrack.bibdesk.plist'],
'Boto': ['.boto'],
'Bundler': ['.bundler'],
'Byobu': ['.byobu',
'.byoburc',
'.byoburc.tmux',
'.byoburc.screen'],
'Caffeine': [PREFERENCES + 'com.lightheadsw.Caffeine.plist'],
'Cardiris for ScanSnap': [PREFERENCES + 'Cardiris Prefs'],
'Chef': ['.chef'],
'ClipMenu': [APP_SUPPORT + 'ClipMenu',
PREFERENCES + 'com.naotaka.ClipMenu.plist'],
'CloudApp': [PREFERENCES + 'com.linebreak.CloudAppMacOSX.plist'],
'Colloquy': [PREFERENCES + 'info.colloquy.plist',
APP_SUPPORT + 'Colloquy'],
'Concentrate': [APP_SUPPORT + 'Concentrate/Concentrate.sqlite3'],
'ControlPlane': [PREFERENCES + 'com.dustinrue.ControlPlane.plist'],
'CoRD': [APP_SUPPORT + 'CoRD'],
'Coda 2': [APP_SUPPORT + 'Coda 2',
PREFERENCES + 'com.panic.Coda2.plist'],
'Curl': ['.netrc'],
'Divvy': [PREFERENCES + 'com.mizage.direct.Divvy.plist'],
'Droplr': [PREFERENCES + 'com.droplr.droplr-mac.plist'],
'Emacs': ['.emacs',
'.emacs.d'],
'Exercism': ['.exercism'],
'ExpanDrive': [APP_SUPPORT + 'ExpanDrive'],
'Fantastical': [PREFERENCES + 'com.flexibits.fantastical.plist'],
'Fish': ['.config/fish'],
'Flux': [PREFERENCES + 'org.herf.Flux.plist'],
'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'],
'Gitbox': [PREFERENCES + 'com.oleganza.gitbox.plist'],
'Git Hooks': ['.git_hooks'],
'GnuPG': ['.gnupg'],
'Heroku': ['.heroku/accounts', '.heroku/plugins'],
'Htop': ['.htoprc'],
'IntelliJIdea 12': [APP_SUPPORT + 'IntelliJIdea12',
PREFERENCES + 'IntelliJIdea12'],
'iTerm2': [PREFERENCES + 'com.googlecode.iterm2.plist'],
'Irssi': ['.irssi'],
'iWork Templates': [APP_SUPPORT + "iWork"],
'Janus': ['.janus'],
'Keymo': [PREFERENCES + 'com.manytricks.Keymo.plist'],
'KeyRemap4MacBook': [
PREFERENCES + 'org.pqrs.KeyRemap4MacBook.plist',
PREFERENCES + 'org.pqrs.KeyRemap4MacBook.multitouchextension.plist',
APP_SUPPORT + 'KeyRemap4MacBook/private.xml'],
'LaTeXiT': [PREFERENCES + 'fr.chachatelier.pierre.LaTeXiT.plist'],
'LimeChat': [PREFERENCES + 'net.limechat.LimeChat-AppStore.plist'],
'Mackup': ['.mackup.cfg'],
'Mailplane': [PREFERENCES + 'com.mailplaneapp.Mailplane.plist'],
'MacOSX': ['.MacOSX',
'Library/ColorSync/Profiles'],
'MacVim': [PREFERENCES + 'org.vim.MacVim.LSSharedFileList.plist',
PREFERENCES + 'org.vim.MacVim.plist'],
'MenuMeters': [PREFERENCES + 'com.ragingmenace.MenuMeters.plist'],
'Mercurial': ['.hgrc',
'.hgignore_global'],
'Moom': [
PREFERENCES + 'com.manytricks.Moom.plist',
APP_SUPPORT + 'Many Tricks'],
'MPV': ['.mpv/channels.conf',
'.mpv/config',
'.mpv/input.conf'],
'MercuryMover': [PREFERENCES + 'com.heliumfoot.MyWiAgent.plist'],
'Nano': ['.nanorc'],
'nvALT': [PREFERENCES + 'net.elasticthreads.nv.plist',
APP_SUPPORT + 'Notational Velocity',
APP_SUPPORT + 'Notational Data'],
'Oh My Zsh': ['.oh-my-zsh'],
'OmniFocus': [
APP_SUPPORT + 'OmniFocus/Plug-Ins',
APP_SUPPORT + 'OmniFocus/Themes'],
'Pastebot': [
PREFERENCES + 'com.tapbots.PastebotSync.plist',
PREFERENCES + 'com.tapbots.PastebotSync.prefPane.plist',
PREFERENCES + 'com.tapbots.PastebotSync.stats.plist'],
'PCKeyboardHack': [PREFERENCES + 'org.pqrs.PCKeyboardHack.plist'],
'Pear': ['.pearrc'],
'PhpStorm 6': [APP_SUPPORT + 'WebIde60',
PREFERENCES + 'WebIde60',
PREFERENCES + 'com.jetbrains.PhpStorm.plist'],
'pip': ['.pip/pip.cfg'],
'PopClip': [
PREFERENCES + 'com.pilotmoon.popclip.plist',
APP_SUPPORT + 'PopClip'],
'Pow': ['.powconfig',
'.powenv',
'.powrc'],
'PyPI': ['.pypirc'],
'Quicklook': ['Library/Quicklook'],
'Quicksilver': [PREFERENCES + 'com.blacktree.Quicksilver.plist',
APP_SUPPORT + 'Quicksilver'],
'Rails': ['.railsrc'],
'Ruby': ['.gemrc',
'.irbrc',
'.gem',
'.pryrc',
'.aprc'],
'RubyMine 4': [APP_SUPPORT + 'RubyMine40',
PREFERENCES + 'RubyMine40'],
'RubyMine 5': [APP_SUPPORT + 'RubyMine50',
PREFERENCES + 'RubyMine50'],
'Ruby Version': ['.ruby-version'],
'Pentadactyl': ['.pentadactyl',
'.pentadactylrc'],
'S3cmd': ['.s3cfg'],
'ScanSnap Manager V3.2': [PREFERENCES + 'jp.co.pfu.ScanSnap.P2IUNISET.plist',
PREFERENCES + 'jp.co.pfu.ScanSnap.QMScanToPrint.plist',
PREFERENCES + 'jp.co.pfu.ScanSnap.Scan2EN2Setting.plist',
PREFERENCES + 'jp.co.pfu.ScanSnap.Scan2Folder.plist',
PREFERENCES + 'jp.co.pfu.ScanSnap.Scan2FolderSetting.plist',
PREFERENCES + 'jp.co.pfu.ScanSnap.Scan2GDocSetting.plist',
PREFERENCES + 'jp.co.pfu.ScanSnap.Scan2MailSetting.plist',
PREFERENCES + 'jp.co.pfu.ScanSnap.Scan2MobileSetting.plist',
PREFERENCES + 'jp.co.pfu.ScanSnap.Scan2PrintSetting.plist',
PREFERENCES + 'jp.co.pfu.ScanSnap.ScanToDropboxSetting.plist',
PREFERENCES + 'jp.co.pfu.ScanSnap.ScanToFolder.plist',
PREFERENCES + 'jp.co.pfu.ScanSnap.ScanToSalesforceSetting.plist',
PREFERENCES + 'jp.co.pfu.ScanSnap.V10L10.plist'],
'Scenario': [PREFERENCES + 'com.lagente.scenario.plist',
'Library/Scenario'],
'Scripts': ['Library/Scripts'],
'Screen': ['.screenrc'],
'SelfControl': [PREFERENCES + 'org.eyebeam.SelfControl.plist'],
'Sequel Pro': [APP_SUPPORT + 'Sequel Pro/Data'],
'Services': ['Library/Services'],
'SHSH Blobs': ['.shsh'],
'Shuttle': ['.shuttle.json'],
'SizeUp': [PREFERENCES + 'com.irradiatedsoftware.SizeUp.plist',
APP_SUPPORT + 'SizeUp/SizeUp.sizeuplicense'],
'Skim': [PREFERENCES + 'net.sourceforge.skim-app.skim.plist'],
'Skype': [PREFERENCES + 'com.skype.skype.plist',
APP_SUPPORT + 'Skype'],
'Slate': ['.slate',
APP_SUPPORT + 'com.slate.Slate'],
'Slogger': ['Slogger'],
'SourceTree': [APP_SUPPORT + 'SourceTree/sourcetree.license',
APP_SUPPORT + 'SourceTree/browser.plist',
APP_SUPPORT + 'SourceTree/hgrc_sourcetree',
APP_SUPPORT + 'SourceTree/hostingservices.plist',
PREFERENCES + 'com.torusknot.SourceTree.plist',
PREFERENCES + 'com.torusknot.SourceTreeNotMAS.plist'],
'Spark': [APP_SUPPORT + 'Spark'],
'Spectacle': [PREFERENCES + 'com.divisiblebyzero.Spectacle.plist'],
'Spotify' : [PREFERENCES + 'com.spotify.client.plist'],
'SSH': ['.ssh'],
'Stata': [APP_SUPPORT + 'Stata',
PREFERENCES + 'com.stata.stata12.plist',
PREFERENCES + 'com.stata.stata13.plist'],
'Sublime Text 2': [APP_SUPPORT + 'Sublime Text 2/Installed Packages',
APP_SUPPORT + 'Sublime Text 2/Packages',
APP_SUPPORT + 'Sublime Text 2/Pristine Packages',
APP_SUPPORT + 'Sublime Text 2/Settings'],
'Sublime Text 3': [APP_SUPPORT + 'Sublime Text 3/Installed Packages',
APP_SUPPORT + 'Sublime Text 3/Packages'],
'Subversion': ['.subversion'],
'Teamocil': ['.teamocil'],
'TextMate': [APP_SUPPORT + 'TextMate',
PREFERENCES + 'com.macromates.textmate.plist',
PREFERENCES + 'com.macromates.textmate.webpreview.plist'],
'TextMate GetBundles': [PREFERENCES + 'com.macromates.textmate.getbundles.plist'],
'TextWrangler': [APP_SUPPORT + 'TextWrangler',
PREFERENCES + 'com.barebones.textwrangler.PreferenceData',
PREFERENCES + 'com.barebones.textwrangler.plist'],
'Tmux': ['.tmux.conf'],
'Tmuxinator': ['.tmuxinator'],
'TotalFinder': [PREFERENCES + 'com.binaryage.totalfinder.crashwatcher.plist',
PREFERENCES + 'com.binaryage.totalfinder.plist'],
'TotalTerminal': [PREFERENCES + 'com.binaryage.totalterminal.crashwatcher.plist',
PREFERENCES + 'com.binaryage.totalterminal.plist'],
'Tower': [APP_SUPPORT + 'Tower',
PREFERENCES + 'com.fournova.Tower.plist'],
'Transmission': [PREFERENCES + 'org.m0k.transmission.plist'],
'Transmit': [
PREFERENCES + 'com.panic.Transmit.plist',
APP_SUPPORT + 'Transmit/Metadata'
],
'Twitterrific': [APP_SUPPORT + 'Twitterrific'],
'VelaClock': [PREFERENCES + 'widget-com.veladg.widget.velaclockdeluxe.plist',
PREFERENCES + 'com.veladg.vcDeluxeReg.plist',
APP_SUPPORT + 'VelaClock',
APP_SUPPORT + 'Vela Design Group'],
'VelaTerra': [PREFERENCES + 'com.veladg.VelaTerra.plist',
APP_SUPPORT + 'VelaTerra'],
'Ventrilo': [PREFERENCES + 'Ventrilo'],
'Vim': ['.gvimrc',
'.gvimrc.before',
'.gvimrc.after',
'.vim',
'.vimrc',
'.vimrc.before',
'.vimrc.after'],
'Vimperator': ['.vimperator',
'.vimperatorrc'],
'Viscosity': [APP_SUPPORT + 'Viscosity',
PREFERENCES + 'com.viscosityvpn.Viscosity.plist'],
'Witch': [PREFERENCES + 'com.manytricks.Witch.plist'],
'X11': ['.Xresources',
'.fonts'],
'Xcode': ['Library/Developer/Xcode/UserData/CodeSnippets',
'Library/Developer/Xcode/UserData/FontAndColorThemes',
'Library/Developer/Xcode/UserData/KeyBindings',
'Library/Developer/Xcode/UserData/SearchScopes.xcsclist'],
'XEmacs': ['.xemacs'],
'Zsh': ['.zshenv',
'.zprofile',
'.zshrc',
'.zlogin',
'.zlogout'],
}
#############
# Constants #
#############
# Current version
VERSION = '0.5.2'
# 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'
# Support platforms
PLATFORM_DARWIN = 'Darwin'
PLATFORM_LINUX = 'Linux'
###########
# 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."
"\nAre 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
# and the folder makes sense on the current platform (Don't sync
# any subfolder of ~/Library on GNU/Linux)
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))
and can_file_be_synced_on_current_platform(filename)):
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 = os.path.join(self.dropbox_folder, MACKUP_DB_PATH)
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/>"))
# Is Sublime Text running ?
#if is_process_running('Sublime Text'):
# error(("Sublime Text is running. It is known to cause problems"
# " when Sublime Text is running while I backup or restore"
# " its configuration files. Please close Sublime Text and"
# " run me again."))
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
"""
# Some files have ACLs, let's remove them recursively
remove_acl(filepath)
# Some files have immutable attributes, let's remove them recursively
remove_immutable_attribute(filepath)
# Finally remove the files and folders
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) or isinstance(src, unicode)
assert os.path.exists(src)
assert isinstance(dst, str) or isinstance(src, unicode)
# 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)
# 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) or isinstance(target, unicode)
assert os.path.exists(target)
assert isinstance(link, str) or isinstance(target, unicode)
# 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) or isinstance(target, unicode)
assert os.path.exists(target)
file_mode = stat.S_IRUSR | stat.S_IWUSR
folder_mode = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
# Remove the immutable attribute recursively if there is one
remove_immutable_attribute(target)
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 immediately 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
def get_ignored_apps():
"""
Get the list of applications ignored in the config file
Returns:
(set) List of application names to ignore, lowercase
"""
# If a config file exists, grab it and parser it
config = configparser.SafeConfigParser(allow_no_value=True)
# We ignore nothing by default
ignored_apps = []
# Is the config file there ?
if config.read(os.environ['HOME'] + '/.mackup.cfg'):
# Is the "Ignored Applications" in the cfg file ?
if config.has_section('Ignored Applications'):
ignored_apps = config.options('Ignored Applications')
return set(ignored_apps)
def get_config_path_and_append_to_backup(section, optionName, mackup):
"""
Looks in the config for the specified option in the specified section. If it is there,
it reads the value and parses it as a path. If the path is valid, it appends the path
to the list of files to backup for the 'Mackup' application entry.
Args:
section(str): The section in the config file
optionName(str): The option name to look for
mackup(Mackup): the instance that is running
Returns:
The path if it is valid and exists, the empty string otherwise.
"""
# If a config file exists, grab it and parser it
config = configparser.SafeConfigParser(allow_no_value=True)
# Is the config file there (be sure to check the backup dir since it may not have been copied yet) ?
if config.read(os.environ['HOME'] + '/.mackup.cfg') or config.read(mackup.mackup_folder + '/.mackup.cfg'):
# Is the section/option pair in the cfg file ?
if config.has_option(section,optionName):
path = os.path.expanduser( config.get(section,optionName))
relPath = os.path.relpath(path, os.environ['HOME'])
# Is the specified path valid (either on the real system or in the backup) ?
if os.path.exists(path):
SUPPORTED_APPS['Mackup'].append(relPath)
return path;
elif os.path.exists(mackup.mackup_folder + '/' + relPath):
SUPPORTED_APPS['Mackup'].append(relPath)
return mackup.mackup_folder + '/' + relPath
return "";
def get_custom_apps(mackup):
"""
Get the list of custom applications referenced in the config file and
reads it in as a dictionary.
Args:
mackup(Mackup) the instance that is running
Returns:
(dictionary) Applications / files to backup or an empy dictionary
if the user didn't specify any custom applications
"""
path = get_config_path_and_append_to_backup('Custom Applications', 'dictionaryFile', mackup)
if path:
json_data=open(path).read()
return json.loads(json_data)
return {}
def get_allowed_apps():
"""
Get the list of applications allowed in the config file
Returns:
(set) list of applciation names to backup
"""