forked from twolfson/sublime-files
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sublime_plugin.py
1016 lines (785 loc) · 27.9 KB
/
sublime_plugin.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
import imp
import importlib
import os
import sys
import time
import traceback
import zipfile
import sublime
import sublime_api
api_ready = False
application_command_classes = []
window_command_classes = []
text_command_classes = []
view_event_listener_classes = []
view_event_listeners = {}
all_command_classes = [
application_command_classes,
window_command_classes,
text_command_classes]
all_callbacks = {
'on_new': [],
'on_clone': [],
'on_load': [],
'on_pre_close': [],
'on_close': [],
'on_pre_save': [],
'on_post_save': [],
'on_modified': [],
'on_selection_modified': [],
'on_activated': [],
'on_deactivated': [],
'on_query_context': [],
'on_query_completions': [],
'on_hover': [],
'on_text_command': [],
'on_window_command': [],
'on_post_text_command': [],
'on_post_window_command': [],
'on_modified_async': [],
'on_selection_modified_async': [],
'on_pre_save_async': [],
'on_post_save_async': [],
'on_activated_async': [],
'on_deactivated_async': [],
'on_new_async': [],
'on_load_async': [],
'on_clone_async': []}
profile = {}
def unload_module(module):
if "plugin_unloaded" in module.__dict__:
module.plugin_unloaded()
# Check unload_handler too, for backwards compat
if "unload_handler" in module.__dict__:
module.unload_handler()
# Unload the old plugins
if "plugins" in module.__dict__:
for view_id, listener_instances in view_event_listeners.items():
for vel in listener_instances[:]:
if vel.__class__ in module.plugins:
listener_instances.remove(vel)
for p in module.plugins:
for cmd_cls_list in all_command_classes:
try:
cmd_cls_list.remove(p)
except ValueError:
pass
for c in all_callbacks.values():
try:
c.remove(p)
except ValueError:
pass
try:
view_event_listener_classes.remove(p)
except ValueError:
pass
def unload_plugin(modulename):
print("unloading plugin", modulename)
was_loaded = modulename in sys.modules
if was_loaded:
m = sys.modules[modulename]
unload_module(m)
del sys.modules[modulename]
def reload_plugin(modulename):
print("reloading plugin", modulename)
if modulename in sys.modules:
m = sys.modules[modulename]
unload_module(m)
m = imp.reload(m)
else:
m = importlib.import_module(modulename)
module_plugins = []
on_activated_targets = []
module_view_event_listener_classes = []
for type_name in dir(m):
try:
t = m.__dict__[type_name]
if t.__bases__:
is_plugin = False
if issubclass(t, ApplicationCommand):
application_command_classes.append(t)
is_plugin = True
if issubclass(t, WindowCommand):
window_command_classes.append(t)
is_plugin = True
if issubclass(t, TextCommand):
text_command_classes.append(t)
is_plugin = True
if is_plugin:
module_plugins.append(t)
if issubclass(t, EventListener):
obj = t()
for p in all_callbacks.items():
if p[0] in dir(obj):
p[1].append(obj)
if "on_activated" in dir(obj):
on_activated_targets.append(obj)
module_plugins.append(obj)
if issubclass(t, ViewEventListener):
view_event_listener_classes.append(t)
module_view_event_listener_classes.append(t)
module_plugins.append(t)
except AttributeError:
pass
if len(module_plugins) > 0:
m.plugins = module_plugins
if api_ready:
if "plugin_loaded" in m.__dict__:
try:
m.plugin_loaded()
except:
traceback.print_exc()
# Synthesize any required on_activated calls
for el in on_activated_targets:
w = sublime.active_window()
if w:
v = w.active_view()
if v:
try:
el.on_activated(v)
except:
traceback.print_exc()
# Create any require ViewEventListener objects
if len(module_view_event_listener_classes) > 0:
for w in sublime.windows():
for v in w.views():
create_view_event_listeners(
module_view_event_listener_classes, v)
def create_application_commands():
cmds = []
for class_ in application_command_classes:
cmds.append(class_())
sublime_api.notify_application_commands(cmds)
def create_window_commands(window_id):
window = sublime.Window(window_id)
cmds = []
for class_ in window_command_classes:
cmds.append(class_(window))
return cmds
def create_text_commands(view_id):
view = sublime.View(view_id)
cmds = []
for class_ in text_command_classes:
cmds.append(class_(view))
return cmds
def on_api_ready():
global api_ready
api_ready = True
for m in list(sys.modules.values()):
if "plugin_loaded" in m.__dict__:
try:
m.plugin_loaded()
except:
traceback.print_exc()
# Synthesize an on_activated call
w = sublime.active_window()
if w:
view_id = sublime_api.window_active_view(w.window_id)
if view_id != 0:
try:
on_activated(view_id)
except:
traceback.print_exc()
# Create ViewEventListener instances
if len(view_event_listener_classes) > 0:
for w in sublime.windows():
for v in w.views():
attach_view(v)
def is_view_event_listener_applicable(cls, view):
if not cls.is_applicable(view.settings()):
return False
if cls.applies_to_primary_view_only() and not view.is_primary():
return False
return True
def create_view_event_listeners(classes, view):
if len(classes) > 0:
if view.view_id not in view_event_listeners:
view_event_listeners[view.view_id] = []
for c in classes:
if is_view_event_listener_applicable(c, view):
view_event_listeners[view.view_id].append(c(view))
def check_view_event_listeners(view):
if len(view_event_listener_classes) > 0:
if view.view_id not in view_event_listeners:
view_event_listeners[view.view_id] = []
listeners = view_event_listeners[view.view_id]
for cls in view_event_listener_classes:
found = False
instance = None
for l in listeners:
if l.__class__ == cls:
found = True
instance = l
break
want = is_view_event_listener_applicable(cls, view)
if want and not found:
listeners.append(cls(view))
elif found and not want:
listeners.remove(instance)
def attach_view(view):
check_view_event_listeners(view)
view.settings().add_on_change(
"check_view_event_listeners",
lambda: check_view_event_listeners(view))
check_all_view_event_listeners_scheduled = False
def check_all_view_event_listeners():
global check_all_view_event_listeners_scheduled
check_all_view_event_listeners_scheduled = False
for w in sublime.windows():
for v in w.views():
check_view_event_listeners(v)
def detach_view(view):
if view.view_id in view_event_listeners:
del view_event_listeners[view.view_id]
# A view has closed, which implies 'is_primary' may have changed, so see if
# any of the ViewEventListener classes need to be created.
# Call this in a timeout, as 'view' will still be reporting itself as a
# primary at this stage
global check_all_view_event_listeners_scheduled
if not check_all_view_event_listeners_scheduled:
check_all_view_event_listeners_scheduled = True
sublime.set_timeout(check_all_view_event_listeners)
def event_listeners_for_view(view):
if view.view_id in view_event_listeners:
return view_event_listeners[view.view_id]
else:
return []
def find_view_event_listener(view, cls):
if view.view_id in view_event_listeners:
for vel in view_event_listeners[view.view_id]:
if vel.__class__ == cls:
return vel
return None
def on_new(view_id):
v = sublime.View(view_id)
attach_view(v)
for callback in all_callbacks['on_new']:
try:
callback.on_new(v)
except:
traceback.print_exc()
def on_new_async(view_id):
v = sublime.View(view_id)
for callback in all_callbacks['on_new_async']:
try:
callback.on_new_async(v)
except:
traceback.print_exc()
def on_clone(view_id):
v = sublime.View(view_id)
attach_view(v)
for callback in all_callbacks['on_clone']:
try:
callback.on_clone(v)
except:
traceback.print_exc()
def on_clone_async(view_id):
v = sublime.View(view_id)
for callback in all_callbacks['on_clone_async']:
try:
callback.on_clone_async(v)
except:
traceback.print_exc()
class Summary(object):
def __init__(self):
self.max = 0.0
self.sum = 0.0
self.count = 0
def record(self, x):
self.count += 1
self.sum += x
self.max = max(self.max, x)
def __str__(self):
if self.count > 1:
return "{0:.3f}s total, mean: {1:.3f}s, max: {2:.3f}s".format(self.sum, self.sum / self.count, self.max)
elif self.count == 1:
return "{0:.3f}s total".format(self.sum)
else:
return "0s total"
def run_callback(event, callback, expr):
t0 = time.time()
try:
expr()
except:
traceback.print_exc()
elapsed = time.time() - t0
if event not in profile:
profile[event] = {}
p = profile[event]
name = callback.__module__
if name not in p:
p[name] = Summary()
p[name].record(elapsed)
def run_view_listener_callback(view, name):
for vel in event_listeners_for_view(view):
if name in vel.__class__.__dict__:
run_callback(name, vel, lambda: vel.__class__.__dict__[name](vel))
def run_async_view_listener_callback(view, name):
for vel in event_listeners_for_view(view):
if name in vel.__class__.__dict__:
try:
vel.__class__.__dict__[name](vel)
except:
traceback.print_exc()
def on_load(view_id):
v = sublime.View(view_id)
attach_view(v)
for callback in all_callbacks['on_load']:
run_callback('on_load', callback, lambda: callback.on_load(v))
def on_load_async(view_id):
v = sublime.View(view_id)
for callback in all_callbacks['on_load_async']:
try:
callback.on_load_async(v)
except:
traceback.print_exc()
def on_pre_close(view_id):
v = sublime.View(view_id)
for callback in all_callbacks['on_pre_close']:
run_callback('on_pre_close', callback, lambda: callback.on_pre_close(v))
def on_close(view_id):
v = sublime.View(view_id)
detach_view(v)
for callback in all_callbacks['on_close']:
run_callback('on_close', callback, lambda: callback.on_close(v))
def on_pre_save(view_id):
v = sublime.View(view_id)
for callback in all_callbacks['on_pre_save']:
run_callback('on_pre_save', callback, lambda: callback.on_pre_save(v))
def on_pre_save_async(view_id):
v = sublime.View(view_id)
for callback in all_callbacks['on_pre_save_async']:
try:
callback.on_pre_save_async(v)
except:
traceback.print_exc()
def on_post_save(view_id):
v = sublime.View(view_id)
for callback in all_callbacks['on_post_save']:
run_callback('on_post_save', callback, lambda: callback.on_post_save(v))
def on_post_save_async(view_id):
v = sublime.View(view_id)
for callback in all_callbacks['on_post_save_async']:
try:
callback.on_post_save_async(v)
except:
traceback.print_exc()
def on_modified(view_id):
v = sublime.View(view_id)
for callback in all_callbacks['on_modified']:
run_callback('on_modified', callback, lambda: callback.on_modified(v))
run_view_listener_callback(v, 'on_modified')
def on_modified_async(view_id):
v = sublime.View(view_id)
for callback in all_callbacks['on_modified_async']:
try:
callback.on_modified_async(v)
except:
traceback.print_exc()
run_async_view_listener_callback(v, 'on_modified_async')
def on_selection_modified(view_id):
v = sublime.View(view_id)
for callback in all_callbacks['on_selection_modified']:
run_callback('on_selection_modified', callback, lambda: callback.on_selection_modified(v))
run_view_listener_callback(v, 'on_selection_modified')
def on_selection_modified_async(view_id):
v = sublime.View(view_id)
for callback in all_callbacks['on_selection_modified_async']:
try:
callback.on_selection_modified_async(v)
except:
traceback.print_exc()
run_async_view_listener_callback(v, 'on_selection_modified_async')
def on_activated(view_id):
v = sublime.View(view_id)
for callback in all_callbacks['on_activated']:
run_callback('on_activated', callback, lambda: callback.on_activated(v))
run_view_listener_callback(v, 'on_activated')
def on_activated_async(view_id):
v = sublime.View(view_id)
for callback in all_callbacks['on_activated_async']:
try:
callback.on_activated_async(v)
except:
traceback.print_exc()
run_async_view_listener_callback(v, 'on_activated_async')
def on_deactivated(view_id):
v = sublime.View(view_id)
for callback in all_callbacks['on_deactivated']:
run_callback('on_deactivated', callback, lambda: callback.on_deactivated(v))
run_view_listener_callback(v, 'on_deactivated')
def on_deactivated_async(view_id):
v = sublime.View(view_id)
for callback in all_callbacks['on_deactivated_async']:
try:
callback.on_deactivated_async(v)
except:
traceback.print_exc()
run_async_view_listener_callback(v, 'on_deactivated_async')
def on_query_context(view_id, key, operator, operand, match_all):
v = sublime.View(view_id)
for callback in all_callbacks['on_query_context']:
try:
val = callback.on_query_context(v, key, operator, operand, match_all)
if val:
return True
except:
traceback.print_exc()
for vel in event_listeners_for_view(v):
if 'on_query_context' in vel.__class__.__dict__:
try:
val = vel.on_query_context(key, operator, operand, match_all)
if val:
return True
except:
traceback.print_exc()
return False
def normalise_completion(c):
if len(c) == 1:
return (c[0], "", "")
elif len(c) == 2:
return (c[0], "", c[1])
else:
return c
def on_query_completions(view_id, prefix, locations):
v = sublime.View(view_id)
completions = []
flags = 0
for callback in all_callbacks['on_query_completions']:
try:
res = callback.on_query_completions(v, prefix, locations)
if isinstance(res, tuple):
completions += [normalise_completion(c) for c in res[0]]
flags |= res[1]
elif isinstance(res, list):
completions += [normalise_completion(c) for c in res]
except:
traceback.print_exc()
for vel in event_listeners_for_view(v):
if 'on_query_completions' in vel.__class__.__dict__:
try:
res = vel.on_query_completions(prefix, locations)
if isinstance(res, tuple):
completions += [normalise_completion(c) for c in res[0]]
flags |= res[1]
elif isinstance(res, list):
completions += [normalise_completion(c) for c in res]
except:
traceback.print_exc()
return (completions, flags)
def on_hover(view_id, point, hover_zone):
v = sublime.View(view_id)
for callback in all_callbacks['on_hover']:
run_callback('on_hover', callback, lambda: callback.on_hover(v, point, hover_zone))
for vel in event_listeners_for_view(v):
if 'on_hover' in vel.__class__.__dict__:
try:
vel.on_hover(point, hover_zone)
except:
traceback.print_exc()
def on_text_command(view_id, name, args):
v = sublime.View(view_id)
for callback in all_callbacks['on_text_command']:
try:
res = callback.on_text_command(v, name, args)
if isinstance(res, tuple):
return res
elif res:
return (res, None)
except:
traceback.print_exc()
return ("", None)
def on_window_command(window_id, name, args):
window = sublime.Window(window_id)
for callback in all_callbacks['on_window_command']:
try:
res = callback.on_window_command(window, name, args)
if isinstance(res, tuple):
return res
elif res:
return (res, None)
except:
traceback.print_exc()
return ("", None)
def on_post_text_command(view_id, name, args):
v = sublime.View(view_id)
for callback in all_callbacks['on_post_text_command']:
try:
callback.on_post_text_command(v, name, args)
except:
traceback.print_exc()
def on_post_window_command(window_id, name, args):
window = sublime.Window(window_id)
for callback in all_callbacks['on_post_window_command']:
try:
callback.on_post_window_command(window, name, args)
except:
traceback.print_exc()
class Command(object):
def name(self):
clsname = self.__class__.__name__
name = clsname[0].lower()
last_upper = False
for c in clsname[1:]:
if c.isupper() and not last_upper:
name += '_'
name += c.lower()
else:
name += c
last_upper = c.isupper()
if name.endswith("_command"):
name = name[0:-8]
return name
def is_enabled_(self, args):
ret = None
try:
args = self.filter_args(args)
if args:
ret = self.is_enabled(**args)
else:
ret = self.is_enabled()
except TypeError:
ret = self.is_enabled()
if not isinstance(ret, bool):
raise ValueError("is_enabled must return a bool", self)
return ret
def is_enabled(self):
return True
def is_visible_(self, args):
ret = None
try:
args = self.filter_args(args)
if args:
ret = self.is_visible(**args)
else:
ret = self.is_visible()
except TypeError:
ret = self.is_visible()
if not isinstance(ret, bool):
raise ValueError("is_visible must return a bool", self)
return ret
def is_visible(self):
return True
def is_checked_(self, args):
ret = None
try:
args = self.filter_args(args)
if args:
ret = self.is_checked(**args)
else:
ret = self.is_checked()
except TypeError:
ret = self.is_checked()
if not isinstance(ret, bool):
raise ValueError("is_checked must return a bool", self)
return ret
def is_checked(self):
return False
def description_(self, args):
try:
args = self.filter_args(args)
if args is not None:
return self.description(**args)
else:
return self.description()
except TypeError:
return ""
def description(self):
return ""
def filter_args(self, args):
if args:
if 'event' in args and not self.want_event():
args = args.copy()
del args['event']
return args
def want_event(self):
return False
class ApplicationCommand(Command):
def run_(self, edit_token, args):
args = self.filter_args(args)
if args:
return self.run(**args)
else:
return self.run()
def run(self):
pass
class WindowCommand(Command):
def __init__(self, window):
self.window = window
def run_(self, edit_token, args):
args = self.filter_args(args)
if args:
return self.run(**args)
else:
return self.run()
def run(self):
pass
class TextCommand(Command):
def __init__(self, view):
self.view = view
def run_(self, edit_token, args):
args = self.filter_args(args)
if args:
edit = self.view.begin_edit(edit_token, self.name(), args)
try:
return self.run(edit, **args)
finally:
self.view.end_edit(edit)
else:
edit = self.view.begin_edit(edit_token, self.name())
try:
return self.run(edit)
finally:
self.view.end_edit(edit)
def run(self, edit):
pass
class EventListener(object):
pass
class ViewEventListener(object):
@classmethod
def is_applicable(cls, settings):
return True
@classmethod
def applies_to_primary_view_only(cls):
return True
def __init__(self, view):
self.view = view
class MultizipImporter(object):
def __init__(self):
self.loaders = []
self.file_loaders = []
def find_module(self, fullname, path=None):
if not path:
for l in self.loaders:
if l.name == fullname:
return l
for l in self.loaders:
if path == [l.zippath]:
if l.has(fullname):
return l
return None
class ZipLoader(object):
def __init__(self, zippath):
self.zippath = zippath
self.name = os.path.splitext(os.path.basename(zippath))[0]
self._scan_zip()
def has(self, fullname):
key = '.'.join(fullname.split('.')[1:])
if key in self.contents:
return True
override_file = os.path.join(override_path, os.sep.join(fullname.split('.')) + '.py')
if os.path.isfile(override_file):
return True
override_package = os.path.join(override_path, os.sep.join(fullname.split('.')))
if os.path.isdir(override_package):
return True
return False
def load_module(self, fullname):
# Only if a module is being reloaded and hasn't been scanned recently
# do we force a refresh of the contents of the .sublime-package. This
# allows proper code upgrades using Package Control.
if fullname in imp._RELOADING:
if self.refreshed < time.time() - 5:
self._scan_zip()
source, source_path, mod_file, is_pkg = self._read_source(fullname)
if source is None:
raise ImportError("No module named '%s'" % fullname)
is_new = False
if fullname in sys.modules:
mod = sys.modules[fullname]
old_mod_file = mod.__file__
else:
is_new = True
mod = sys.modules.setdefault(fullname, imp.new_module(fullname))
mod.__name__ = fullname
mod.__path__ = [self.zippath]
mod.__loader__ = self
mod.__file__ = mod_file
if is_pkg:
mod.__package__ = mod.__name__
else:
mod.__package__ = fullname.rpartition('.')[0]
try:
exec(compile(source, source_path, 'exec'), mod.__dict__)
return mod
except:
if is_new:
del sys.modules[fullname]
else:
mod.__file__ = old_mod_file
raise
def _read_source(self, fullname):
name_parts = fullname.split('.')
override_basename = os.path.join(override_path, *name_parts)
override_py = override_basename + '.py'
override_init = os.path.join(override_basename, '__init__.py')
if os.path.isfile(override_py):
try:
with open(override_py, 'r', encoding='utf-8') as f:
return (f.read(), override_py, override_py, False)
except (Exception) as e:
print(override_py, 'could not be read:', e)
if os.path.isfile(override_init):
try:
with open(override_init, 'r', encoding='utf-8') as f:
return (f.read(), override_init, override_init, True)
except (Exception) as e:
print(override_init, 'could not be read:', e)
key = '.'.join(name_parts[1:])
if key in self.contents:
source = self.contents[key]
source_path = key + " in " + self.zippath
mod_file = os.path.join(self.zippath, self.filenames[key]).rstrip(os.sep)
is_pkg = key in self.packages
return (source, source_path, mod_file, is_pkg)
# This allows .py overrides to exist in subfolders that:
# 1. Do not exist in the .sublime-package file
# 2. Do not contain an __init__.py
if os.path.isdir(override_basename):
return ('', override_basename, override_basename, True)
return (None, None, None, False)
def _scan_zip(self):
self.contents = {"": ""}
self.filenames = {"": ""}
self.packages = {""}
self.refreshed = time.time()
try:
with zipfile.ZipFile(self.zippath, 'r') as z:
files = [i.filename for i in z.infolist()]
for f in files:
base, ext = os.path.splitext(f)
if ext != ".py":
continue
paths = base.split('/')
if len(paths) > 0 and paths[len(paths) - 1] == "__init__":
paths.pop()
self.packages.add('.'.join(paths))
try:
pkg_path = '.'.join(paths)
self.contents[pkg_path] = z.read(f).decode('utf-8')
self.filenames[pkg_path] = f
except UnicodeDecodeError:
print(f, "in", self.zippath, "is not utf-8 encoded, unable to load plugin")
continue
while len(paths) > 1:
paths.pop()
parent = '.'.join(paths)
if parent not in self.contents:
self.contents[parent] = ""
self.filenames[parent] = parent
self.packages.add(parent)
except (Exception) as e:
print("Error loading %s:" % self.zippath, e)
override_path = None