-
-
Notifications
You must be signed in to change notification settings - Fork 761
Expand file tree
/
Copy pathcore.py
More file actions
207 lines (153 loc) · 5.63 KB
/
core.py
File metadata and controls
207 lines (153 loc) · 5.63 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
"""Pylama's core functionality.
Prepare params, check a modeline and run the checkers.
"""
import logging
import sys
import os.path as op
from .config import process_value, LOGGER, MODELINE_RE, SKIP_PATTERN, CURDIR
from .errors import Error, remove_duplicates
from .lint.extensions import LINTERS
def run(path='', code=None, rootdir=CURDIR, options=None):
"""Run code checkers with given params.
:param path: (str) A file's path.
:param code: (str) A code source
:return errors: list of dictionaries with error's information
"""
errors = []
fileconfig = dict()
linters = LINTERS
linters_params = dict()
lname = 'undefined'
params = dict()
path = op.relpath(path, rootdir)
if options:
linters = options.linters
linters_params = options.linters_params
for mask in options.file_params:
if mask.match(path):
fileconfig.update(options.file_params[mask])
if options.skip and any(p.match(path) for p in options.skip):
LOGGER.info('Skip checking for path: %s', path)
return []
try:
with CodeContext(code, path) as ctx:
code = ctx.code
params = prepare_params(parse_modeline(code), fileconfig, options)
LOGGER.debug('Checking params: %s', params)
if params.get('skip'):
return errors
for item in params.get('linters') or linters:
if not isinstance(item, tuple):
item = (item, LINTERS.get(item))
lname, linter = item
if not linter:
continue
lparams = linters_params.get(lname, dict())
LOGGER.info("Run %s %s", lname, lparams)
linter_errors = linter.run(
path, code=code, ignore=params.get("ignore", set()),
select=params.get("select", set()), params=lparams)
if linter_errors:
for er in linter_errors:
errors.append(Error(filename=path, linter=lname, **er))
except IOError as e:
LOGGER.debug("IOError %s", e)
errors.append(Error(text=str(e), filename=path, linter=lname))
except SyntaxError as e:
LOGGER.debug("SyntaxError %s", e)
errors.append(
Error(linter='pylama', lnum=e.lineno, col=e.offset,
text='E0100 SyntaxError: {}'.format(e.args[0]),
filename=path))
except Exception as e: # noqa
import traceback
LOGGER.info(traceback.format_exc())
errors = filter_errors(errors, **params) # noqa
errors = list(remove_duplicates(errors))
if code and errors:
errors = filter_skiplines(code, errors)
key = lambda e: e.lnum
if options and options.sort:
sort = dict((v, n) for n, v in enumerate(options.sort, 1))
key = lambda e: (sort.get(e.type, 999), e.lnum)
return sorted(errors, key=key)
def parse_modeline(code):
"""Parse params from file's modeline.
:return dict: Linter params.
"""
seek = MODELINE_RE.search(code)
if seek:
return dict(v.split('=') for v in seek.group(1).split(':'))
return dict()
def prepare_params(modeline, fileconfig, options):
"""Prepare and merge a params from modelines and configs.
:return dict:
"""
params = dict(skip=False, ignore=[], select=[], linters=[])
if options:
params['ignore'] = list(options.ignore)
params['select'] = list(options.select)
for config in filter(None, [modeline, fileconfig]):
for key in ('ignore', 'select', 'linters'):
params[key] += process_value(key, config.get(key, []))
params['skip'] = bool(int(config.get('skip', False)))
params['ignore'] = set(params['ignore'])
params['select'] = set(params['select'])
return params
def filter_errors(errors, select=None, ignore=None, **params):
"""Filter errors by select and ignore options.
:return bool:
"""
select = select or []
ignore = ignore or []
for e in errors:
for s in select:
if e.number.startswith(s):
yield e
break
else:
for s in ignore:
if e.number.startswith(s):
break
else:
yield e
def filter_skiplines(code, errors):
"""Filter lines by `noqa`.
:return list: A filtered errors
"""
if not errors:
return errors
enums = set(er.lnum for er in errors)
removed = set([
num for num, l in enumerate(code.split('\n'), 1)
if num in enums and SKIP_PATTERN(l)
])
if removed:
errors = [er for er in errors if er.lnum not in removed]
return errors
class CodeContext(object):
"""Read file if code is None. """
def __init__(self, code, path):
""" Init context. """
self.code = code
self.path = path
self._file = None
def __enter__(self):
""" Open a file and read it. """
if self.code is None:
LOGGER.info("File is reading: %s", self.path)
if sys.version_info >= (3, ):
# 'U' mode is deprecated in python 3
mode = 'r'
else:
mode = 'rU'
self._file = open(self.path, mode)
self.code = self._file.read()
return self
def __exit__(self, t, value, traceback):
""" Close the file which was opened. """
if self._file is not None:
self._file.close()
if t and LOGGER.level == logging.DEBUG:
LOGGER.debug(traceback)
# pylama:ignore=R0912,D210,F0001