forked from SublimeLinter/SublimeLinter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
commands.py
1208 lines (864 loc) · 38.4 KB
/
commands.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
#
# commands.py
# Part of SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ryan Hileman and Aparajita Fishman
#
# Project: https://github.com/SublimeLinter/SublimeLinter3
# License: MIT
#
"""This module implements the Sublime Text commands provided by SublimeLinter."""
import datetime
from fnmatch import fnmatch
from glob import glob
import json
import os
import re
import shutil
import subprocess
import tempfile
from textwrap import TextWrapper
from threading import Thread
import time
import sublime
import sublime_plugin
from .lint import highlight, linter, persist, util
def error_command(method):
"""
A decorator that executes method only if the current view has errors.
This decorator is meant to be used only with the run method of
sublime_plugin.TextCommand subclasses.
A wrapped version of method is returned.
"""
def run(self, edit, **kwargs):
vid = self.view.id()
if vid in persist.errors and persist.errors[vid]:
method(self, self.view, persist.errors[vid], persist.highlights[vid], **kwargs)
else:
sublime.message_dialog('No lint errors.')
return run
def select_line(view, line):
"""Change view's selection to be the given line."""
point = view.text_point(line, 0)
sel = view.sel()
sel.clear()
sel.add(view.line(point))
class SublimelinterLintCommand(sublime_plugin.TextCommand):
"""A command that lints the current view if it has a linter."""
def is_enabled(self):
"""
Return True if the current view can be linted.
If the view has *only* file-only linters, it can be linted
only if the view is not dirty.
Otherwise it can be linted.
"""
has_non_file_only_linter = False
vid = self.view.id()
linters = persist.view_linters.get(vid, [])
for lint in linters:
if lint.tempfile_suffix != '-':
has_non_file_only_linter = True
break
if not has_non_file_only_linter:
return not self.view.is_dirty()
return True
def run(self, edit):
"""Lint the current view."""
from .sublimelinter import SublimeLinter
SublimeLinter.shared_plugin().lint(self.view.id())
class HasErrorsCommand:
"""
A mixin class for sublime_plugin.TextCommand subclasses.
Inheriting from this class will enable the command only if the current view has errors.
"""
def is_enabled(self):
"""Return True if the current view has errors."""
vid = self.view.id()
return vid in persist.errors and len(persist.errors[vid]) > 0
class GotoErrorCommand(sublime_plugin.TextCommand):
"""A superclass for commands that go to the next/previous error."""
def goto_error(self, view, errors, direction='next'):
"""Go to the next/previous error in view."""
sel = view.sel()
if len(sel) == 0:
sel.add(sublime.Region(0, 0))
saved_sel = tuple(sel)
empty_selection = len(sel) == 1 and sel[0].empty()
# sublime.Selection() changes the view's selection, get the point first
point = sel[0].begin() if direction == 'next' else sel[-1].end()
regions = sublime.Selection(view.id())
regions.clear()
for error_type in (highlight.WARNING, highlight.ERROR):
regions.add_all(view.get_regions(highlight.MARK_KEY_FORMAT.format(error_type)))
region_to_select = None
# If going forward, find the first region beginning after the point.
# If going backward, find the first region ending before the point.
# If nothing is found in the given direction, wrap to the first/last region.
if direction == 'next':
for region in regions:
if (
(point == region.begin() and empty_selection and not region.empty()) or
(point < region.begin())
):
region_to_select = region
break
else:
for region in reversed(regions):
if (
(point == region.end() and empty_selection and not region.empty()) or
(point > region.end())
):
region_to_select = region
break
# If there is only one error line and the cursor is in that line, we cannot move.
# Otherwise wrap to the first/last error line unless settings disallow that.
if region_to_select is None and ((len(regions) > 1 or not regions[0].contains(point))):
if persist.settings.get('wrap_find', True):
region_to_select = regions[0] if direction == 'next' else regions[-1]
if region_to_select is not None:
self.select_lint_region(self.view, region_to_select)
else:
sel.clear()
sel.add_all(saved_sel)
sublime.message_dialog('No {0} lint error.'.format(direction))
@classmethod
def select_lint_region(cls, view, region):
"""
Select and scroll to the first marked region that contains region.
If none are found, the beginning of region is used. The view is
centered on the calculated region and the region is selected.
"""
marked_region = cls.find_mark_within(view, region)
if marked_region is None:
marked_region = sublime.Region(region.begin(), region.begin())
sel = view.sel()
sel.clear()
sel.add(marked_region)
# There is a bug in ST3 that prevents the selection from changing
# when a quick panel is open and the viewport does not change position,
# so we call our own custom method that works around that.
util.center_region_in_view(marked_region, view)
@classmethod
def find_mark_within(cls, view, region):
"""Return the nearest marked region that contains region, or None if none found."""
marks = view.get_regions(highlight.MARK_KEY_FORMAT.format(highlight.WARNING))
marks.extend(view.get_regions(highlight.MARK_KEY_FORMAT.format(highlight.ERROR)))
marks.sort(key=sublime.Region.begin)
for mark in marks:
if mark.contains(region):
return mark
return None
class SublimelinterGotoErrorCommand(GotoErrorCommand):
"""A command that selects the next/previous error."""
@error_command
def run(self, view, errors, highlights, **kwargs):
"""Run the command."""
self.goto_error(view, errors, **kwargs)
class SublimelinterShowAllErrors(sublime_plugin.TextCommand):
"""A command that shows a quick panel with all of the errors in the current view."""
@error_command
def run(self, view, errors, highlights):
"""Run the command."""
self.errors = errors
self.highlights = highlights
self.points = []
options = []
for lineno, line_errors in sorted(errors.items()):
if persist.settings.get("passive_warnings", False):
if self.highlights.line_type(lineno) != highlight.ERROR:
continue
line = view.substr(view.full_line(view.text_point(lineno, 0))).rstrip('\n\r')
# Strip whitespace from the front of the line, but keep track of how much was
# stripped so we can adjust the column.
diff = len(line)
line = line.lstrip()
diff -= len(line)
max_prefix_len = 40
for column, message in sorted(line_errors):
# Keep track of the line and column
point = view.text_point(lineno, column)
self.points.append(point)
# If there are more than max_prefix_len characters before the adjusted column,
# lop off the excess and insert an ellipsis.
column = max(column - diff, 0)
if column > max_prefix_len:
visible_line = '...' + line[column - max_prefix_len:]
column = max_prefix_len + 3 # 3 for ...
else:
visible_line = line
# Insert an arrow at the column in the stripped line
code = visible_line[:column] + '➜' + visible_line[column:]
options.append(['{} {}'.format(lineno + 1, message), code])
self.viewport_pos = view.viewport_position()
self.selection = list(view.sel())
view.window().show_quick_panel(
options,
on_select=self.select_error,
on_highlight=self.select_error
)
def select_error(self, index):
"""Completion handler for the quick panel. Selects the indexed error."""
if index != -1:
point = self.points[index]
GotoErrorCommand.select_lint_region(self.view, sublime.Region(point, point))
else:
self.view.set_viewport_position(self.viewport_pos)
self.view.sel().clear()
self.view.sel().add_all(self.selection)
class SublimelinterToggleSettingCommand(sublime_plugin.WindowCommand):
"""Command that toggles a setting."""
def __init__(self, window):
"""Initialize a new instance."""
super().__init__(window)
def is_visible(self, **args):
"""Return True if the opposite of the setting is True."""
if args.get('checked', False):
return True
if persist.settings.has_setting(args['setting']):
setting = persist.settings.get(args['setting'], None)
return setting is not None and setting is not args['value']
else:
return args['value'] is not None
def is_checked(self, **args):
"""Return True if the setting should be checked."""
if args.get('checked', False):
setting = persist.settings.get(args['setting'], False)
return setting is True
else:
return False
def run(self, **args):
"""Toggle the setting if value is boolean, or remove it if None."""
if 'value' in args:
if args['value'] is None:
persist.settings.pop(args['setting'])
else:
persist.settings.set(args['setting'], args['value'], changed=True)
else:
setting = persist.settings.get(args['setting'], False)
persist.settings.set(args['setting'], not setting, changed=True)
persist.settings.save()
class ChooseSettingCommand(sublime_plugin.WindowCommand):
"""An abstract base class for commands that choose a setting from a list."""
def __init__(self, window, setting=None, preview=False):
"""Initialize a new instance."""
super().__init__(window)
self.setting = setting
self._settings = None
self.preview = preview
def description(self, **args):
"""Return the visible description of the command, used in menus."""
return args.get('value', None)
def is_checked(self, **args):
"""Return whether this command should be checked in a menu."""
if 'value' not in args:
return False
item = self.transform_setting(args['value'], matching=True)
setting = self.setting_value(matching=True)
return item == setting
def _get_settings(self):
"""Return the list of settings."""
if self._settings is None:
self._settings = self.get_settings()
return self._settings
settings = property(_get_settings)
def get_settings(self):
"""Return the list of settings. Subclasses must override this."""
raise NotImplementedError
def transform_setting(self, setting, matching=False):
"""
Transform the display text for setting to the form it is stored in.
By default, returns a lowercased copy of setting.
"""
return setting.lower()
def setting_value(self, matching=False):
"""Return the current value of the setting."""
return self.transform_setting(persist.settings.get(self.setting, ''), matching=matching)
def on_highlight(self, index):
"""If preview is on, set the selected setting."""
if self.preview:
self.set(index)
def choose(self, **kwargs):
"""
Choose or set the setting.
If 'value' is in kwargs, the setting is set to the corresponding value.
Otherwise the list of available settings is built via get_settings
and is displayed in a quick panel. The current value of the setting
is initially selected in the quick panel.
"""
if 'value' in kwargs:
setting = self.transform_setting(kwargs['value'])
else:
setting = self.setting_value(matching=True)
index = 0
for i, s in enumerate(self.settings):
if isinstance(s, (tuple, list)):
s = self.transform_setting(s[0])
else:
s = self.transform_setting(s)
if s == setting:
index = i
break
if 'value' in kwargs:
self.set(index)
else:
self.previous_setting = self.setting_value()
self.window.show_quick_panel(
self.settings,
on_select=self.set,
selected_index=index,
on_highlight=self.on_highlight)
def set(self, index):
"""Set the value of the setting."""
if index == -1:
if self.settings_differ(self.previous_setting, self.setting_value()):
self.update_setting(self.previous_setting)
return
setting = self.selected_setting(index)
if isinstance(setting, (tuple, list)):
setting = setting[0]
setting = self.transform_setting(setting)
if not self.settings_differ(persist.settings.get(self.setting, ''), setting):
return
self.update_setting(setting)
def update_setting(self, value):
"""Update the setting with the given value."""
persist.settings.set(self.setting, value, changed=True)
self.setting_was_changed(value)
persist.settings.save()
def settings_differ(self, old_setting, new_setting):
"""Return whether two setting values differ."""
if isinstance(new_setting, (tuple, list)):
new_setting = new_setting[0]
new_setting = self.transform_setting(new_setting)
return new_setting != old_setting
def selected_setting(self, index):
"""
Return the selected setting by index.
Subclasses may override this if they want to return something other
than the indexed value from self.settings.
"""
return self.settings[index]
def setting_was_changed(self, setting):
"""
Do something after the setting value is changed but before settings are saved.
Subclasses may override this if further action is necessary after
the setting's value is changed.
"""
pass
def choose_setting_command(setting, preview):
"""Return a decorator that provides common methods for concrete subclasses of ChooseSettingCommand."""
def decorator(cls):
def init(self, window):
super(cls, self).__init__(window, setting, preview)
def run(self, **kwargs):
"""Run the command."""
self.choose(**kwargs)
cls.setting = setting
cls.__init__ = init
cls.run = run
return cls
return decorator
@choose_setting_command('lint_mode', preview=False)
class SublimelinterChooseLintModeCommand(ChooseSettingCommand):
"""A command that selects a lint mode from a list."""
def get_settings(self):
"""Return a list of the lint modes."""
return [[name.capitalize(), description] for name, description in persist.LINT_MODES]
def setting_was_changed(self, setting):
"""Update all views when the lint mode changes."""
if setting == 'background':
from .sublimelinter import SublimeLinter
SublimeLinter.lint_all_views()
else:
linter.Linter.clear_all()
@choose_setting_command('mark_style', preview=True)
class SublimelinterChooseMarkStyleCommand(ChooseSettingCommand):
"""A command that selects a mark style from a list."""
def get_settings(self):
"""Return a list of the mark styles."""
return highlight.mark_style_names()
@choose_setting_command('gutter_theme', preview=True)
class SublimelinterChooseGutterThemeCommand(ChooseSettingCommand):
"""A command that selects a gutter theme from a list."""
def get_settings(self):
"""
Return a list of all available gutter themes, with 'None' at the end.
Whether the theme is colorized and is a SublimeLinter or user theme
is indicated below the theme name.
"""
settings = self.find_gutter_themes()
settings.append(['None', 'Do not display gutter marks'])
self.themes.append('none')
return settings
def find_gutter_themes(self):
"""
Find all SublimeLinter.gutter-theme resources.
For each found resource, if it doesn't match one of the patterns
from the "gutter_theme_excludes" setting, return the base name
of resource and info on whether the theme is a standard theme
or a user theme, as well as whether it is colorized.
The list of paths to the resources is appended to self.themes.
"""
self.themes = []
settings = []
gutter_themes = sublime.find_resources('*.gutter-theme')
excludes = persist.settings.get('gutter_theme_excludes', [])
pngs = sublime.find_resources('*.png')
for theme in gutter_themes:
# Make sure the theme has error.png and warning.png
exclude = False
parent = os.path.dirname(theme)
for name in ('error', 'warning'):
if '{}/{}.png'.format(parent, name) not in pngs:
exclude = True
if exclude:
continue
# Now see if the theme name is in gutter_theme_excludes
name = os.path.splitext(os.path.basename(theme))[0]
for pattern in excludes:
if fnmatch(name, pattern):
exclude = True
break
if exclude:
continue
self.themes.append(theme)
try:
info = json.loads(sublime.load_resource(theme))
colorize = info.get('colorize', False)
except ValueError:
colorize = False
std_theme = theme.startswith('Packages/SublimeLinter/gutter-themes/')
settings.append([
name,
'{}{}'.format(
'SublimeLinter theme' if std_theme else 'User theme',
' (colorized)' if colorize else ''
)
])
# Sort self.themes and settings in parallel using the zip trick
settings, self.themes = zip(*sorted(zip(settings, self.themes)))
# zip returns tuples, convert back to lists
settings = list(settings)
self.themes = list(self.themes)
return settings
def selected_setting(self, index):
"""Return the theme name with the given index."""
return self.themes[index]
def transform_setting(self, setting, matching=False):
"""
Return a transformed version of setting.
For gutter themes, setting is a Packages-relative path
to a .gutter-theme file.
If matching == False, return the original setting text,
gutter theme settings are not lowercased.
If matching == True, return the base name of the filename
without the .gutter-theme extension.
"""
if matching:
return os.path.splitext(os.path.basename(setting))[0]
else:
return setting
class SublimelinterToggleLinterCommand(sublime_plugin.WindowCommand):
"""A command that toggles, enables, or disables linter plugins."""
def __init__(self, window):
"""Initialize a new instance."""
super().__init__(window)
self.linters = {}
def is_visible(self, **args):
"""Return True if the command would show any linters."""
which = args['which']
if self.linters.get(which) is None:
linters = []
settings = persist.settings.get('linters', {})
for instance in persist.linter_classes:
linter_settings = settings.get(instance, {})
disabled = linter_settings.get('@disable')
if which == 'all':
include = True
instance = [instance, 'disabled' if disabled else 'enabled']
else:
include = (
which == 'enabled' and not disabled or
which == 'disabled' and disabled
)
if include:
linters.append(instance)
linters.sort()
self.linters[which] = linters
return len(self.linters[which]) > 0
def run(self, **args):
"""Run the command."""
self.which = args['which']
if self.linters[self.which]:
self.window.show_quick_panel(self.linters[self.which], self.on_done)
def on_done(self, index):
"""Completion handler for quick panel, toggle the enabled state of the chosen linter."""
if index != -1:
linter = self.linters[self.which][index]
if isinstance(linter, list):
linter = linter[0]
settings = persist.settings.get('linters', {})
linter_settings = settings.get(linter, {})
linter_settings['@disable'] = not linter_settings.get('@disable', False)
persist.settings.set('linters', settings, changed=True)
persist.settings.save()
self.linters = {}
class SublimelinterCreateLinterPluginCommand(sublime_plugin.WindowCommand):
"""A command that creates a new linter plugin."""
def run(self):
"""Run the command."""
if not sublime.ok_cancel_dialog(
'You will be asked for the linter name. Please enter the name '
'of the linter binary (including dashes), NOT the name of the language being linted. '
'For example, to lint CSS with csslint, the linter name is '
'“csslint”, NOT “css”.',
'I understand'
):
return
self.window.show_input_panel(
'Linter name:',
'',
on_done=self.copy_linter,
on_change=None,
on_cancel=None)
def copy_linter(self, name):
"""Copy the template linter to a new linter with the given name."""
self.name = name
self.fullname = 'SublimeLinter-contrib-{}'.format(name)
self.dest = os.path.join(sublime.packages_path(), self.fullname)
if os.path.exists(self.dest):
sublime.error_message('The plugin “{}” already exists.'.format(self.fullname))
return
src = os.path.join(sublime.packages_path(), persist.PLUGIN_DIRECTORY, 'linter-plugin-template')
self.temp_dir = None
try:
self.temp_dir = tempfile.mkdtemp()
self.temp_dest = os.path.join(self.temp_dir, self.fullname)
shutil.copytree(src, self.temp_dest)
self.get_linter_language(name, self.configure_linter)
except Exception as ex:
if self.temp_dir and os.path.exists(self.temp_dir):
shutil.rmtree(self.temp_dir)
sublime.error_message('An error occurred while copying the template plugin: {}'.format(str(ex)))
def configure_linter(self, language):
"""Fill out the template and move the linter into Packages."""
try:
if language is None:
return
if not self.fill_template(self.temp_dir, self.name, self.fullname, language):
return
git = util.which('git')
if git:
subprocess.call((git, 'init', self.temp_dest))
shutil.move(self.temp_dest, self.dest)
util.open_directory(self.dest)
self.wait_for_open(self.dest)
except Exception as ex:
sublime.error_message('An error occurred while configuring the plugin: {}'.format(str(ex)))
finally:
if self.temp_dir and os.path.exists(self.temp_dir):
shutil.rmtree(self.temp_dir)
def get_linter_language(self, name, callback):
"""Get the language (python, node, etc.) on which the linter is based."""
languages = ['javascript', 'python', 'ruby', 'other']
items = ['Select the language on which the linter is based:']
for language in languages:
items.append(' ' + language.capitalize())
def on_done(index):
language = languages[index - 1] if index > 0 else None
callback(language)
self.window.show_quick_panel(items, on_done)
def fill_template(self, template_dir, name, fullname, language):
"""Replace placeholders and fill template files in template_dir, return success."""
# Read per-language info
path = os.path.join(os.path.dirname(__file__), 'create_linter_info.json')
with open(path, mode='r', encoding='utf-8') as f:
try:
info = json.load(f)
except Exception as err:
persist.printf(err)
sublime.error_message('A configuration file could not be opened, the linter cannot be created.')
return False
info = info.get(language, {})
extra_attributes = []
comment_re = info.get('comment_re', 'None')
extra_attributes.append('comment_re = ' + comment_re)
attributes = info.get('attributes', [])
for attr in attributes:
extra_attributes.append(attr.format(name))
extra_attributes = '\n '.join(extra_attributes)
if extra_attributes:
extra_attributes += '\n'
extra_steps = info.get('extra_steps', '')
if isinstance(extra_steps, list):
extra_steps = '\n\n'.join(extra_steps)
if extra_steps:
extra_steps = '\n' + extra_steps + '\n'
platform = info.get('platform', language.capitalize())
# Replace placeholders
placeholders = {
'__linter__': name,
'__user__': util.get_user_fullname(),
'__year__': str(datetime.date.today().year),
'__class__': self.camel_case(name),
'__superclass__': info.get('superclass', 'Linter'),
'__cmd__': '{}@python'.format(name) if language == 'python' else name,
'__extra_attributes__': extra_attributes,
'__platform__': platform,
'__install__': info['installer'].format(name),
'__extra_install_steps__': extra_steps
}
for root, dirs, files in os.walk(template_dir):
for filename in files:
extension = os.path.splitext(filename)[1]
if extension in ('.py', '.md', '.txt'):
path = os.path.join(root, filename)
with open(path, encoding='utf-8') as f:
text = f.read()
for placeholder, value in placeholders.items():
text = text.replace(placeholder, value)
with open(path, mode='w', encoding='utf-8') as f:
f.write(text)
return True
def camel_case(self, name):
"""Convert and return a name in the form foo-bar to FooBar."""
camel_name = name[0].capitalize()
i = 1
while i < len(name):
if name[i] == '-' and i < len(name) - 1:
camel_name += name[i + 1].capitalize()
i += 1
else:
camel_name += name[i]
i += 1
return camel_name
def wait_for_open(self, dest):
"""Wait for new linter window to open in another thread."""
def open_linter_py():
"""Wait until the new linter window has opened and open linter.py."""
start = datetime.datetime.now()
while True:
time.sleep(0.25)
delta = datetime.datetime.now() - start
# Wait a maximum of 5 seconds
if delta.seconds > 5:
break
window = sublime.active_window()
folders = window.folders()
if folders and folders[0] == dest:
window.open_file(os.path.join(dest, 'linter.py'))
break
sublime.set_timeout_async(open_linter_py, 0)
class SublimelinterPackageControlCommand(sublime_plugin.WindowCommand):
"""
Abstract superclass for Package Control utility commands.
Only works if git is installed.
"""
TAG_RE = re.compile(r'(?P<major>\d+)\.(?P<minor>\d+)\.(?P<release>\d+)(?:\+\d+)?')
def __init__(self, window):
"""Initialize a new instance."""
super().__init__(window)
self.git = ''
def is_visible(self, paths=[]):
"""Return True if any eligible plugin directories are selected."""
if self.git == '':
self.git = util.which('git')
if self.git:
for path in paths:
if self.is_eligible_path(path):
return True
return False
def is_eligible_path(self, path):
"""
Return True if path is an eligible directory.
A directory is eligible if it has a messages subdirectory
and has messages.json.
"""
return (
os.path.isdir(path) and
os.path.isdir(os.path.join(path, 'messages')) and
os.path.isfile(os.path.join(path, 'messages.json'))
)
def get_current_tag(self):
"""
Return the most recent tag components.
A tuple of (major, minor, release) is returned, or (1, 0, 0) if there are no tags.
If the most recent tag does not conform to semver, return (None, None, None).
"""
tag = util.communicate(['git', 'describe', '--tags', '--abbrev=0']).strip()
if not tag:
return (1, 0, 0)
match = self.TAG_RE.match(tag)
if match:
return (int(match.group('major')), int(match.group('minor')), int(match.group('release')))
else:
return None
class SublimelinterNewPackageControlMessageCommand(SublimelinterPackageControlCommand):
"""
This command automates the process of creating new Package Control release messages.
It creates a new entry in messages.json for the next version
and creates a new file named messages/<version>.txt.
"""
COMMIT_MSG_RE = re.compile(r'{{{{(.+?)}}}}')
def __init__(self, window):
"""Initialize a new instance."""
super().__init__(window)
def run(self, paths=[]):
"""Run the command."""
for path in paths:
if self.is_eligible_path(path):
self.make_new_version_message(path)
def make_new_version_message(self, path):
"""Make a new version message for the repo at the given path."""
try:
cwd = os.getcwd()
os.chdir(path)