-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSyncFileYouWant.py
More file actions
587 lines (463 loc) · 23 KB
/
SyncFileYouWant.py
File metadata and controls
587 lines (463 loc) · 23 KB
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
import shutil
import sublime
import sublime_plugin
import os
import difflib
sbs_markedSelection = [ '', '' ]
sbs_files = []
class SyncFileCommand(sublime_plugin.TextCommand):
def run(self, edit, inputFile=None):
settings = sublime.load_settings('SyncFile.sublime-settings')
src_mappings = settings.get("mappings", [])
mappings = []
# Check if we have the correct value type
if not isinstance(src_mappings, list):
print("invalid value type, should be a list: %r" % src_mappings)
return
for mapping in src_mappings:
# Check if we have the correct value types for the mappings
if not isinstance(mapping, dict):
print("invalid mapping type, should be a dict: %r" % mapping)
continue
# Check if required keys exist
elif not all(name in mapping for name in ('source', 'dest')):
print("required key(s) missing: %r" % mapping)
continue
# Check if required keys have correct value type
elif not isinstance(mapping['source'], str) or not isinstance(mapping['dest'], str):
print("invalid type for required key(s), should be str: %r" % mapping)
continue
# Check if required keys are not empty
elif not mapping['source'] or not mapping['dest']:
print("required key(s) empty: %r" % mapping)
continue
else:
mappings.append(mapping)
# Check if there are valid mappings
if not mappings:
print("No valid mappings found")
return
if inputFile == None:
source_name = self.view.file_name()
else:
source_name = inputFile
found = False
for mapping in mappings:
if mapping['source'] in source_name:
shutil.copyfile(source_name, source_name.replace(mapping['source'], mapping['dest']))
found = True
if found == True:
return
else:
msg = 'Your current file location is not in one of your source locations '
msg += 'or the relevant dest location is empty. '
msg += 'Please set the settings file properly and retry.'
sublime.error_message(msg)
class SyncMultipleFileCommand(sublime_plugin.WindowCommand):
def run(self, files):
if files != None and isinstance(files, list) and len(files) > 0:
for f in files:
self.window.active_view().run_command('sync_file', {'inputFile': f })
class DiffWithMeldCommand(sublime_plugin.TextCommand):
def run(self, files):
settings = sublime.load_settings('SyncFile.sublime-settings')
src_mappings = settings.get("mappings", [])
meld_cmd = settings.get("meldLocation")
if meld_cmd == None:
meld_cmd = "C:\\Program Files (x86)\\Meld\\meld\\meld"
mappings = []
# Check if we have the correct value type
if not isinstance(src_mappings, list):
print("invalid value type, should be a list: %r" % src_mappings)
return
for mapping in src_mappings:
# Check if we have the correct value types for the mappings
if not isinstance(mapping, dict):
print("invalid mapping type, should be a dict: %r" % mapping)
continue
# Check if required keys exist
elif not all(name in mapping for name in ('source', 'dest')):
print("required key(s) missing: %r" % mapping)
continue
# Check if required keys have correct value type
elif not isinstance(mapping['source'], str) or not isinstance(mapping['dest'], str):
print("invalid type for required key(s), should be str: %r" % mapping)
continue
# Check if required keys are not empty
elif not mapping['source'] or not mapping['dest']:
print("required key(s) empty: %r" % mapping)
continue
else:
mappings.append(mapping)
# Check if there are valid mappings
if not mappings:
print("No valid mappings found")
return
source_name = self.view.file_name()
for mapping in mappings:
if mapping['source'] in source_name:
dest_name = source_name.replace(mapping['source'], mapping['dest'])
source_name = os.path.abspath(source_name)
dest_name = os.path.abspath(dest_name)
print('"%s" "%s" "%s"' %(meld_cmd, source_name, dest_name))
os.system('""%s" "%s" "%s""' %(meld_cmd, source_name, dest_name))
return
else:
msg = 'Your current file location is not in one of your source locations '
msg += 'or the relevant dest location is empty. '
msg += 'Please set the settings file properly and retry.'
sublime.error_message(msg)
class DiffFileCommand(sublime_plugin.TextCommand):
def run(self, edit):
global sbs_files
settings = sublime.load_settings('SyncFile.sublime-settings')
src_mappings = settings.get("mappings", [])
mappings = []
# Check if we have the correct value type
if not isinstance(src_mappings, list):
print("invalid value type, should be a list: %r" % src_mappings)
return
for mapping in src_mappings:
# Check if we have the correct value types for the mappings
if not isinstance(mapping, dict):
print("invalid mapping type, should be a dict: %r" % mapping)
continue
# Check if required keys exist
elif not all(name in mapping for name in ('source', 'dest')):
print("required key(s) missing: %r" % mapping)
continue
# Check if required keys have correct value type
elif not isinstance(mapping['source'], str) or not isinstance(mapping['dest'], str):
print("invalid type for required key(s), should be str: %r" % mapping)
continue
# Check if required keys are not empty
elif not mapping['source'] or not mapping['dest']:
print("required key(s) empty: %r" % mapping)
continue
else:
mappings.append(mapping)
# Check if there are valid mappings
if not mappings:
return
source_name = self.view.file_name()
for mapping in mappings:
if mapping['source'] in source_name:
del sbs_files[:]
dest_name = source_name.replace(mapping['source'], mapping['dest'])
source_name = os.path.abspath(source_name)
dest_name = os.path.abspath(dest_name)
if not os.path.isfile(source_name) or not os.path.isfile(dest_name):
print( 'Compare Error: file(s) not found' )
return
sbs_files.append(source_name)
sbs_files.append(dest_name)
print( 'Comparing "%s" and "%s"' % ( source_name, dest_name ) )
window = sublime.active_window()
window.run_command( 'sbs_compare' )
return
else:
msg = 'Your current file location is not in one of your source locations '
msg += 'or the relevant dest location is empty. '
msg += 'Please set the settings file properly and retry.'
sublime.error_message(msg)
class EraseViewCommand( sublime_plugin.TextCommand ):
def run( self, edit ):
self.view.erase( edit, sublime.Region( 0, self.view.size() ) )
class InsertViewCommand( sublime_plugin.TextCommand ):
def run( self, edit, string='' ):
self.view.insert( edit, self.view.size(), string )
class SbsMarkSelCommand( sublime_plugin.TextCommand ):
def run( self, edit ):
global sbs_markedSelection
window = sublime.active_window()
view = window.active_view()
sel = view.sel()
region = sel[0]
selectionText = view.substr( region )
sbs_markedSelection[0] = sbs_markedSelection[1]
sbs_markedSelection[1] = selectionText
class SbsCompareCommand( sublime_plugin.TextCommand ):
def settings( self ):
return sublime.load_settings( 'SBSCompare.sublime-settings' )
def get_view_contents( self, view ):
selection = sublime.Region( 0, view.size() )
content = view.substr( selection )
return content
def close_view( self, view ):
parent = view.window()
parent.focus_view( view )
parent.run_command( "close_file" )
def get_drawtype( self ):
# fill highlighting (DRAW_NO_OUTLINE) only exists on ST3+
drawType = sublime.DRAW_OUTLINED
if int( sublime.version() ) >= 3000:
if not self.settings().get( 'outlines_only', False ):
drawType = sublime.DRAW_NO_OUTLINE
return drawType
def highlight_lines( self, view, lines, sublines, col ):
# full line diffs
regionList = []
for lineNum in lines:
lineStart = view.text_point( lineNum, 0 )
for sub in (sub for sub in sublines if sub[0] == lineNum):
subStart = view.text_point( lineNum, sub[1] )
subEnd = view.text_point( lineNum, sub[2] )
region = sublime.Region( lineStart, subStart )
regionList.append( region )
lineStart = subEnd
lineEnd = view.text_point( lineNum+1, -1 )
region = sublime.Region( lineStart, lineEnd )
regionList.append( region )
colour = 'keyword'
if col == 'A':
colour = self.settings().get( 'remove_colour', 'invalid.illegal' )
elif col == 'B':
colour = self.settings().get( 'add_colour', 'string' )
drawType = self.get_drawtype()
view.add_regions( 'diff_highlighted-' + col, regionList, colour, '', drawType )
def sub_highlight_lines( self, view, lines, col ):
# intra-line diffs
regionList = []
for diff in lines:
lineNum = diff[0]
start = view.text_point( lineNum, diff[1] )
end = view.text_point( lineNum, diff[2] )
region = sublime.Region( start, end )
regionList.append( region )
colour = self.settings().get( 'modified_colour', 'support.class' )
drawType = self.get_drawtype()
view.add_regions( 'diff_intraline-' + col, regionList, colour, '', drawType )
def compare_views( self, view1, view2 ):
view1_contents = self.get_view_contents( view1 )
view2_contents = self.get_view_contents( view2 )
linesA = view1_contents.splitlines( False )
linesB = view2_contents.splitlines( False )
bufferA = []
bufferB = []
highlightA = []
highlightB = []
subHighlightA = []
subHighlightB = []
diff = difflib.ndiff( linesA, linesB, charjunk = None )
lastB = False
intraLineA = ''
intraLineB = ''
lineNum = 0
for line in diff:
lineNum += 1
code = line[:2]
text = line[2:]
if code == '- ':
bufferA.append( text )
bufferB.append( '' )
highlightA.append( lineNum - 1 )
intraLineA = text
lastB = False
elif code == '+ ':
bufferA.append( '' )
bufferB.append( text )
highlightB.append( lineNum - 1 )
intraLineB = text
lastB = True
elif code == ' ':
bufferA.append( text )
bufferB.append( text )
lastB = False
elif code == '? ' and lastB == True:
lineNum -= 1
if self.settings().get( 'enable_intraline', True ):
s = difflib.SequenceMatcher( None, intraLineA, intraLineB )
for tag, i1, i2, j1, j2 in s.get_opcodes():
if tag != 'equal': # == replace
lnA = lineNum-2
lnB = lineNum-1
if self.settings().get( 'full_intraline_highlights', False ):
if tag == 'insert':
i2 += j2 - j1
if tag == 'delete':
j2 += i2 - i1
subHighlightA.append( [ lnA, i1, i2 ] )
subHighlightB.append( [ lnB, j1, j2 ] )
lastB = False
else:
lineNum -= 1
window = sublime.active_window()
window.focus_view( view1 )
window.run_command( 'erase_view' )
window.run_command( 'insert_view', { 'string': '\n'.join( bufferA ) } )
window.focus_view( view2 )
window.run_command( 'erase_view' )
window.run_command( 'insert_view', { 'string': '\n'.join( bufferB ) } )
self.highlight_lines( view1, highlightA, subHighlightA, 'A' )
self.highlight_lines( view2, highlightB, subHighlightB, 'B' )
intraDiff = ''
if self.settings().get( 'enable_intraline', True ):
self.sub_highlight_lines( view1, subHighlightA, 'A' )
self.sub_highlight_lines( view2, subHighlightB, 'B' )
numIntra = len( subHighlightA ) + len( subHighlightB )
intraDiff = str( numIntra ) + ' intra-line modifications\n'
if self.settings().get( 'line_count_popup', False ):
numDiffs = len( highlightA ) + len( highlightB )
sublime.message_dialog( intraDiff + str( len( highlightA ) ) + ' lines removed, ' + str( len( highlightB ) ) + ' lines added\n' + str( numDiffs ) + ' line differences total' )
def run( self, edit, with_active = False, group = -1, index = -1, compare_selections = False ):
global sbs_markedSelection, sbs_files
active_view = self.view
active_window = active_view.window()
active_id = active_view.id()
openTabs = []
for view in active_window.views():
if view.id() != active_id:
viewName = 'untitled'
if view.file_name():
viewName = view.file_name()
elif view.name():
viewName = view.name()
openTabs.append( [ viewName, view ] )
def create_comparison( view1_contents, view2_contents, syntax, name1_override = False, name2_override = False ):
view1_syntax = syntax
view2_syntax = syntax
# make new window
active_window.run_command( 'new_window' )
new_window = sublime.active_window()
new_window.set_layout( { "cols": [0.0, 0.5, 1.0], "rows": [0.0, 1.0], "cells": [[0, 0, 1, 1], [1, 0, 2, 1]] } )
if self.settings().get( 'toggle_sidebar', False ):
new_window.run_command( 'toggle_side_bar' )
if self.settings().get( 'toggle_menu', False ):
new_window.run_command( 'toggle_menu' )
# view 1
new_window.run_command( 'new_file' )
new_window.run_command( 'insert_view', { 'string': view1_contents } )
new_window.active_view().set_syntax_file( view1_syntax )
view1_name = 'untitled'
if active_view.file_name():
view1_name = active_view.file_name()
elif active_view.name():
view1_name = active_view.name()
if name1_override != False:
view1_name = name1_override
new_window.active_view().set_name( os.path.basename( view1_name ) + ' (active)' )
new_window.active_view().set_scratch( True )
view1 = new_window.active_view()
# view 2
new_window.run_command( 'new_file' )
new_window.run_command( 'insert_view', { 'string': view2_contents } )
new_window.active_view().set_syntax_file( view2_syntax )
new_window.active_view().set_name( os.path.basename( name2_override ) + ' (other)' )
# move view 2 to group 2
new_window.set_view_index( new_window.active_view(), 1, 0 )
new_window.active_view().set_scratch( True )
view2 = new_window.active_view()
# run diff
self.compare_views( view1, view2 )
# make readonly
new_window.focus_view( view1 )
if self.settings().get( 'read_only', False ):
new_window.active_view().set_read_only( True )
new_window.focus_view( view2 )
if self.settings().get( 'read_only', False ):
new_window.active_view().set_read_only( True )
# activate scroll syncer
ViewScrollSyncer( new_window, [ view1, view2 ] )
# move views to top left
view1.set_viewport_position( (0, 0), False )
view2.set_viewport_position( (0, 0), False )
def on_click( index ):
if index > -1:
# get original views' data
view1_contents = self.get_view_contents( active_view )
view2_contents = self.get_view_contents( openTabs[index][1] )
syntax = active_view.settings().get( 'syntax' )
create_comparison( view1_contents, view2_contents, syntax, False, openTabs[index][0] )
def compare_from_views( view1, view2 ):
if view1.is_loading() or view2.is_loading():
sublime.set_timeout( lambda: compare_from_views( view1, view2 ), 10 )
else:
view1_contents = self.get_view_contents( view1 )
view2_contents = self.get_view_contents( view2 )
syntax = view1.settings().get( 'syntax' )
self.close_view( view1 )
self.close_view( view2 )
create_comparison( view1_contents, view2_contents, syntax, file1, file2 )
if len( sbs_files ) > 0:
file1 = sbs_files[0]
file2 = sbs_files[1]
view1 = active_window.open_file( file1 )
view2 = active_window.open_file( file2 )
compare_from_views( view1, view2 )
del sbs_files[:]
elif compare_selections == True:
selA = sbs_markedSelection[0]
selB = sbs_markedSelection[1]
sel = active_view.sel()
selNum = 0
for selection in sel:
selNum += 1
if selNum == 2:
selA = active_view.substr( sel[0] )
selB = active_view.substr( sel[1] )
syntax = active_view.settings().get( 'syntax' )
create_comparison( selA, selB, syntax, 'selection A', 'selection B' )
elif len( openTabs ) == 1:
on_click( 0 )
else:
if with_active == True:
active_group, active_group_index = active_window.get_view_index( active_view )
if index > active_group_index:
index -= 1
on_click( index )
else:
menu_items = []
for tab in openTabs:
fileName = tab[0]
if self.settings().get( 'expanded_filenames', False ):
menu_items.append( [ os.path.basename( fileName ), fileName ] )
else:
menu_items.append( os.path.basename( fileName ) )
sublime.set_timeout( self.view.window().show_quick_panel( menu_items, on_click ) )
class ViewScrollSyncer( object ):
def __init__( self, window, viewList ):
self.window = window
self.views = viewList
self.timeout_focused = 10
self.timeout_unfocused = 50
self.run()
def update_scroll( self, view1, view2, lastUpdated ):
if lastUpdated == 'A':
view2.set_viewport_position( view1.viewport_position(), False )
elif lastUpdated == 'B':
view1.set_viewport_position( view2.viewport_position(), False )
def run( self ):
if not self.window:
return
if self.window.id() != sublime.active_window().id():
sublime.set_timeout( self.run, self.timeout_unfocused )
return
view1 = self.views[0]
view2 = self.views[1]
if not view1 or not view2:
return
vecA = view1.viewport_position()
vecB = view2.viewport_position()
if vecA != vecB:
lastVecA0 = view1.settings().get( 'viewsync_last_vec0', 1 )
lastVecA1 = view1.settings().get( 'viewsync_last_vec1', 1 )
lastVecB0 = view2.settings().get( 'viewsync_last_vec0', 1 )
lastVecB1 = view2.settings().get( 'viewsync_last_vec1', 1 )
lastVecA = ( lastVecA0, lastVecA1 )
lastVecB = ( lastVecB0, lastVecB1 )
lastUpdated = ''
if lastVecA != vecA:
lastUpdated = 'A'
view1.settings().set( 'viewsync_last_vec0', vecA[0] )
view1.settings().set( 'viewsync_last_vec1', vecA[1] )
view2.settings().set( 'viewsync_last_vec0', vecA[0] )
view2.settings().set( 'viewsync_last_vec1', vecA[1] )
if lastVecB != vecB:
lastUpdated = 'B'
view1.settings().set( 'viewsync_last_vec0', vecB[0] )
view1.settings().set( 'viewsync_last_vec1', vecB[1] )
view2.settings().set( 'viewsync_last_vec0', vecB[0] )
view2.settings().set( 'viewsync_last_vec1', vecB[1] )
if ( lastUpdated != '' ):
self.update_scroll( view1, view2, lastUpdated )
sublime.set_timeout( self.run, self.timeout_focused )