-
Notifications
You must be signed in to change notification settings - Fork 2
/
PackageSync.py
656 lines (528 loc) · 25.9 KB
/
PackageSync.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
import sublime
import sublime_plugin
import os
import tempfile
import fnmatch
import time
import shutil
import zipfile
import json
import sys
try:
from .package_sync_helpers import tools
from .package_sync_helpers import online
from .package_sync_helpers import offline
except ValueError:
from package_sync_helpers import tools
from package_sync_helpers import online
from package_sync_helpers import offline
sync_queue = online.Queue()
class PsyncLocalBackupListCommand(sublime_plugin.WindowCommand):
# def is_enabled(self):
# return True
def run(self):
psync_settings = tools.get_psync_settings()
if psync_settings["prompt_for_location"] == False:
list_backup_path = psync_settings["list_backup_path"]
backup_path = None
try:
if list_backup_path == "":
backup_path = tools.default_list_backup_path
elif os.path.exists(list_backup_path):
if sublime.ok_cancel_dialog(
"Backup already exists @ %s \nReplace it?" % list_backup_path) == True:
os.remove(list_backup_path)
backup_path = list_backup_path
else:
backup_path = None
elif os.path.isabs(os.path.dirname(list_backup_path)):
backup_path = list_backup_path
else:
sublime.error_message(
"Invalid path provided in user-settings. Please correct & then retry.")
backup_path = None
except Exception as e:
tools.log("PackageSync: Error while fetching backup path.", force=True)
tools.log("PackageSync: Error message: %s" % str(e), force=True)
self.backup_pkg_list(backup_path)
else:
offline.prompt_parameters = {
"mode": "backup",
"type": "file",
"window_context": self.window,
"initial_text": tools.default_list_backup_path,
"operation_to_perform": self.backup_pkg_list,
"on_change": None,
"on_cancel": tools.packagesync_cancelled
}
offline.prompt_for_location()
def backup_pkg_list(self, backup_path):
if backup_path is not None:
try:
package_control_settings = sublime.load_settings(
"Package Control.sublime-settings")
installed_packages = package_control_settings.get(
"installed_packages") or []
if os.path.isfile(backup_path):
os.remove(backup_path)
elif not os.path.exists(os.path.dirname(backup_path)):
os.makedirs(os.path.dirname(backup_path))
with open(backup_path, "w") as _backupFile:
json.dump(
{"installed_packages": installed_packages}, _backupFile, indent=4)
tools.log("PackageSync: Backup of installed packages list created at %s" %
backup_path)
except Exception as e:
tools.log(
"PackageSync: Error while backing up installed packages list", force=True)
tools.log("PackageSync: Error message: %s" % str(e), force=True)
else:
tools.packagesync_cancelled()
class PsyncLocalRestoreListCommand(sublime_plugin.WindowCommand):
# def is_enabled(self):
# return True
def run(self):
psync_settings = tools.get_psync_settings()
if psync_settings["prompt_for_location"] == False:
list_backup_path = psync_settings["list_backup_path"]
backup_path = None
try:
if list_backup_path == "":
backup_path = tools.default_list_backup_path
elif os.path.isfile(list_backup_path):
backup_path = list_backup_path
else:
sublime.error_message(
"Invalid path provided in user-settings. Please correct & then retry.")
backup_path = None
except Exception as e:
tools.log("PackageSync: Error while fetching backup path.", force=True)
tools.log("PackageSync: Error message: %s" % str(e), force=True)
self.restore_pkg_list(backup_path)
else:
offline.prompt_parameters = {
"mode": "restore",
"type": "file",
"window_context": self.window,
"initial_text": tools.default_list_backup_path,
"operation_to_perform": self.restore_pkg_list,
"on_change": None,
"on_cancel": tools.packagesync_cancelled
}
offline.prompt_for_location()
def restore_pkg_list(self, backup_path):
if backup_path is not None:
try:
tools.log("PackageSync: Restoring package list from %s" %
backup_path)
with open(backup_path, "r") as f:
_installed_packages = json.load(f)["installed_packages"]
_package_control_settings = sublime.load_settings(
"Package Control.sublime-settings")
_package_control_settings.set(
"installed_packages", _installed_packages)
sublime.save_settings("Package Control.sublime-settings")
tools.install_new_packages()
except Exception as e:
tools.log(
"PackageSync: Error while restoring packages from package list", force=True)
tools.log("PackageSync: Error message: %s" % str(e), force=True)
else:
tools.packagesync_cancelled()
class PsyncLocalBackupFolderCommand(sublime_plugin.WindowCommand):
# def is_enabled(self):
# return True
def run(self):
psync_settings = tools.get_psync_settings()
if psync_settings["prompt_for_location"] == False:
folder_backup_path = psync_settings["folder_backup_path"]
backup_path = None
try:
if folder_backup_path == "":
backup_path = tools.default_folder_backup_path
elif os.path.exists(folder_backup_path) and len(os.listdir(folder_backup_path)) > 0:
if sublime.ok_cancel_dialog(
"Backup already exists @ %s \nReplace it?" % folder_backup_path) == True:
backup_path = folder_backup_path
else:
backup_path = None
elif os.path.isabs(os.path.dirname(folder_backup_path)):
backup_path = folder_backup_path
else:
sublime.error_message(
"Invalid path provided in user-settings. Please correct & then retry.")
backup_path = None
except Exception as e:
tools.log("PackageSync: Error while fetching backup path.", force=True)
tools.log("PackageSync: Error message: %s" % str(e), force=True)
self.backup_folder(backup_path)
else:
offline.prompt_parameters = {
"mode": "backup",
"type": "folder",
"window_context": self.window,
"initial_text": tools.default_folder_backup_path,
"operation_to_perform": self.backup_folder,
"on_change": None,
"on_cancel": tools.packagesync_cancelled
}
offline.prompt_for_location()
def backup_folder(self, backup_path):
if backup_path is not None:
try:
offline.create_temp_backup()
if os.path.isdir(backup_path):
shutil.rmtree(backup_path, True)
shutil.copytree(tools.temp_backup_folder, backup_path)
tools.log("PackageSync: Backup of packages & settings created at %s" %
backup_path)
except Exception as e:
tools.log("PackageSync: Error while backing up packages to folder", force=True)
tools.log("PackageSync: Error message: %s" % str(e), force=True)
else:
tools.packagesync_cancelled()
class PsyncLocalRestoreFolderCommand(sublime_plugin.WindowCommand):
# def is_enabled(self):
# return True
def run(self):
psync_settings = tools.get_psync_settings()
if psync_settings["prompt_for_location"] == False:
folder_backup_path = psync_settings["folder_backup_path"]
backup_path = None
try:
if folder_backup_path == "":
backup_path = tools.default_folder_backup_path
elif os.path.isdir(folder_backup_path):
backup_path = folder_backup_path
else:
sublime.error_message(
"Invalid path provided in user-settings. Please correct & then retry.")
backup_path = None
except Exception as e:
tools.log("PackageSync: Error while fetching backup path.", force=True)
tools.log("PackageSync: Error message: %s" % str(e), force=True)
self.restore_folder(backup_path)
else:
offline.prompt_parameters = {
"mode": "restore",
"type": "folder",
"window_context": self.window,
"initial_text": tools.default_folder_backup_path,
"operation_to_perform": self.restore_folder,
"on_change": None,
"on_cancel": tools.packagesync_cancelled
}
offline.prompt_for_location()
def restore_folder(self, backup_path):
if backup_path is not None:
try:
tools.log(
"PackageSync: Restoring package list & user settings from %s" % backup_path, force=True)
# Backup PackageSync user settings before restore operation
packagesync_settings_backup = os.path.join(
tempfile.gettempdir(), str(time.time()))
packagesync_settings_original = os.path.join(
tools.user_settings_folder, "PackageSync.sublime-settings")
# Verify that user setting are present before backing up
if os.path.exists(packagesync_settings_original):
shutil.copy2(
packagesync_settings_original, packagesync_settings_backup)
tools.log("PackageSync: PackageSync.sublime-settings backed up to %s" %
packagesync_settings_backup, force=True)
if os.path.exists(tools.temp_restore_folder):
shutil.rmtree(tools.temp_restore_folder, True)
# Copy to temp restore folder & restore as per the preserve
# setting
shutil.copytree(backup_path, tools.temp_restore_folder)
offline.restore_from_temp()
# Restore PackageSync user settings if they were backed up
if os.path.exists(packagesync_settings_backup) and not os.path.exists(packagesync_settings_original):
shutil.copy2(
packagesync_settings_backup, packagesync_settings_original)
tools.log("PackageSync: PackageSync.sublime-settings restored from %s" %
packagesync_settings_backup, force=True)
tools.install_new_packages()
except Exception as e:
tools.log(
"PackageSync: Error while restoring packages from folder", force=True)
tools.log("PackageSync: Error message: %s" % str(e), force=True)
else:
tools.packagesync_cancelled()
class PsyncLocalBackupZipCommand(sublime_plugin.WindowCommand):
# def is_enabled(self):
# return True
def run(self):
psync_settings = tools.get_psync_settings()
if psync_settings["prompt_for_location"] == False:
zip_backup_path = psync_settings["zip_backup_path"]
backup_path = None
try:
if zip_backup_path == "":
backup_path = tools.default_zip_backup_path
elif os.path.exists(zip_backup_path):
if sublime.ok_cancel_dialog(
"Backup already exists @ %s \nReplace it?" % zip_backup_path) == True:
os.remove(zip_backup_path)
backup_path = zip_backup_path
else:
backup_path = None
elif os.path.isabs(os.path.dirname(zip_backup_path)):
backup_path = zip_backup_path
else:
sublime.error_message(
"Invalid path provided in user-settings. Please correct & then retry.")
backup_path = None
except Exception as e:
tools.log("PackageSync: Error while fetching backup path.", force=True)
tools.log("PackageSync: Error message: %s" % str(e), force=True)
self.backup_zip(backup_path)
else:
offline.prompt_parameters = {
"mode": "backup",
"type": "file",
"window_context": self.window,
"initial_text": tools.default_zip_backup_path,
"operation_to_perform": self.backup_zip,
"on_change": None,
"on_cancel": tools.packagesync_cancelled
}
offline.prompt_for_location()
def backup_zip(self, backup_path):
if backup_path is not None:
try:
offline.create_temp_backup()
temp_zip_file_path = os.path.join(
tempfile.gettempdir(), str(time.time())) + ".zip"
# create temp backup zip from the temp backup
z = zipfile.ZipFile(temp_zip_file_path, 'w')
basePath = tools.temp_backup_folder.rstrip("\\/") + ""
basePath = basePath.rstrip("\\/")
for root, dirs, files in os.walk(tools.temp_backup_folder):
for item in (files + dirs):
itemPath = os.path.join(root, item)
inZipPath = itemPath.replace(
basePath, "", 1).lstrip("\\/")
z.write(itemPath, inZipPath)
# close the temp backup file
z.close()
if os.path.isfile(backup_path):
os.remove(backup_path)
elif not os.path.exists(os.path.dirname(backup_path)):
os.makedirs(os.path.dirname(backup_path))
shutil.move(temp_zip_file_path, backup_path)
tools.log("PackageSync: Zip backup of packages & settings created at %s" %
backup_path)
except Exception as e:
tools.log(
"PackageSync: Error while backing up packages to zip file", force=True)
tools.log("PackageSync: Error message: %s" % str(e), force=True)
else:
tools.packagesync_cancelled()
class PsyncLocalRestoreZipCommand(sublime_plugin.WindowCommand):
# def is_enabled(self):
# return True
def run(self):
psync_settings = tools.get_psync_settings()
if psync_settings["prompt_for_location"] == False:
zip_backup_path = psync_settings["zip_backup_path"]
backup_path = None
try:
if zip_backup_path == "":
backup_path = tools.default_zip_backup_path
elif os.path.isfile(zip_backup_path):
backup_path = zip_backup_path
else:
sublime.error_message(
"Invalid path provided in user-settings. Please correct & then retry.")
backup_path = None
except Exception as e:
tools.log("PackageSync: Error while fetching backup path.", force=True)
tools.log("PackageSync: Error message: %s" % str(e), force=True)
self.restore_zip(backup_path)
else:
offline.prompt_parameters = {
"mode": "restore",
"type": "file",
"window_context": self.window,
"initial_text": tools.default_zip_backup_path,
"operation_to_perform": self.restore_zip,
"on_change": None,
"on_cancel": tools.packagesync_cancelled
}
offline.prompt_for_location()
def restore_zip(self, backup_path):
if backup_path is not None:
try:
tools.log(
"PackageSync: Restoring package list & user settings from %s" % backup_path, force=True)
# Backup PackageSync user settings before restore operation
packagesync_settings_backup = os.path.join(
tempfile.gettempdir(), str(time.time()))
packagesync_settings_original = os.path.join(
tools.user_settings_folder, "PackageSync.sublime-settings")
# Verify that user setting are present before backing up
if os.path.exists(packagesync_settings_original):
shutil.copy2(
packagesync_settings_original, packagesync_settings_backup)
tools.log("PackageSync: PackageSync.sublime-settings backed up to %s" %
packagesync_settings_backup, force=True)
if os.path.exists(tools.temp_restore_folder):
shutil.rmtree(tools.temp_restore_folder, True)
# Extract to temp restore folder & then perform restore operation
# as per the preserve setting
#
# Sublime 2 has Python 2.6.9 as interpreter. So using with zipfile.ZipFile would not work
# Therefore explicitly open & close the zip file for operation
z = zipfile.ZipFile(backup_path, "r")
z.extractall(tools.temp_restore_folder)
z.close()
offline.restore_from_temp()
# Restore PackageSync user settings if they were backed up
if os.path.exists(packagesync_settings_backup) and not os.path.exists(packagesync_settings_original):
shutil.copy2(
packagesync_settings_backup, packagesync_settings_original)
tools.log("PackageSync: PackageSync.sublime-settings restored from %s" %
packagesync_settings_backup, force=True)
tools.install_new_packages()
except Exception as e:
tools.log(
"PackageSync: Error while restoring packages from zip file", force=True)
tools.log("PackageSync: Error message: %s" % str(e), force=True)
else:
tools.packagesync_cancelled()
class PsyncOnlineSyncEnableCommand(sublime_plugin.WindowCommand):
def is_enabled(self):
s = tools.get_psync_settings()
return not s.get("online_sync_enabled", False)
def run(self):
s = sublime.load_settings("PackageSync.sublime-settings")
s.set("online_sync_enabled", True)
sublime.save_settings("PackageSync.sublime-settings")
# Start watcher
tools.start_watcher(tools.get_psync_settings())
# Run online package syncing module
sublime.run_command("psync_online_sync", {"mode": ["pull", "push"]})
class PsyncOnlineSyncDisableCommand(sublime_plugin.WindowCommand):
def is_enabled(self):
s = tools.get_psync_settings()
return s.get("online_sync_enabled", False)
def run(self):
s = sublime.load_settings("PackageSync.sublime-settings")
s.set("online_sync_enabled", False)
sublime.save_settings("PackageSync.sublime-settings")
# Stop watcher
tools.stop_watcher()
class PsyncOnlineSyncCommand(sublime_plugin.ApplicationCommand):
def is_enabled(self):
s = tools.get_psync_settings()
return s.get("online_sync_enabled", False) and s.get("online_sync_folder", False) != False
def run(self, mode=["pull", "push"], override=False):
# Load settings
settings = sublime.load_settings("PackageSync.sublime-settings")
# Check for valid online_sync_folder
if not os.path.isdir(settings.get("online_sync_folder")):
sublime.error_message(
"Invalid path provided for online_sync_folder in PackageSync settings. Online syncing has been turned off. Please correct and retry.\n %s" % settings.get(
"online_sync_folder"))
settings.set("online_sync_enabled", False)
sublime.save_settings("PackageSync.sublime-settings")
return
# Check if sync is already running
if not sync_queue.has("sync_online"):
t = online.Sync(mode, override)
sync_queue.add(t, "sync_online")
else:
tools.log("PackageSync: Sync operation already running.", force=True)
class PsyncOnlinePullItemCommand(sublime_plugin.ApplicationCommand):
def is_enabled(self):
s = tools.get_psync_settings()
return s.get("online_sync_enabled", False) and s.get("online_sync_folder", False) and os.path.isdir(s.get("online_sync_folder"))
def run(self, item):
tools.log("PsyncOnlinePullItemCommand %s", item)
# Start a thread to pull the current item
t = online.Sync(mode=["pull"], item=item)
sync_queue.add(t)
class PsyncOnlinePushItemCommand(sublime_plugin.ApplicationCommand):
def is_enabled(self):
s = tools.get_psync_settings()
return s.get("online_sync_enabled", False) and s.get("online_sync_folder", False) and os.path.isdir(s.get("online_sync_folder"))
def run(self, item):
tools.log("PsyncOnlinePushItemCommand %s", item)
# Start a thread to push the current item
t = online.Sync(mode=["push"], item=item)
sync_queue.add(t)
class PsyncOnlineSyncFolderCommand(sublime_plugin.WindowCommand):
def is_enabled(self):
return not sync_queue.has("sync_online")
def run(self):
# Load settings to provide an initial value for the input panel
settings = sublime.load_settings("PackageSync.sublime-settings")
settings.clear_on_change("package_sync")
sublime.save_settings("PackageSync.sublime-settings")
sync_folder = settings.get("online_sync_folder")
# Suggest user dir if nothing set or folder do not exists
if not sync_folder:
sync_folder = os.path.expanduser("~")
def get_sync_folder_on_done(path):
if not os.path.isdir(path):
os.makedirs(path)
if os.path.isdir(path):
if os.listdir(path):
if sublime.ok_cancel_dialog("Backup already exists @ %s \nReplace it?" % path, "Continue"):
override = True
else:
self.window.show_input_panel(
"Online Sync Folder", path, get_sync_folder_on_done, None, tools.packagesync_cancelled)
return
else:
override = False
# Adjust settings
settings.set("online_sync_enabled", True)
settings.set("online_sync_folder", path)
# Reset last-run file for Package Control
last_run_file = os.path.join(
sublime.packages_path(), "User", "Package Control.last-run")
if os.path.isfile(last_run_file):
os.remove(last_run_file)
# Reset last-run file for PackageSync
last_run_file = os.path.join(
sublime.packages_path(), "User", "PackageSync.last-run")
if os.path.isfile(last_run_file):
os.remove(last_run_file)
sublime.save_settings("PackageSync.sublime-settings")
sublime.status_message(
"online_sync_folder has been set to \n %s" % path)
# Restart watcher
tools.pause_watcher(local=False)
tools.stop_watcher(local=False)
tools.start_watcher(tools.get_psync_settings(), local=False)
# Run pkg_sync
sublime.set_timeout(lambda: sublime.run_command(
"psync_online_sync", {"mode": ["pull", "push"], "override": override}), 1000)
else:
sublime.error_message("Invalid Path \n %s" % path)
# Add an on_change listener
sublime.set_timeout(
lambda: settings.add_on_change("package_sync", tools.restart_watcher), 500)
self.window.show_input_panel(
"Online Sync Folder", sync_folder, get_sync_folder_on_done, None, tools.packagesync_cancelled)
def plugin_loaded():
tools.init_paths()
s = sublime.load_settings("PackageSync.sublime-settings")
s.clear_on_change("package_sync")
s.add_on_change("package_sync", tools.restart_watcher)
sublime.save_settings("PackageSync.sublime-settings")
# Start watcher
sublime.set_timeout(
lambda: tools.start_watcher(tools.get_psync_settings()), 100)
# Run online package syncing
sublime.set_timeout(lambda: sublime.run_command(
"psync_online_sync", {"mode": ["pull", "push"]}), 1000)
def plugin_unloaded():
s = sublime.load_settings("PackageSync.sublime-settings")
s.clear_on_change("package_sync")
sublime.save_settings("PackageSync.sublime-settings")
# Stop folder watcher
tools.stop_watcher()
if sublime.version()[0] == "2":
plugin_loaded()