-
Notifications
You must be signed in to change notification settings - Fork 65
/
FTPSync.py
3378 lines (2579 loc) · 98.3 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 Text 2 API: see http://www.sublimetext.com/docs/2/api_reference.html
# Sublime Text 3 API: see http://www.sublimetext.com/docs/3/api_reference.html
import sublime
import sublime_plugin
# Python's built-in libraries
import copy
import hashlib
import os
import re
import shutil
import sys
import threading
import traceback
import webbrowser
from time import sleep
# FTPSync libraries
if sys.version < '3':
import lib2.simplejson as json
from ftpsynccommon import Types
from ftpsyncwrapper import CreateConnection, TargetAlreadyExists
from ftpsyncprogress import Progress
from ftpsyncfiles import getFolders, findFile, getFiles, formatTimestamp, gatherMetafiles, replace, addLinks, fileToMetafile
from ftpsyncworker import Worker
from ftpsyncfilewatcher import FileWatcher
# exceptions
from ftpsyncexceptions import FileNotFoundException
else:
import FTPSync.lib3.simplejson as json
from FTPSync.ftpsynccommon import Types
from FTPSync.ftpsyncwrapper import CreateConnection, TargetAlreadyExists
from FTPSync.ftpsyncprogress import Progress
from FTPSync.ftpsyncfiles import getFolders, findFile, getFiles, formatTimestamp, gatherMetafiles, replace, addLinks, fileToMetafile
from FTPSync.ftpsyncworker import Worker
from FTPSync.ftpsyncfilewatcher import FileWatcher
# exceptions
from FTPSync.ftpsyncexceptions import FileNotFoundException
# ==== Initialization and optimization =====================================================
__dir__ = os.path.dirname(os.path.realpath(__file__))
isLoaded = False
isDebug = True
# print overly informative messages?
isDebugVerbose = True
# default config for a project
projectDefaults = {}
nested = []
index = 0
# global config key - for specifying global config in settings file
globalConfigKey = '__global'
ignore = False
# time format settings
timeFormat = ""
# delay before check of right opened file is performed, cancelled if closed in the meantime
downloadOnOpenDelay = 0
coreConfig = {}
browseConfig = {}
# 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 = []
# root check cache
rootCheckCache = {}
# individual folder config cache, file => config path
configs = {}
# scheduled delayed uploads, file_path => action id
scheduledUploads = {}
# limit of workers
workerLimit = 0
# debug workers?
debugWorkers = False
# debug json?
debugJson = False
# overwrite cancelled
overwriteCancelled = []
# last navigation
navigateLast = {
'config_file': None,
'connection_name': None,
'path': None
}
displayDetails = False
displayPermissions = False
displayTimestampFormat = False
# last folder
re_thisFolder = re.compile("/([^/]*?)/?$", re.I)
re_parentFolder = re.compile("/([^/]*?)/[^/]*?/?$", re.I)
# watch pre-scan
preScan = {}
# temporarily remembered passwords
#
# { settings_filepath => { connection_name => password }, ... }
passwords = {}
# Overriding config for on-the-fly modifications
overridingConfig = {}
def isString(var):
var_type = type(var)
if sys.version[0] == '3':
return var_type is str or var_type is bytes
else:
return var_type is str or var_type is unicode
def plugin_loaded():
global browseConfig
global coreConfig
global debugJson
global debugWorkers
global displayDetails
global displayPermissions
global displayTimestampFormat
global downloadOnOpenDelay
global ignore
global index
global isDebug
global isDebugVerbose
global isLoaded
global nested
global projectDefaults
global re_ignore
global settings
global systemNotifications
global timeFormat
global workerLimit
# 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 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')
index = 0
for item in projectDefaults.items():
if type(item[1]) is dict:
nested.append(index)
index += 1
# global ignore pattern
ignore = settings.get('ignore')
# time format settings
timeFormat = settings.get('time_format')
# delay before check of right opened file is performed, cancelled if closed in the meantime
downloadOnOpenDelay = settings.get('download_on_open_delay')
# system notifications
systemNotifications = settings.get('system_notifications')
# compiled global ignore pattern
if isString(ignore):
re_ignore = re.compile(ignore)
else:
re_ignore = None
# loaded project's config will be merged with this global one
coreConfig = {
'ignore': ignore,
'debug_verbose': settings.get('debug_verbose'),
'ftp_retry_limit': settings.get('ftp_retry_limit'),
'ftp_retry_delay': settings.get('ftp_retry_delay'),
'connection_timeout': settings.get('connection_timeout'),
'ascii_extensions': settings.get('ascii_extensions'),
'binary_extensions': settings.get('binary_extensions')
}
browseConfig = {
'browse_display_details': settings.get('browse_display_details'),
'browse_open_on_download': settings.get('browse_open_on_download'),
'browse_display_permission': settings.get('browse_display_permission'),
'browse_timestamp_format': settings.get('browse_timestamp_format'),
'browse_folder_prefix': settings.get('browse_folder_prefix'),
'browse_folder_suffix': settings.get('browse_folder_suffix'),
'browse_file_prefix': settings.get('browse_file_prefix'),
'browse_file_suffix': settings.get('browse_file_suffix'),
'browse_up': settings.get('browse_up'),
'browse_action_prefix': settings.get('browse_action_prefix')
}
# limit of workers
workerLimit = settings.get('max_threads')
# debug workers?
debugWorkers = settings.get('debug_threads')
# debug json?
debugJson = settings.get('debug_json')
# browsing
displayDetails = settings.get('browse_display_details')
displayPermissions = settings.get('browse_display_permission')
displayTimestampFormat = settings.get('browse_timestamp_format')
isLoaded = True
if isDebug:
print ('FTPSync > plugin async loaded')
if int(sublime.version()) < 3000:
plugin_loaded()
# ==== Generic =============================================================================
# Returns file with syntax for settings file
def getConfigSyntax():
return 'Packages/FTPSync/Settings.tmLanguage'
# Returns if Sublime has currently active View
#
# ST3 on no opened view returns a View with empty file_name (wtf)
#
# @return boolean
def hasActiveView():
window = sublime.active_window()
if window is None:
return False
view = window.active_view()
if view is None or view.file_name() is None:
return False
return True
# 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 str(exception)
# Checks whether cerain package exists
def packageExists(packageName):
return os.path.exists(os.path.join(sublime.packages_path(), packageName))
def decode(string):
if hasattr('x', 'decode') and callable(getattr('x', 'decode')):
return string.decode('utf-8')
else:
return string
# ==== 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 += " [" + name + "]"
message += " > "
message += 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 as e:
printMessage("Notification failed")
handleExceptions(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 += " " + str(progress.current) + "/" + str(progress.getTotal()) + "] "
base += action
if basename is not None:
base += " {" + basename + "}"
return base
# ==== Config =============================================================================
# Alters override config
#
# @type config_dir_name: string
# @param config_dir_name: path to a folder of a config
# @type property: string
# @param property: property to be modified
# @type value: mixed
# @type specificName: string
# @param specificName: use to only modify specific connection's value
#
# @global overrideConfig
def overrideConfig(config_file_path, property, value, specificName=None):
if config_file_path is None or os.path.exists(config_file_path) is False:
return
config = loadConfig(config_file_path)
if config_file_path not in overridingConfig:
overridingConfig[config_file_path] = { 'connections': {} }
for name in config['connections']:
if specificName and name != specificName:
continue
if name not in overridingConfig[config_file_path]['connections']:
overridingConfig[config_file_path]['connections'][name] = {}
overridingConfig[config_file_path]['connections'][name][property] = value
# 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 first found config file from folders
#
# @type folders: list<string>
# @param folders: list of paths to folders to search in
#
# @return config filepath
def guessConfigFile(folders):
for folder in folders:
config = getConfigFile(folder)
if config is not None:
return config
for folder in os.walk(folder):
config = getConfigFile(folder[0])
if config is not None:
return config
return None
# 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):
cacheKey = file_path
if isString(cacheKey) is False:
cacheKey = cacheKey.decode('utf-8')
# try cached
try:
if configs[cacheKey] and os.path.exists(configs[cacheKey]) and os.path.getsize(configs[cacheKey]) > 0:
printMessage("Loading config: cache hit (key: " + cacheKey + ")")
return configs[cacheKey]
else:
raise KeyError
# 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 {" + cacheKey + "}", None, True)
return None
config = os.path.join(configFolder, configName)
configs[cacheKey] = 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):
return view.file_name()
# 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, " + str(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, " + str(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, " + str(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, " + str(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, " + str(type(config['ignore'])) + " given"
if isString(config['path']) is False:
return "Config entry 'path' must be a string, " + str(type(config['path'])) + " given"
if config['encoding'] is not None and isString(config['encoding']) is False:
return "Config entry 'encoding' must be a string, " + str(type(config['encoding'])) + " given"
if type(config['tls']) is not bool:
return "Config entry 'tls' must be true or false, " + str(type(config['tls'])) + " given"
if type(config['passive']) is not bool:
return "Config entry 'passive' must be true or false, " + str(type(config['passive'])) + " given"
if type(config['use_tempfile']) is not bool:
return "Config entry 'use_tempfile' must be true or false, " + str(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, " + str(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, " + str(type(config['upload_on_save'])) + " given"
if type(config['check_time']) is not bool:
return "Config entry 'check_time' must be true or false, " + str(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, " + str(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, " + str(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, " + str(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, " + str(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, " + str(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, " + str(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|None
#
# @global removeLineComment
def parseJson(file_path):
attempts = 3
succeeded = False
while attempts > 0:
attempts = attempts - 1
try:
json = parseJsonInternal(file_path)
if debugJson:
printMessage("Type returned: " + str(type(json)))
printMessage("Is empty: " + str(bool(json)))
succeeded = type(json) is dict and bool(json) is True
break
except Exception as e:
handleException(e)
printMessage("Retrying reading config... (remaining " + str(attempts) + ")")
sleep(0.1)
if succeeded:
return json
else:
printMessage("Failed to read settings from file: " + str(file_path))
return {}
# 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 parseJsonInternal(file_path):
if isString(file_path) is False:
raise Exception("Expected filepath as string, " + str(type(file_path)) + " given")
if os.path.exists(file_path) is False:
raise IOError("File " + str(file_path) + " does not exist")
if os.path.getsize(file_path) == 0:
raise IOError("File " + str(file_path) + " is empty")
contents = ""
try:
file = open(file_path, 'r')
for line in file:
contents += removeLineComment.sub('', line).strip()
finally:
file.close()
decoder = json.JSONDecoder()
if debugJson:
printMessage("Debug JSON:")
print ("="*86)
print (contents)
print ("="*86)
if len(contents) > 0:
return decoder.decode(contents)
else:
raise IOError('Content read from ' + str(file_path) + ' is empty')
# Asks for passwords if missing in configuration
#
# @type config_file_path: string
# @type config: dict
# @param config: configuration object
# @type callback: callback
# @param callback: what should be done after config is filled
# @type window: Window
# @param window: SublimeText2 API Window object
#
# @global passwords
def addPasswords(config_file_path, config, callback, window):
def setPassword(config, name, password):
config['connections'][name]['password'] = password
if config_file_path not in passwords:
passwords[config_file_path] = {}
passwords[config_file_path][name] = password
addPasswords(config_file_path, config, callback, window)
def ask(connectionName, host, username):
window.show_input_panel('FTPSync > please provide password for: ' + str(host) + ' ~ ' + str(username), "", lambda password: setPassword(config, connectionName, password), None, None)
if type(config) is dict:
for name in config['connections']:
prop = config['connections'][name]
if prop['password'] is None:
if config_file_path in passwords and name in passwords[config_file_path] and passwords[config_file_path][name] is not None:
config['connections'][name]['password'] = passwords[config_file_path][name]
else:
ask(name, prop['host'], prop['username'])
return
return callback()
# Fills passwords if missing in configuration
#
# @type fileList: [ [ filepath, config_file_path ], ... ]
# @type callback: callback
# @param callback: what should be done after config is filled
# @type window: Window
# @param window: SublimeText2 API Window object
#
# @global passwords
def fillPasswords(fileList, callback, window, index = 0):
def ask():
fillPasswords(fileList, callback, window, index + 1)
i = 0
length = len(fileList)
if index >= length:
callback(fileList)
return
config_files = []
for filepath, config_file_path in fileList:
if config_file_path not in config_files:
config_files.append(config_file_path)
for config_file_path in config_files:
if i < index:
i = i + 1
continue
if config_file_path is None:
continue
config = loadConfig(config_file_path)
if config is not None:
addPasswords(config_file_path, config, ask, window)
return
callback(fileList)
# 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 isLoaded
# @global coreConfig
# @global projectDefaults
def loadConfig(file_path):
if isLoaded is False:
printMessage("FTPSync is not loaded (just installed?), please restart Sublime Text")
return None
if isString(file_path) is False:
printMessage("LoadConfig expects string, " + str(type(file_path)) + " given")
return None
if os.path.exists(file_path) is False:
return None
# parse config
try:
config = parseJson(file_path)
except Exception as 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
result[name] = dict(list(projectDefaults.items()) + list(config[name].items()))
result[name]['file_path'] = file_path
# fix path
if len(result[name]['path']) > 1 and result[name]['path'][-1] != "/":
result[name]['path'] = result[name]['path'] + "/"
# merge nested
for index in nested:
list1 = list(list(projectDefaults.items())[index][1].items())
list2 = list(result[name][list(projectDefaults.items())[index][0]].items())
result[name][list(projectDefaults.items())[index][0]] = dict(list1 + list2)
try:
if result[name]['debug_extras']['dump_config_load'] is True:
print(result[name])
except KeyError:
pass
# add passwords
if file_path in passwords and name in passwords[file_path] and passwords[file_path][name] is not None:
result[name]['password'] = passwords[file_path][name]
result[name] = updateConfig(result[name])
verification_result = verifyConfig(result[name])
if verification_result is not True:
printMessage("Invalid configuration loaded: <" + str(verification_result) + ">", status=True)
# merge with generics
final = dict(list(coreConfig.items()) + list({"connections": result}.items()))
# override by overridingConfig
if file_path in overridingConfig:
for name in overridingConfig[file_path]['connections']:
if name in final['connections']:
for item in overridingConfig[file_path]['connections'][name]:
final['connections'][name][item] = overridingConfig[file_path]['connections'][name][item]
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 as e:
if handleExceptions is False:
raise
printMessage("Connection initialization failed [Exception: " + stringifyException(e) + "]", name, status=True)
handleException(e)
return []