-
-
Notifications
You must be signed in to change notification settings - Fork 272
/
util.py
1555 lines (1140 loc) · 46.3 KB
/
util.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=utf8
#
# util.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 provides general utility methods."""
from functools import lru_cache
from glob import glob
import json
import locale
from numbers import Number
import os
import getpass
import re
import shutil
from string import Template
import stat
import sublime
import subprocess
import sys
import tempfile
from xml.etree import ElementTree
if sublime.platform() != 'windows':
import pwd
#
# Public constants
#
STREAM_STDOUT = 1
STREAM_STDERR = 2
STREAM_BOTH = STREAM_STDOUT + STREAM_STDERR
PYTHON_CMD_RE = re.compile(r'(?P<script>[^@]+)?@python(?P<version>[\d\.]+)?')
VERSION_RE = re.compile(r'(?P<major>\d+)(?:\.(?P<minor>\d+))?')
INLINE_SETTINGS_RE = re.compile(r'(?i).*?\[sublimelinter[ ]+(?P<settings>[^\]]+)\]')
INLINE_SETTING_RE = re.compile(r'(?P<key>[@\w][\w\-]*)\s*:\s*(?P<value>[^\s]+)')
MENU_INDENT_RE = re.compile(r'^(\s+)\$menus', re.MULTILINE)
MARK_COLOR_RE = (
r'(\s*<string>sublimelinter\.{}</string>\s*\r?\n'
r'\s*<key>settings</key>\s*\r?\n'
r'\s*<dict>\s*\r?\n'
r'\s*<key>foreground</key>\s*\r?\n'
r'\s*<string>)#.+?(</string>\s*\r?\n)'
)
ANSI_COLOR_RE = re.compile(r'\033\[[0-9;]*m')
UNSAVED_FILENAME = 'untitled'
# Temp directory used to store temp files for linting
tempdir = os.path.join(tempfile.gettempdir(), 'SublimeLinter3-' + getpass.getuser())
# settings utils
def merge_user_settings(settings):
"""Return the default linter settings merged with the user's settings."""
default = settings.get('default', {})
user = settings.get('user', {})
if user:
linters = default.pop('linters', {})
user_linters = user.get('linters', {})
for name, data in user_linters.items():
if name in linters:
linters[name].update(data)
else:
linters[name] = data
default['linters'] = linters
user.pop('linters', None)
default.update(user)
return default
def inline_settings(comment_re, code, prefix=None, alt_prefix=None):
r"""
Return a dict of inline settings within the first two lines of code.
This method looks for settings in the form [SublimeLinter <name>:<value>]
on the first or second line of code if the lines match comment_re.
comment_re should be a compiled regex object whose pattern is unanchored (no ^)
and matches everything through the comment prefix, including leading whitespace.
For example, to specify JavaScript comments, you would use the pattern:
r'\s*/[/*]'
If prefix or alt_prefix is a non-empty string, setting names must begin with
the given prefix or alt_prefix to be considered as a setting.
A dict of matching name/value pairs is returned.
"""
if prefix:
prefix = prefix.lower() + '-'
if alt_prefix:
alt_prefix = alt_prefix.lower() + '-'
settings = {}
pos = -1
for i in range(0, 2):
# Does this line start with a comment marker?
match = comment_re.match(code, pos + 1)
if match:
# If it's a comment, does it have inline settings?
match = INLINE_SETTINGS_RE.match(code, pos + len(match.group()))
if match:
# We have inline settings, stop looking
break
# Find the next line
pos = code.find('\n', )
if pos == -1:
# If no more lines, stop looking
break
if match:
for key, value in INLINE_SETTING_RE.findall(match.group('settings')):
if prefix and key[0] != '@':
if key.startswith(prefix):
key = key[len(prefix):]
elif alt_prefix and key.startswith(alt_prefix):
key = key[len(alt_prefix):]
else:
continue
settings[key] = value
return settings
def get_view_rc_settings(view, limit=None):
"""Return the rc settings, starting at the parent directory of the given view."""
filename = view.file_name()
if filename:
return get_rc_settings(os.path.dirname(filename), limit=limit)
else:
return None
@lru_cache(maxsize=None)
def get_rc_settings(start_dir, limit=None):
"""
Search for a file named .sublimelinterrc starting in start_dir.
From start_dir it ascends towards the root directory for a maximum
of limit directories (including start_dir). If the file is found,
it is read as JSON and the resulting object is returned. If the file
is not found, None is returned.
"""
if not start_dir:
return None
path = find_file(start_dir, '.sublimelinterrc', limit=limit)
if path:
try:
with open(path, encoding='utf8') as f:
rc_settings = json.loads(f.read())
return rc_settings
except (OSError, ValueError) as ex:
from . import persist
persist.printf('ERROR: could not load \'{}\': {}'.format(path, str(ex)))
else:
return None
def generate_color_scheme(from_reload=True):
"""
Asynchronously call generate_color_scheme_async.
from_reload is True if this is called from the change callback for user settings.
"""
# If this was called from a reload of prefs, turn off the prefs observer,
# otherwise we'll end up back here when ST updates the prefs with the new color.
if from_reload:
from . import persist
def prefs_reloaded():
persist.settings.observe_prefs()
persist.settings.observe_prefs(observer=prefs_reloaded)
# ST crashes unless this is run async
sublime.set_timeout_async(generate_color_scheme_async, 0)
def generate_color_scheme_async():
"""
Generate a modified copy of the current color scheme that contains SublimeLinter color entries.
The current color scheme is checked for SublimeLinter color entries. If any are missing,
the scheme is copied, the entries are added, and the color scheme is rewritten to Packages/User/SublimeLinter.
"""
# First make sure the user prefs are valid. If not, bail.
path = os.path.join(sublime.packages_path(), 'User', 'Preferences.sublime-settings')
if (os.path.isfile(path)):
try:
with open(path, mode='r', encoding='utf-8') as f:
json = f.read()
sublime.decode_value(json)
except:
from . import persist
persist.printf('generate_color_scheme: Preferences.sublime-settings invalid, aborting')
return
prefs = sublime.load_settings('Preferences.sublime-settings')
scheme = prefs.get('color_scheme')
if scheme is None:
return
scheme_text = sublime.load_resource(scheme)
# Ensure that all SublimeLinter colors are in the scheme
scopes = {
'mark.warning': False,
'mark.error': False,
'gutter-mark': False
}
for scope in scopes:
if re.search(MARK_COLOR_RE.format(re.escape(scope)), scheme_text):
scopes[scope] = True
if False not in scopes.values():
return
# Append style dicts with our styles to the style array
plist = ElementTree.XML(scheme_text)
styles = plist.find('./dict/array')
from . import persist
for style in COLOR_SCHEME_STYLES:
color = persist.settings.get('{}_color'.format(style), DEFAULT_MARK_COLORS[style]).lstrip('#')
styles.append(ElementTree.XML(COLOR_SCHEME_STYLES[style].format(color)))
if not os.path.exists(os.path.join(sublime.packages_path(), 'User', 'SublimeLinter')):
os.makedirs(os.path.join(sublime.packages_path(), 'User', 'SublimeLinter'))
# Write the amended color scheme to Packages/User/SublimeLinter
original_name = os.path.splitext(os.path.basename(scheme))[0]
name = original_name + ' (SL)'
scheme_path = os.path.join(sublime.packages_path(), 'User', 'SublimeLinter', name + '.tmTheme')
with open(scheme_path, 'w', encoding='utf8') as f:
f.write(COLOR_SCHEME_PREAMBLE)
f.write(ElementTree.tostring(plist, encoding='unicode'))
# Set the amended color scheme to the current color scheme
path = os.path.join('User', 'SublimeLinter', os.path.basename(scheme_path))
prefs.set('color_scheme', packages_relative_path(path))
sublime.save_settings('Preferences.sublime-settings')
def change_mark_colors(error_color, warning_color):
"""Change SublimeLinter error/warning colors in user color schemes."""
error_color = error_color.lstrip('#')
warning_color = warning_color.lstrip('#')
base_path = os.path.join(sublime.packages_path(), 'User', '*.tmTheme')
sublime_path = os.path.join(sublime.packages_path(), 'User', 'SublimeLinter', '*.tmTheme')
themes = glob(sublime_path) + glob(base_path)
for theme in themes:
with open(theme, encoding='utf8') as f:
text = f.read()
if re.search(MARK_COLOR_RE.format(r'mark\.error'), text):
text = re.sub(MARK_COLOR_RE.format(r'mark\.error'), r'\1#{}\2'.format(error_color), text)
text = re.sub(MARK_COLOR_RE.format(r'mark\.warning'), r'\1#{}\2'.format(warning_color), text)
with open(theme, encoding='utf8', mode='w') as f:
f.write(text)
def install_syntaxes():
"""Asynchronously call install_syntaxes_async."""
sublime.set_timeout_async(install_syntaxes_async, 0)
def install_syntaxes_async():
"""
Install fixed syntax packages.
Unfortunately the scope definitions in some syntax definitions
(HTML at the moment) incorrectly define embedded scopes, which leads
to spurious lint errors.
This method copies all of the syntax packages in fixed_syntaxes to Packages
so that they override the built in syntax package.
"""
from . import persist
plugin_dir = os.path.dirname(os.path.dirname(__file__))
syntaxes_dir = os.path.join(plugin_dir, 'fixed-syntaxes')
for syntax in os.listdir(syntaxes_dir):
# See if our version of the syntax already exists in Packages
src_dir = os.path.join(syntaxes_dir, syntax)
version_file = os.path.join(src_dir, 'sublimelinter.version')
if not os.path.isdir(src_dir) or not os.path.isfile(version_file):
continue
with open(version_file, encoding='utf8') as f:
my_version = int(f.read().strip())
dest_dir = os.path.join(sublime.packages_path(), syntax)
version_file = os.path.join(dest_dir, 'sublimelinter.version')
if os.path.isdir(dest_dir):
if os.path.isfile(version_file):
with open(version_file, encoding='utf8') as f:
try:
other_version = int(f.read().strip())
except ValueError:
other_version = 0
persist.debug('found existing {} syntax, version {}'.format(syntax, other_version))
copy = my_version > other_version
else:
copy = sublime.ok_cancel_dialog(
'An existing {} syntax definition exists, '.format(syntax) +
'and SublimeLinter wants to overwrite it with its own version. ' +
'Is that okay?')
else:
copy = True
if copy:
copy_syntax(syntax, src_dir, my_version, dest_dir)
update_syntax_map()
def copy_syntax(syntax, src_dir, version, dest_dir):
"""Copy a customized syntax and related files to Packages."""
from . import persist
try:
cached = os.path.join(sublime.cache_path(), syntax)
if os.path.isdir(cached):
shutil.rmtree(cached)
if not os.path.exists(dest_dir):
os.mkdir(dest_dir)
for filename in os.listdir(src_dir):
shutil.copy2(os.path.join(src_dir, filename), dest_dir)
persist.printf('copied {} syntax version {}'.format(syntax, version))
except OSError as ex:
persist.printf(
'ERROR: could not copy {} syntax package: {}'
.format(syntax, str(ex))
)
def update_syntax_map():
"""Update the user syntax_map setting with any missing entries from the defaults."""
from . import persist
syntax_map = {}
syntax_map.update(persist.settings.get('syntax_map', {}))
default_syntax_map = persist.settings.plugin_settings.get('default', {}).get('syntax_map', {})
modified = False
for key, value in default_syntax_map.items():
if key not in syntax_map:
syntax_map[key] = value
modified = True
persist.debug('added syntax mapping: \'{}\' => \'{}\''.format(key, value))
if modified:
persist.settings.set('syntax_map', syntax_map)
persist.settings.save()
# menu utils
def indent_lines(text, indent):
"""Return all of the lines in text indented by prefixing with indent."""
return re.sub(r'^', indent, text, flags=re.MULTILINE)[len(indent):]
def generate_menus(**kwargs):
"""Asynchronously call generate_menus_async."""
sublime.set_timeout_async(generate_menus_async, 0)
def generate_menus_async():
"""
Generate context and Tools SublimeLinter menus.
This is done dynamically so that we can have a submenu with all
of the available gutter themes.
"""
commands = []
for chooser in CHOOSERS:
commands.append({
'caption': chooser,
'menus': build_submenu(chooser),
'toggleItems': ''
})
menus = []
indent = MENU_INDENT_RE.search(CHOOSER_MENU).group(1)
for cmd in commands:
# Indent the commands to where they want to be in the template.
# The first line doesn't need to be indented, remove the extra indent.
cmd['menus'] = indent_lines(cmd['menus'], indent)
if cmd['caption'] in TOGGLE_ITEMS:
cmd['toggleItems'] = TOGGLE_ITEMS[cmd['caption']]
cmd['toggleItems'] = indent_lines(cmd['toggleItems'], indent)
menus.append(Template(CHOOSER_MENU).safe_substitute(cmd))
menus = ',\n'.join(menus)
text = generate_menu('Context', menus)
generate_menu('Main', text)
def generate_menu(name, menu_text):
"""Generate and return a sublime-menu from a template."""
from . import persist
plugin_dir = os.path.join(sublime.packages_path(), persist.PLUGIN_DIRECTORY)
path = os.path.join(plugin_dir, '{}.sublime-menu.template'.format(name))
with open(path, encoding='utf8') as f:
template = f.read()
# Get the indent for the menus within the template,
# indent the chooser menus except for the first line.
indent = MENU_INDENT_RE.search(template).group(1)
menu_text = indent_lines(menu_text, indent)
text = Template(template).safe_substitute({'menus': menu_text})
path = os.path.join(plugin_dir, '{}.sublime-menu'.format(name))
with open(path, mode='w', encoding='utf8') as f:
f.write(text)
return text
def build_submenu(caption):
"""Generate and return a submenu with commands to select a lint mode, mark style, or gutter theme."""
setting = caption.lower()
if setting == 'lint mode':
from . import persist
names = [mode[0].capitalize() for mode in persist.LINT_MODES]
elif setting == 'mark style':
from . import highlight
names = highlight.mark_style_names()
commands = []
for name in names:
commands.append(CHOOSER_COMMAND.format(setting.replace(' ', '_'), name))
return ',\n'.join(commands)
# file/directory/environment utils
def climb(start_dir, limit=None):
"""
Generate directories, starting from start_dir.
If limit is None, stop at the root directory.
Otherwise return a maximum of limit directories.
"""
right = True
while right and (limit is None or limit > 0):
yield start_dir
start_dir, right = os.path.split(start_dir)
if limit is not None:
limit -= 1
@lru_cache(maxsize=None)
def find_file(start_dir, name, parent=False, limit=None, aux_dirs=[]):
"""
Find the given file by searching up the file hierarchy from start_dir.
If the file is found and parent is False, returns the path to the file.
If parent is True the path to the file's parent directory is returned.
If limit is None, the search will continue up to the root directory.
Otherwise a maximum of limit directories will be checked.
If aux_dirs is not empty and the file hierarchy search failed,
those directories are also checked.
"""
for d in climb(start_dir, limit=limit):
target = os.path.join(d, name)
if os.path.exists(target):
if parent:
return d
return target
for d in aux_dirs:
d = os.path.expanduser(d)
target = os.path.join(d, name)
if os.path.exists(target):
if parent:
return d
return target
def run_shell_cmd(cmd):
"""Run a shell command and return stdout."""
proc = popen(cmd, env=os.environ)
from . import persist
try:
timeout = persist.settings.get('shell_timeout', 10)
out, err = proc.communicate(timeout=timeout)
except subprocess.TimeoutExpired:
proc.kill()
out = b''
persist.printf('shell timed out after {} seconds, executing {}'.format(timeout, cmd))
return out
def extract_path(cmd, delim=':'):
"""Return the user's PATH as a colon-delimited list."""
from . import persist
persist.debug('user shell:', cmd[0])
out = run_shell_cmd(cmd).decode()
path = out.split('__SUBL_PATH__', 2)
if len(path) > 1:
path = path[1]
return ':'.join(path.strip().split(delim))
else:
persist.printf('Could not parse shell PATH output:\n' + (out if out else '<empty>'))
sublime.error_message(
'SublimeLinter could not determine your shell PATH. '
'It is unlikely that any linters will work. '
'\n\n'
'Please see the troubleshooting guide for info on how to debug PATH problems.')
return ''
def get_shell_path(env):
"""
Return the user's shell PATH using shell --login.
This method is only used on Posix systems.
"""
if 'SHELL' in env:
shell_path = env['SHELL']
shell = os.path.basename(shell_path)
# We have to delimit the PATH output with markers because
# text might be output during shell startup.
if shell in ('bash', 'zsh'):
return extract_path(
(shell_path, '-l', '-c', 'echo "__SUBL_PATH__${PATH}__SUBL_PATH__"')
)
elif shell == 'fish':
return extract_path(
(shell_path, '-l', '-c', 'echo "__SUBL_PATH__"; for p in $PATH; echo $p; end; echo "__SUBL_PATH__"'),
'\n'
)
else:
from . import persist
persist.printf('Using an unsupported shell:', shell)
# guess PATH if we haven't returned yet
split = env['PATH'].split(':')
p = env['PATH']
for path in (
'/usr/bin', '/usr/local/bin',
'/usr/local/php/bin', '/usr/local/php5/bin'
):
if path not in split:
p += (':' + path)
return p
@lru_cache(maxsize=None)
def get_environment_variable(name):
"""Return the value of the given environment variable, or None if not found."""
if os.name == 'posix':
value = None
if 'SHELL' in os.environ:
shell_path = os.environ['SHELL']
# We have to delimit the output with markers because
# text might be output during shell startup.
out = run_shell_cmd((shell_path, '-l', '-c', 'echo "__SUBL_VAR__${{{}}}__SUBL_VAR__"'.format(name))).strip()
if out:
value = out.decode().split('__SUBL_VAR__', 2)[1].strip() or None
else:
value = os.environ.get(name, None)
from . import persist
persist.debug('ENV[\'{}\'] = \'{}\''.format(name, value))
return value
def get_path_components(path):
"""Split a file path into its components and return the list of components."""
components = []
while path:
head, tail = os.path.split(path)
if tail:
components.insert(0, tail)
if head:
if head == os.path.sep or head == os.path.altsep:
components.insert(0, head)
break
path = head
else:
break
return components
def packages_relative_path(path, prefix_packages=True):
"""
Return a Packages-relative version of path with '/' as the path separator.
Sublime Text wants Packages-relative paths used in settings and in the plugin API
to use '/' as the path separator on all platforms. This method converts platform
path separators to '/'. If insert_packages = True, 'Packages' is prefixed to the
converted path.
"""
components = get_path_components(path)
if prefix_packages and components and components[0] != 'Packages':
components.insert(0, 'Packages')
return '/'.join(components)
@lru_cache(maxsize=None)
def create_environment():
"""
Return a dict with os.environ augmented with a better PATH.
On Posix systems, the user's shell PATH is added to PATH.
Platforms paths are then added to PATH by getting the
"paths" user settings for the current platform. If "paths"
has a "*" item, it is added to PATH on all platforms.
"""
from . import persist
env = {}
env.update(os.environ)
if os.name == 'posix':
env['PATH'] = get_shell_path(os.environ)
paths = persist.settings.get('paths', {})
if sublime.platform() in paths:
paths = convert_type(paths[sublime.platform()], [])
else:
paths = []
if paths:
env['PATH'] = os.pathsep.join(paths) + os.pathsep + env['PATH']
from . import persist
if persist.debug_mode():
if os.name == 'posix':
if 'SHELL' in env:
shell = 'using ' + env['SHELL']
else:
shell = 'using standard paths'
else:
shell = 'from system'
if env['PATH']:
persist.printf('computed PATH {}:\n{}\n'.format(shell, env['PATH'].replace(os.pathsep, '\n')))
# Many linters use stdin, and we convert text to utf-8
# before sending to stdin, so we have to make sure stdin
# in the target executable is looking for utf-8. Some
# linters (like ruby) need to have LANG and/or LC_CTYPE
# set as well.
env['PYTHONIOENCODING'] = 'utf8'
env['LANG'] = 'en_US.UTF-8'
env['LC_CTYPE'] = 'en_US.UTF-8'
return env
def can_exec(path):
"""Return whether the given path is a file and is executable."""
return os.path.isfile(path) and os.access(path, os.X_OK)
@lru_cache(maxsize=None)
def which(cmd, module=None):
"""
Return the full path to the given command, or None if not found.
If cmd is in the form [script]@python[version], find_python is
called to locate the appropriate version of python. If an executable
version of the script can be found, its path is returned. Otherwise
the result is a tuple of the full python path and the full path to the script
(or None if there is no script).
"""
match = PYTHON_CMD_RE.match(cmd)
if match:
args = match.groupdict()
args['module'] = module
path = find_python(**args)[0:2]
# If a script is requested and an executable path is returned
# with no script path, just use the executable.
if (
path is not None and
path[0] is not None and
path[1] is None and
args['script'] # for the case where there is no script in cmd
):
return path[0]
else:
return path
else:
return find_executable(cmd)
def extract_major_minor_version(version):
"""Extract and return major and minor versions from a string version."""
match = VERSION_RE.match(version)
if match:
return {key: int(value) if value is not None else None for key, value in match.groupdict().items()}
else:
return {'major': None, 'minor': None}
@lru_cache(maxsize=None)
def get_python_version(path):
"""Return a dict with the major/minor version of the python at path."""
try:
# Different python versions use different output streams, so check both
output = communicate((path, '-V'), '', output_stream=STREAM_BOTH)
# 'python -V' returns 'Python <version>', extract the version number
return extract_major_minor_version(output.split(' ')[1])
except Exception as ex:
from . import persist
persist.printf(
'ERROR: an error occurred retrieving the version for {}: {}'
.format(path, str(ex)))
return {'major': None, 'minor': None}
@lru_cache(maxsize=None)
def find_python(version=None, script=None, module=None):
"""
Return the path to and version of python and an optional related script.
If not None, version should be a string/numeric version of python to locate, e.g.
'3' or '3.3'. Only major/minor versions are examined. This method then does
its best to locate a version of python that satisfies the requested version.
If module is not None, Sublime Text's python version is tested against the
requested version.
If version is None, the path to the default system python is used, unless
module is not None, in which case '<builtin>' is returned.
If not None, script should be the name of a python script that is typically
installed with easy_install or pip, e.g. 'pep8' or 'pyflakes'.
A tuple of the python path, script path, major version, minor version is returned.
"""
from . import persist
persist.debug(
'find_python(version={!r}, script={!r}, module={!r})'
.format(version, script, module)
)
path = None
script_path = None
requested_version = {'major': None, 'minor': None}
if module is None:
available_version = {'major': None, 'minor': None}
else:
available_version = {
'major': sys.version_info.major,
'minor': sys.version_info.minor
}
if version is None:
# If no specific version is requested and we have a module,
# assume the linter will run using ST's python.
if module is not None:
result = ('<builtin>', script, available_version['major'], available_version['minor'])
persist.debug('find_python: <=', repr(result))
return result
# No version was specified, get the default python
path = find_executable('python')
persist.debug('find_python: default python =', path)
else:
version = str(version)
requested_version = extract_major_minor_version(version)
persist.debug('find_python: requested version =', repr(requested_version))
# If there is no module, we will use a system python.
# If there is a module, a specific version was requested,
# and the builtin version does not fulfill the request,
# use the system python.
if module is None:
need_system_python = True
else:
persist.debug('find_python: available version =', repr(available_version))
need_system_python = not version_fulfills_request(available_version, requested_version)
path = '<builtin>'
if need_system_python:
if sublime.platform() in ('osx', 'linux'):
path = find_posix_python(version)
else:
path = find_windows_python(version)
persist.debug('find_python: system python =', path)
if path and path != '<builtin>':
available_version = get_python_version(path)
persist.debug('find_python: available version =', repr(available_version))
if version_fulfills_request(available_version, requested_version):
if script:
script_path = find_python_script(path, script)
persist.debug('find_python: {!r} path = {}'.format(script, script_path))
if script_path is None:
path = None
elif script_path.endswith('.exe'):
path = script_path
script_path = None
else:
path = script_path = None
result = (path, script_path, available_version['major'], available_version['minor'])
persist.debug('find_python: <=', repr(result))
return result
def version_fulfills_request(available_version, requested_version):
"""
Return whether available_version fulfills requested_version.
Both are dicts with 'major' and 'minor' items.
"""
# No requested major version is fulfilled by anything
if requested_version['major'] is None:
return True
# If major version is requested, that at least must match
if requested_version['major'] != available_version['major']:
return False
# Major version matches, if no requested minor version it's a match
if requested_version['minor'] is None:
return True
# If a minor version is requested, the available minor version must be >=
return (
available_version['minor'] is not None and
available_version['minor'] >= requested_version['minor']
)
@lru_cache(maxsize=None)
def find_posix_python(version):
"""Find the nearest version of python and return its path."""
from . import persist
if version:
# Try the exact requested version first
path = find_executable('python' + version)
persist.debug('find_posix_python: python{} => {}'.format(version, path))
# If that fails, try the major version
if not path:
path = find_executable('python' + version[0])
persist.debug('find_posix_python: python{} => {}'.format(version[0], path))
# If the major version failed, see if the default is available
if not path:
path = find_executable('python')
persist.debug('find_posix_python: python =>', path)
else:
path = find_executable('python')
persist.debug('find_posix_python: python =>', path)
return path
@lru_cache(maxsize=None)
def find_windows_python(version):
"""Find the nearest version of python and return its path."""
if version:
# On Windows, there may be no separately named python/python3 binaries,
# so it seems the only reliable way to check for a given version is to
# check the root drive for 'Python*' directories, and try to match the
# version based on the directory names. The 'Python*' directories end
# with the <major><minor> version number, so for matching with the version
# passed in, strip any decimal points.