-
Notifications
You must be signed in to change notification settings - Fork 3
/
eslint_styler.py
74 lines (58 loc) · 2.32 KB
/
eslint_styler.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
# -*- coding: utf-8 -*-
"""ESLint plugin for zazu."""
import zazu.styler
zazu.util.lazy_import(locals(), [
'click',
'json',
'os',
'subprocess'
])
__author__ = "Patrick Moore"
__copyright__ = "Copyright 2018"
class ESLintStyler(zazu.styler.Styler):
"""ESLint plugin for code styling."""
def style_string(self, string, filepath):
"""Fix a string to be within style guidelines.
Args:
string (str): the string to style
filepath (str): the filepath of the file being styled
Returns:
Styled string.
"""
eslint = 'eslint'
cwd = os.path.normpath(os.getcwd())
dirname = os.path.normpath(os.path.dirname(filepath))
loop_count = 0
local_eslint = os.path.join('node_modules', 'eslint', 'bin', 'eslint.js')
while True and loop_count < 100:
loop_count = loop_count + 1
maybe_eslint = os.path.join(dirname, local_eslint)
if os.path.isfile(maybe_eslint):
eslint = maybe_eslint
break
elif os.path.realpath(dirname) == cwd:
# Stop searching for eslint above current working directory
# An invalid filepath should break-out here
break
elif os.path.realpath(dirname) == os.path.normpath('/'):
# Stop searching when dirname and maybe_eslint are same
# This should be the filesystem root
break
dirname = os.path.normpath(os.path.join(dirname, '..'))
if loop_count >= 100:
raise click.ClickException('Unable to find eslint.js')
args = [eslint, '-f', 'json', '--fix-dry-run', '--stdin', '--stdin-filename', filepath] + self.options
try:
p = subprocess.Popen(args=args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
results, _ = p.communicate(string)
except OSError:
raise click.ClickException('Unable to find {}'.format(args[0]))
return json.loads(results)[0].get('output', string)
@staticmethod
def default_extensions():
"""Return the list of file extensions that are compatible with this Styler."""
return ['*.js']
@staticmethod
def type():
"""Return the string type of this Styler."""
return 'eslint'