forked from NoxArt/SublimeText2-FTPSync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFTPSync.py
2517 lines (1895 loc) · 72.7 KB
/
FTPSync.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
# -*- coding: utf-8 -*-
# Copyright (c) 2012 Jiri "NoxArt" Petruzelka
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
# @author Jiri "NoxArt" Petruzelka | [email protected] | @NoxArt
# @copyright (c) 2012 Jiri "NoxArt" Petruzelka
# @link https://github.com/NoxArt/SublimeText2-FTPSync
# Doc comment syntax inspired by http://stackoverflow.com/a/487203/387503
# ==== Libraries ===========================================================================
# Sublime API see http://www.sublimetext.com/docs/2/api_reference.html
import sublime
import sublime_plugin
# Python's built-in libraries
import shutil
import os
import hashlib
import json
import threading
import re
import copy
import traceback
import sys
# FTPSync libraries
from ftpsyncwrapper import CreateConnection, TargetAlreadyExists
from ftpsyncprogress import Progress
from ftpsyncfiles import getFolders, findFile, getFiles, formatTimestamp, gatherMetafiles, getChangedFiles, replace
from ftpsyncworker import Worker
# exceptions
from ftpsyncexceptions import FileNotFoundException
# ==== Initialization and optimization =====================================================
# global config
settings = sublime.load_settings('FTPSync.sublime-settings')
# test settings
if settings.get('project_defaults') is None:
print "="*86
print "FTPSync > Error loading settings ... please restart Sublime Text 2 after installation"
print "="*86
# print debug messages to console?
isDebug = settings.get('debug')
# print overly informative messages?
isDebugVerbose = settings.get('debug_verbose')
# default config for a project
projectDefaults = settings.get('project_defaults').items()
nested = []
index = 0
for item in projectDefaults:
if type(item[1]) is dict:
nested.append(index)
index += 1
# global config key - for specifying global config in settings file
globalConfigKey = '__global'
# global ignore pattern
ignore = settings.get('ignore')
# time format settings
time_format = settings.get('time_format')
# delay before check of right opened file is performed, cancelled if closed in the meantime
download_on_open_delay = settings.get('download_on_open_delay')
# system notifications
systemNotifications = settings.get('system_notifications')
# loaded project's config will be merged with this global one
coreConfig = {
'ignore': ignore,
'connection_timeout': settings.get('connection_timeout'),
'ascii_extensions': settings.get('ascii_extensions'),
'binary_extensions': settings.get('binary_extensions')
}.items()
# compiled global ignore pattern
if type(ignore) is str or type(ignore) is unicode:
re_ignore = re.compile(ignore)
else:
re_ignore = None
# name of a file to be detected in the project
configName = 'ftpsync.settings'
# name of a file that is a default sheet for new configs for projects
connectionDefaultsFilename = 'ftpsync.default-settings'
# timeout for a Sublime status bar messages [ms]
messageTimeout = 250
# comment removing regexp
removeLineComment = re.compile('//.*', re.I)
# deprecated names
deprecatedNames = {
"check_time": "overwrite_newer_prevention"
}
# connection cache pool - all connections
connections = {}
# connections currently marked as {in use}
usingConnections = []
# individual folder config cache, file => config path
configs = {}
# scheduled delayed uploads, file_path => action id
scheduledUploads = {}
# limit of workers
workerLimit = settings.get('max_threads')
# debug workers?
debugWorkers = settings.get('debug_threads')
# overwrite cancelled
overwriteCancelled = []
# last navigation
navigateLast = {
'config_file': None,
'connection_name': None,
'path': None
}
displayPermissions = settings.get('browse_display_permission')
displayTimestampFormat = settings.get('browse_timestamp_format')
# last folder
re_thisFolder = re.compile("/([^/]*?)/?$", re.I)
re_parentFolder = re.compile("/([^/]*?)/[^/]*?/?$", re.I)
# ==== Generic =============================================================================
# Returns whether the variable is some form os string
def isString(var):
var_type = type(var)
return var_type is str or var_type is unicode
# Dumps the exception to console
def handleException(exception):
print "FTPSync > Exception in user code:"
print '-' * 60
traceback.print_exc(file=sys.stdout)
print '-' * 60
# Safer print of exception message
def stringifyException(exception):
return unicode(exception)
# Checks whether cerain package exists
def packageExists(packageName):
return os.path.exists(os.path.join(sublime.packages_path(), packageName))
# Returns global config
def getGlobalConfig(key, config):
if globalConfigKey in config and key in config[globalConfigKey]:
return config[globalConfigKey][key]
else:
return settings.get(key)
# ==== Messaging ===========================================================================
# Shows a message into Sublime's status bar
#
# @type text: string
# @param text: message to status bar
def statusMessage(text):
sublime.status_message(text)
# Schedules a single message to be logged/shown
#
# @type text: string
# @param text: message to status bar
#
# @global messageTimeout
def dumpMessage(text):
sublime.set_timeout(lambda: statusMessage(text), messageTimeout)
# Prints a special message to console and optionally to status bar
#
# @type text: string
# @param text: message to status bar
# @type name: string|None
# @param name: comma-separated list of connections or other auxiliary info
# @type onlyVerbose: boolean
# @param onlyVerbose: print only if config has debug_verbose enabled
# @type status: boolean
# @param status: show in status bar as well = true
#
# @global isDebug
# @global isDebugVerbose
def printMessage(text, name=None, onlyVerbose=False, status=False):
message = "FTPSync"
if name is not None:
message += " [" + unicode(name) + "]"
message += " > "
message += unicode(text)
if isDebug and (onlyVerbose is False or isDebugVerbose is True):
print message.encode('utf-8')
if status:
dumpMessage(message)
# Issues a system notification for certian event
#
# @type text: string
# @param text: notification message
def systemNotify(text):
try:
import subprocess
text = "FTPSync > " + text
if sys.platform == "darwin":
""" Run Grown Notification """
cmd = '/usr/local/bin/growlnotify -a "Sublime Text 2" -t "FTPSync message" -m "'+text+'"'
subprocess.call(cmd,shell=True)
elif sys.platform == "linux2":
subprocess.call('/usr/bin/notify-send "Sublime Text 2" "'+text+'"',shell=True)
elif sys.platform == "win32":
""" Find the notifaction platform for windows if there is one"""
except Exception, e:
printMessage("Notification failed")
handleExceptions(e)
# ==== Config =============================================================================
# Invalidates all config cache entries belonging to a certain directory
# as long as they're empty or less nested in the filesystem
#
# @type config_dir_name: string
# @param config_dir_name: path to a folder of a config to be invalidated
#
# @global configs
def invalidateConfigCache(config_dir_name):
for file_path in configs:
if file_path.startswith(config_dir_name) and (configs[file_path] is None or config_dir_name.startswith(configs[file_path])):
configs.remove(configs[file_path])
# Finds a config file in given folders
#
# @type folders: list<string>
# @param folders: list of paths to folders to filter
#
# @return list<string> of file paths
#
# @global configName
def findConfigFile(folders):
return findFile(folders, configName)
# Returns configuration file for a given file
#
# @type file_path: string
# @param file_path: file_path to the file for which we try to find a config
#
# @return file path to the config file or None
#
# @global configs
def getConfigFile(file_path):
# try cached
try:
if configs[file_path]:
printMessage("Loading config: cache hit (key: " + file_path + ")")
return configs[file_path]
# cache miss
except KeyError:
try:
folders = getFolders(file_path)
if folders is None or len(folders) == 0:
return None
configFolder = findConfigFile(folders)
if configFolder is None:
printMessage("Found no config for {" + file_path + "}")
return None
config = os.path.join(configFolder, configName)
configs[file_path] = config
return config
except AttributeError:
return None
# Returns hash of file_path
#
# @type file_path: string
# @param file_path: file path to the file of which we want the hash
#
# @return hash of filepath
def getFilepathHash(file_path):
return hashlib.md5(file_path.encode('utf-8')).hexdigest()
# Returns path of file from its config file
#
# @type file_path: string
# @param file_path: file path to the file of which we want the hash
#
# @return string file path from settings root
def getRootPath(file_path, prefix = ''):
return prefix + os.path.relpath(file_path, os.path.dirname(getConfigFile(file_path))).replace('\\', '/')
# Returns a file path associated with view
#
# @type file_path: string
# @param file_path: file path to the file of which we want the hash
#
# @return string file path
def getFileName(view):
file_path = view.file_name()
#if file_path is not None:
# file_path = file_path.encode('utf-8')
return file_path
# Gathers all entries from selected paths
#
# @type file_path: list<string>
# @param file_path: list of file/folder paths
#
# @return list of file/folder paths
def gatherFiles(paths):
syncFiles = []
fileNames = []
for target in paths:
if os.path.isfile(target):
if target not in fileNames:
fileNames.append(target)
syncFiles.append([target, getConfigFile(target)])
elif os.path.isdir(target):
empty = True
for root, dirs, files in os.walk(target):
for file_path in files:
empty = False
if file_path not in fileNames:
fileNames.append(target)
syncFiles.append([os.path.join(root, file_path), getConfigFile(os.path.join(root, file_path))])
for folder in dirs:
path = os.path.join(root, folder)
if not os.listdir(path) and path not in fileNames:
fileNames.append(path)
syncFiles.append([path, getConfigFile(path)])
if empty is True:
syncFiles.append([target, getConfigFile(target)])
return syncFiles
# Returns hash of configuration contents
#
# @type config: dict
#
# @return string
#
# @link http://stackoverflow.com/a/8714242/387503
def getObjectHash(o):
if isinstance(o, set) or isinstance(o, tuple) or isinstance(o, list):
return tuple([getObjectHash(e) for e in o])
elif not isinstance(o, dict):
return hash(o)
new_o = copy.deepcopy(o)
for k, v in new_o.items():
new_o[k] = getObjectHash(v)
return hash(tuple(frozenset(new_o.items())))
# Updates deprecated config to newer version
#
# @type config: dict
#
# @return dict (config)
#
# @global deprecatedNames
def updateConfig(config):
for old_name in deprecatedNames:
new_name = deprecatedNames[old_name]
if new_name in config:
config[old_name] = config[new_name]
elif old_name in config:
config[new_name] = config[old_name]
return config
# Verifies contents of a given config object
#
# Checks that it's an object with all needed keys of a proper type
# Does not check semantic validity of the content
#
# Should be used on configs merged with the defaults
#
# @type config: dict
# @param config: config dict
#
# @return string verification fail reason or a boolean
def verifyConfig(config):
if type(config) is not dict:
return "Config is not a {dict} type"
keys = ["username", "password", "private_key", "private_key_pass", "path", "encoding", "tls", "use_tempfile", "upload_on_save", "port", "timeout", "ignore", "check_time", "download_on_open", "upload_delay", "after_save_watch", "time_offset", "set_remote_lastmodified", "default_folder_permissions", "default_local_permissions", "always_sync_local_permissions"]
for key in keys:
if key not in config:
return "Config is missing a {" + key + "} key"
if config['username'] is not None and isString(config['username']) is False:
return "Config entry 'username' must be null or string, " + unicode(type(config['username'])) + " given"
if config['password'] is not None and isString(config['password']) is False:
return "Config entry 'password' must be null or string, " + unicode(type(config['password'])) + " given"
if config['private_key'] is not None and isString(config['private_key']) is False:
return "Config entry 'private_key' must be null or string, " + unicode(type(config['private_key'])) + " given"
if config['private_key_pass'] is not None and isString(config['private_key_pass']) is False:
return "Config entry 'private_key_pass' must be null or string, " + unicode(type(config['private_key_pass'])) + " given"
if config['ignore'] is not None and isString(config['ignore']) is False:
return "Config entry 'ignore' must be null or string, " + unicode(type(config['ignore'])) + " given"
if isString(config['path']) is False:
return "Config entry 'path' must be a string, " + unicode(type(config['path'])) + " given"
if config['encoding'] is not None and isString(config['encoding']) is False:
return "Config entry 'encoding' must be a string, " + unicode(type(config['encoding'])) + " given"
if type(config['tls']) is not bool:
return "Config entry 'tls' must be true or false, " + unicode(type(config['tls'])) + " given"
if type(config['passive']) is not bool:
return "Config entry 'passive' must be true or false, " + unicode(type(config['passive'])) + " given"
if type(config['use_tempfile']) is not bool:
return "Config entry 'use_tempfile' must be true or false, " + unicode(type(config['use_tempfile'])) + " given"
if type(config['set_remote_lastmodified']) is not bool:
return "Config entry 'set_remote_lastmodified' must be true or false, " + unicode(type(config['set_remote_lastmodified'])) + " given"
if type(config['upload_on_save']) is not bool:
return "Config entry 'upload_on_save' must be true or false, " + unicode(type(config['upload_on_save'])) + " given"
if type(config['check_time']) is not bool:
return "Config entry 'check_time' must be true or false, " + unicode(type(config['check_time'])) + " given"
if type(config['download_on_open']) is not bool:
return "Config entry 'download_on_open' must be true or false, " + unicode(type(config['download_on_open'])) + " given"
if type(config['upload_delay']) is not int and type(config['upload_delay']) is not long:
return "Config entry 'upload_delay' must be integer or long, " + unicode(type(config['upload_delay'])) + " given"
if config['after_save_watch'] is not None and type(config['after_save_watch']) is not list:
return "Config entry 'after_save_watch' must be null or list, " + unicode(type(config['after_save_watch'])) + " given"
if type(config['port']) is not int and type(config['port']) is not long:
return "Config entry 'port' must be an integer or long, " + unicode(type(config['port'])) + " given"
if type(config['timeout']) is not int and type(config['timeout']) is not long:
return "Config entry 'timeout' must be an integer or long, " + unicode(type(config['timeout'])) + " given"
if type(config['time_offset']) is not int and type(config['time_offset']) is not long:
return "Config entry 'time_offset' must be an integer or long, " + unicode(type(config['time_offset'])) + " given"
return True
# Parses JSON-type file with comments stripped out (not part of a proper JSON, see http://json.org/)
#
# @type file_path: string
#
# @return dict
#
# @global removeLineComment
def parseJson(file_path):
contents = ""
try:
file = open(file_path, 'r')
for line in file:
contents += removeLineComment.sub('', line)
finally:
file.close()
return json.loads(contents)
# Parses given config and adds default values to each connection entry
#
# @type file_path: string
# @param file_path: file path to the file of which we want the hash
#
# @return config dict or None
#
# @global coreConfig
# @global projectDefaults
def loadConfig(file_path):
if os.path.exists(file_path) is False:
return None
# parse config
try:
config = parseJson(file_path)
except Exception, e:
printMessage("Failed parsing configuration file: {" + file_path + "} (commas problem?) [Exception: " + stringifyException(e) + "]", status=True)
handleException(e)
return None
result = {}
# merge with defaults and check
for name in config:
if type(config[name]) is not dict:
printMessage("Failed using configuration: contents are not dictionaries but values", status=True)
return None
if name == globalConfigKey:
continue
result[name] = dict(projectDefaults + config[name].items())
result[name]['file_path'] = file_path
# merge nested
for index in nested:
result[name][projectDefaults[index][0]] = dict(projectDefaults[index][1].items() + result[name][projectDefaults[index][0]].items())
try:
if result[name]['debug_extras']['dump_config_load'] is True:
printMessage(result[name])
except KeyError:
pass
result[name] = updateConfig(result[name])
verification_result = verifyConfig(result[name])
if verification_result is not True:
printMessage("Invalid configuration loaded: <" + unicode(verification_result) + ">", status=True)
# merge with generics
final = dict(coreConfig + {"connections": result}.items())
# replace global config by
return final
# ==== Remote =============================================================================
# Creates a new connection
#
# @type config: object
# @param config: configuration object
# @type hash: string
# @param hash: connection cache hash (config filepath hash actually)
#
# @return list of descendants of AbstractConnection (ftpsyncwrapper.py)
def makeConnection(config, hash=None, handleExceptions=True):
result = []
# for each config
for name in config['connections']:
properties = config['connections'][name]
# 1. initialize
try:
connection = CreateConnection(config, name)
except Exception, e:
if handleExceptions is False:
raise
printMessage("Connection initialization failed [Exception: " + stringifyException(e) + "]", name, status=True)
handleException(e)
return []
# 2. connect
try:
connection.connect()
except Exception, e:
if handleExceptions is False:
raise
printMessage("Connection failed [Exception: " + stringifyException(e) + "]", name, status=True)
connection.close(connections, hash)
handleException(e)
return []
printMessage("Connected to: " + properties['host'] + ":" + unicode(properties['port']) + " (timeout: " + unicode(properties['timeout']) + ") (key: " + unicode(hash) + ")", name)
# 3. authenticate
try:
if connection.authenticate():
printMessage("Authentication processed", name)
except Exception, e:
if handleExceptions is False:
raise
printMessage("Authentication failed [Exception: " + stringifyException(e) + "]", name, status=True)
handleException(e)
return []
# 4. login
if properties['username'] is not None:
try:
connection.login()
except Exception, e:
if handleExceptions is False:
raise
printMessage("Login failed [Exception: " + stringifyException(e) + "]", name, status=True)
handleException(e)
return []
pass_present = " (using password: NO)"
if len(properties['password']) > 0:
pass_present = " (using password: YES)"
printMessage("Logged in as: " + properties['username'] + pass_present, name)
else:
printMessage("Anonymous connection", name)
# 5. set initial directory, set name, store connection
try:
connection.cwd(properties['path'])
except Exception, e:
if handleExceptions is False:
raise
printMessage("Failed to set path (probably connection failed) [Exception: " + stringifyException(e) + "]", name)
handleException(e)
return []
# 6. add to connections list
present = False
for con in result:
if con.name == connection.name:
present = True
if present is False:
result.append(connection)
return result
# Returns connection, connects if needed
#
# @type hash: string
# @param hash: connection cache hash (config filepath hash actually)
# @type config: object
# @param config: configuration object
# @type shared: bool
# @param shared: whether to use shared connection
#
# @return list of descendants of AbstractConnection (ftpsyncwrapper.py)
#
# @global connections
def getConnection(hash, config, shared=True):
if shared is False:
return makeConnection(config, hash)
# try cache
try:
if connections[hash] and len(connections[hash]) > 0:
printMessage("Connection cache hit (key: " + hash + ")", None, True)
if type(connections[hash]) is not list or len(connections[hash]) < len(config['connections']):
raise KeyError
# has config changed?
valid = True
index = 0
for name in config['connections']:
if getObjectHash(connections[hash][index].config) != getObjectHash(config['connections'][name]):
valid = False
index += 1
if valid == False:
for connection in connections[hash]:
connection.close(connections, hash)
raise KeyError
# is config truly alive
for connection in connections[hash]:
if connection.isAlive() is False:
raise KeyError
return connections[hash]
# cache miss
except KeyError:
connections[hash] = makeConnection(config, hash)
# schedule connection timeout
def closeThisConnection():
if hash not in usingConnections:
closeConnection(hash)
else:
sublime.set_timeout(closeThisConnection, config['connection_timeout'] * 1000)
sublime.set_timeout(closeThisConnection, config['connection_timeout'] * 1000)
# return all connections
return connections[hash]
# Close all connections for a given config file
#
# @type hash: string
# @param hash: connection cache hash (config filepath hash actually)
#
# @global connections
def closeConnection(hash):
if isString(hash) is False:
printMessage("Error closing connection: connection hash must be a string, " + unicode(type(hash)) + " given")
return
if hash not in connections:
return
try:
for connection in connections[hash]:
connection.close(connections, hash)
printMessage("closed", connection.name)
if len(connections[hash]) == 0:
connections.pop(hash)
except Exception, e:
printMessage("Error when closing connection (key: " + hash + ") [Exception: " + stringifyException(e) + "]")
handleException(e)
# Creates a process message with progress bar (to be used in status bar)
#
# @type stored: list<string>
# @param stored: usually list of connection names
# @type progress: Progress
# @type action: string
# @type action: action that the message reports about ("uploaded", "downloaded"...)
# @type basename: string
# @param basename: name of a file connected with the action
#
# @return string message
def getProgressMessage(stored, progress, action, basename = None):
base = "FTPSync [remotes: " + ",".join(stored) + "] "
action = "> " + action + " "
if progress is not None:
base += " ["
percent = progress.getPercent()
for i in range(0, int(percent)):
base += "="
for i in range(int(percent), 20):
base += "--"
base += " " + unicode(progress.current) + "/" + unicode(progress.getTotal()) + "] "
base += action
if basename is not None:
base += " {" + basename + "}"
return base
# Returns a new worker
def createWorker():
queue = Worker(workerLimit, makeConnection, loadConfig)
if debugWorkers and isDebug:
queue.enableDebug()
return queue
# ==== Executive functions ======================================================================
class SyncObject(object):
def __init__(self):
self.onFinish = []
def addOnFinish(self, callback):
if hasattr(self, 'onFinish') is False:
self.onFinish = []
self.onFinish.append(callback)
return self
def triggerFinish(self, args):
for finish in self.onFinish:
if finish is not None:
finish(args)
# Generic synchronization command
class SyncCommand(SyncObject):
def __init__(self, file_path, config_file_path):
SyncObject.__init__(self)
self.running = True
self.closed = False
self.ownConnection = False
self.file_path = file_path
self.config_file_path = config_file_path
if isString(config_file_path) is False:
printMessage("Cancelling " + unicode(self.__class__.__name__) + ": invalid config_file_path given (type: " + unicode(type(config_file_path)) + ")")
self.close()
return
if os.path.exists(config_file_path) is False:
printMessage("Cancelling " + unicode(self.__class__.__name__) + ": config_file_path: No such file")
self.close()
return
self.config = loadConfig(config_file_path)
if file_path is not None:
self.basename = os.path.relpath(file_path, os.path.dirname(config_file_path))
self.config_hash = getFilepathHash(self.config_file_path)
self.connections = None
self.worker = None
def setWorker(self, worker):
self.worker = worker
def setConnection(self, connections):
self.connections = connections
self.ownConnection = False
def _createConnection(self):
if self.connections is None:
self.connections = getConnection(self.config_hash, self.config, False)
self.ownConnection = True
def _localizePath(self, config, remote_path):
path = remote_path
if path.find(config['path']) == 0:
path = os.path.abspath(os.path.join(os.path.dirname(self.config_file_path), remote_path[len(config['path']):]))
return path
def execute(self):
raise NotImplementedError("Abstract method")
def close(self):
self.closed = True
def _closeConnection(self):
closeConnection(getFilepathHash(self.config_file_path))
def whitelistConnections(self, whitelistConnections):
toBeRemoved = []
for name in self.config['connections']:
if name not in whitelistConnections:
toBeRemoved.append(name)
for name in toBeRemoved:
self.config['connections'].pop(name)
return self
def isRunning(self):
return self.running
def __del__(self):
self.running = False
if hasattr(self, 'config_hash') and self.config_hash in usingConnections:
usingConnections.remove(self.config_hash)
if hasattr(self, 'ownConnection'):
if self.ownConnection:
for connection in self.connections:
if isDebug:
printMessage("Closing connection")
connection.close()
elif hasattr(self, 'worker') and self.worker is not None:
self.worker = None
# Transfer-related sychronization command
class SyncCommandTransfer(SyncCommand):
def __init__(self, file_path, config_file_path, progress=None, onSave=False, disregardIgnore=False, whitelistConnections=[], forcedSave=False):
self.progress = progress
# global ignore
if disregardIgnore is False and ignore is not None and re_ignore.search(file_path) is not None:
printMessage("file globally ignored: {" + os.path.basename(file_path) + "}", onlyVerbose=True)
self.closed = True
return
SyncCommand.__init__(self, file_path, config_file_path)
self.onSave = onSave
self.disregardIgnore = False
self.local = True
toBeRemoved = []
for name in self.config['connections']:
# on save
if self.config['connections'][name]['upload_on_save'] is False and onSave is True and forcedSave is False:
toBeRemoved.append(name)
continue
# ignore
if disregardIgnore is False and self.config['connections'][name]['ignore'] is not None and re.search(self.config['connections'][name]['ignore'], file_path):
printMessage("file ignored by rule: {" + self.basename + "}", name, True)
toBeRemoved.append(name)
continue
# whitelist
if len(whitelistConnections) > 0 and name not in whitelistConnections:
toBeRemoved.append(name)
continue
for name in toBeRemoved:
self.config['connections'].pop(name)
def setRemote(self):
self.local = False
return self
def getConnectionsApplied(self):
return self.config['connections']
# Upload command
class SyncCommandUpload(SyncCommandTransfer):
def __init__(self, file_path, config_file_path, progress=None, onSave=False, disregardIgnore=False, whitelistConnections=[], forcedSave=False):
SyncCommandTransfer.__init__(self, file_path, config_file_path, progress, onSave, disregardIgnore, whitelistConnections, forcedSave)