Conditions | 1 |
Total Lines | 351 |
Lines | 0 |
Ratio | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | from contextlib import contextmanager |
||
111 | def _create_linter(klass, options): |
||
112 | class LinterMeta(type): |
||
113 | |||
114 | def __repr__(cls): |
||
115 | return "<{} linter class (wrapping {})>".format( |
||
116 | cls.__name__, repr(options["executable"])) |
||
117 | |||
118 | class LinterBase(LocalBear, metaclass=LinterMeta): |
||
|
|||
119 | |||
120 | @staticmethod |
||
121 | def generate_config(filename, file): |
||
122 | """ |
||
123 | Generates the content of a config-file the linter-tool might |
||
124 | need. |
||
125 | |||
126 | The contents generated from this function are written to a |
||
127 | temporary file and the path is provided inside |
||
128 | ``create_arguments()``. |
||
129 | |||
130 | By default no configuration is generated. |
||
131 | |||
132 | You can provide additional keyword arguments and defaults. These |
||
133 | will be interpreted as required settings that need to be provided |
||
134 | through a coafile-section. |
||
135 | |||
136 | :param filename: |
||
137 | The name of the file currently processed. |
||
138 | :param file: |
||
139 | The contents of the file currently processed. |
||
140 | :return: |
||
141 | The config-file-contents as a string or ``None``. |
||
142 | """ |
||
143 | return None |
||
144 | |||
145 | @staticmethod |
||
146 | def create_arguments(filename, file, config_file): |
||
147 | """ |
||
148 | Creates the arguments for the linter. |
||
149 | |||
150 | You can provide additional keyword arguments and defaults. These |
||
151 | will be interpreted as required settings that need to be provided |
||
152 | through a coafile-section. |
||
153 | |||
154 | :param filename: |
||
155 | The name of the file the linter-tool shall process. |
||
156 | :param file: |
||
157 | The contents of the file. |
||
158 | :param config_file: |
||
159 | The path of the config-file if used. ``None`` if unused. |
||
160 | :return: |
||
161 | A sequence of arguments to feed the linter-tool with. |
||
162 | """ |
||
163 | raise NotImplementedError |
||
164 | |||
165 | @staticmethod |
||
166 | def get_executable(): |
||
167 | """ |
||
168 | Returns the executable of this class. |
||
169 | |||
170 | :return: |
||
171 | The executable name. |
||
172 | """ |
||
173 | return options["executable"] |
||
174 | |||
175 | @classmethod |
||
176 | def check_prerequisites(cls): |
||
177 | """ |
||
178 | Checks whether the linter-tool the bear uses is operational. |
||
179 | |||
180 | :return: |
||
181 | True if operational, otherwise a string containing more info. |
||
182 | """ |
||
183 | if shutil.which(cls.get_executable()) is None: |
||
184 | return repr(cls.get_executable()) + " is not installed." |
||
185 | else: |
||
186 | if options["prerequisite_check_command"]: |
||
187 | try: |
||
188 | check_call(options["prerequisite_check_command"], |
||
189 | stdout=DEVNULL, |
||
190 | stderr=DEVNULL) |
||
191 | return True |
||
192 | except (OSError, CalledProcessError): |
||
193 | return options["prerequisite_check_fail_message"] |
||
194 | return True |
||
195 | |||
196 | @classmethod |
||
197 | def _get_create_arguments_metadata(cls): |
||
198 | return FunctionMetadata.from_function( |
||
199 | cls.create_arguments, |
||
200 | omit={"filename", "file", "config_file"}) |
||
201 | |||
202 | @classmethod |
||
203 | def _get_generate_config_metadata(cls): |
||
204 | return FunctionMetadata.from_function( |
||
205 | cls.generate_config, |
||
206 | omit={"filename", "file"}) |
||
207 | |||
208 | @classmethod |
||
209 | def _get_process_output_metadata(cls): |
||
210 | return FunctionMetadata.from_function( |
||
211 | cls.process_output, |
||
212 | omit={"self", "output", "filename", "file"}) |
||
213 | |||
214 | @classmethod |
||
215 | def get_metadata(cls): |
||
216 | merged_metadata = FunctionMetadata.merge( |
||
217 | cls._get_process_output_metadata(), |
||
218 | cls._get_generate_config_metadata(), |
||
219 | cls._get_create_arguments_metadata()) |
||
220 | merged_metadata.desc = inspect.getdoc(cls) |
||
221 | return merged_metadata |
||
222 | |||
223 | def _convert_output_regex_match_to_result(self, |
||
224 | match, |
||
225 | filename, |
||
226 | severity_map): |
||
227 | """ |
||
228 | Converts the matched named-groups of ``output_regex`` to an actual |
||
229 | ``Result``. |
||
230 | |||
231 | :param match: |
||
232 | The regex match object. |
||
233 | :param filename: |
||
234 | The name of the file this match belongs to. |
||
235 | :param severity_map: |
||
236 | The dict to use to map the severity-match to an actual |
||
237 | ``RESULT_SEVERITY``. |
||
238 | """ |
||
239 | # Pre process the groups |
||
240 | groups = match.groupdict() |
||
241 | |||
242 | try: |
||
243 | groups["severity"] = severity_map[ |
||
244 | groups["severity"].lower()] |
||
245 | except KeyError: |
||
246 | self.warn( |
||
247 | repr(groups["severity"]) + " not found in severity-map. " |
||
248 | "Assuming `RESULT_SEVERITY.NORMAL`.") |
||
249 | groups["severity"] = RESULT_SEVERITY.NORMAL |
||
250 | |||
251 | for variable in ("line", "column", "end_line", "end_column"): |
||
252 | groups[variable] = (None |
||
253 | if groups.get(variable, "") == "" else |
||
254 | int(groups[variable])) |
||
255 | |||
256 | if "origin" in groups: |
||
257 | groups["origin"] = "{} ({})".format(klass.__name__, |
||
258 | groups["origin"]) |
||
259 | |||
260 | # Construct the result. |
||
261 | return Result.from_values( |
||
262 | origin=groups.get("origin", self), |
||
263 | message=groups.get("message", ""), |
||
264 | file=filename, |
||
265 | severity=groups["severity"], |
||
266 | line=groups["line"], |
||
267 | column=groups["column"], |
||
268 | end_line=groups["end_line"], |
||
269 | end_column=groups["end_column"]) |
||
270 | |||
271 | def process_output_corrected(self, |
||
272 | output, |
||
273 | filename, |
||
274 | file, |
||
275 | diff_severity=RESULT_SEVERITY.NORMAL, |
||
276 | diff_message="Inconsistency found."): |
||
277 | """ |
||
278 | Processes the executable's output as a corrected file. |
||
279 | |||
280 | :param output: |
||
281 | The output of the program. This can be either a single |
||
282 | string or a sequence of strings. |
||
283 | :param filename: |
||
284 | The filename of the file currently being corrected. |
||
285 | :param file: |
||
286 | The contents of the file currently being corrected. |
||
287 | :param diff_severity: |
||
288 | The severity to use for generating results. |
||
289 | :param diff_message: |
||
290 | The message to use for generating results. |
||
291 | :return: |
||
292 | An iterator returning results containing patches for the |
||
293 | file to correct. |
||
294 | """ |
||
295 | if isinstance(output, str): |
||
296 | output = (output,) |
||
297 | |||
298 | for string in output: |
||
299 | for diff in Diff.from_string_arrays( |
||
300 | file, |
||
301 | string.splitlines(keepends=True)).split_diff(): |
||
302 | yield Result(self, |
||
303 | diff_message, |
||
304 | affected_code=(diff.range(filename),), |
||
305 | diffs={filename: diff}, |
||
306 | severity=diff_severity) |
||
307 | |||
308 | def process_output_regex( |
||
309 | self, output, filename, file, output_regex, |
||
310 | severity_map=MappingProxyType({ |
||
311 | "error": RESULT_SEVERITY.MAJOR, |
||
312 | "warning": RESULT_SEVERITY.NORMAL, |
||
313 | "warn": RESULT_SEVERITY.NORMAL, |
||
314 | "info": RESULT_SEVERITY.INFO})): |
||
315 | """ |
||
316 | Processes the executable's output using a regex. |
||
317 | |||
318 | :param output: |
||
319 | The output of the program. This can be either a single |
||
320 | string or a sequence of strings. |
||
321 | :param filename: |
||
322 | The filename of the file currently being corrected. |
||
323 | :param file: |
||
324 | The contents of the file currently being corrected. |
||
325 | :param output_regex: |
||
326 | The regex to parse the output with. It should use as many |
||
327 | of the following named groups (via ``(?P<name>...)``) to |
||
328 | provide a good result: |
||
329 | |||
330 | - line - The line where the issue starts. |
||
331 | - column - The column where the issue starts. |
||
332 | - end_line - The line where the issue ends. |
||
333 | - end_column - The column where the issue ends. |
||
334 | - severity - The severity of the issue. |
||
335 | - message - The message of the result. |
||
336 | - origin - The origin of the issue. |
||
337 | |||
338 | The groups ``line``, ``column``, ``end_line`` and |
||
339 | ``end_column`` don't have to match numbers only, they can |
||
340 | also match nothing, the generated ``Result`` is filled |
||
341 | automatically with ``None`` then for the appropriate |
||
342 | properties. |
||
343 | :param severity_map: |
||
344 | A dict used to map a severity string (captured from the |
||
345 | ``output_regex`` with the named group ``severity``) to an |
||
346 | actual ``coalib.results.RESULT_SEVERITY`` for a result. |
||
347 | :return: |
||
348 | An iterator returning results. |
||
349 | """ |
||
350 | if isinstance(output, str): |
||
351 | output = (output,) |
||
352 | |||
353 | for string in output: |
||
354 | for match in re.finditer(output_regex, string): |
||
355 | yield self._convert_output_regex_match_to_result( |
||
356 | match, filename, severity_map=severity_map) |
||
357 | |||
358 | if options["output_format"] is None: |
||
359 | # Check if user supplied a `process_output` override. |
||
360 | if not callable(getattr(klass, "process_output", None)): |
||
361 | raise ValueError("`process_output` not provided by given " |
||
362 | "class {}.".format(repr(klass.__name__))) |
||
363 | # No need to assign to `process_output` here, the class mixing |
||
364 | # below automatically does that. |
||
365 | else: |
||
366 | # Prevent people from accidentally defining `process_output` |
||
367 | # manually, as this would implicitly override the internally |
||
368 | # set-up `process_output`. |
||
369 | if hasattr(klass, "process_output"): |
||
370 | raise ValueError("Found `process_output` already defined " |
||
371 | "by class {}, but {} output-format is " |
||
372 | "specified.".format( |
||
373 | repr(klass.__name__), |
||
374 | repr(options["output_format"]))) |
||
375 | |||
376 | if options["output_format"] == "corrected": |
||
377 | process_output_args = { |
||
378 | key: options[key] |
||
379 | for key in ("diff_message", "diff_severity") |
||
380 | if key in options} |
||
381 | |||
382 | process_output = partialmethod( |
||
383 | process_output_corrected, **process_output_args) |
||
384 | |||
385 | else: |
||
386 | assert options["output_format"] == "regex" |
||
387 | |||
388 | process_output_args = { |
||
389 | key: options[key] |
||
390 | for key in ("output_regex", "severity_map") |
||
391 | if key in options} |
||
392 | |||
393 | process_output = partialmethod( |
||
394 | process_output_regex, **process_output_args) |
||
395 | |||
396 | @classmethod |
||
397 | @contextmanager |
||
398 | def _create_config(cls, filename, file, **kwargs): |
||
399 | """ |
||
400 | Provides a context-manager that creates the config file if the |
||
401 | user provides one and cleans it up when done with linting. |
||
402 | |||
403 | :param filename: |
||
404 | The filename of the file. |
||
405 | :param file: |
||
406 | The file contents. |
||
407 | :param kwargs: |
||
408 | Section settings passed from ``run()``. |
||
409 | :return: |
||
410 | A context-manager handling the config-file. |
||
411 | """ |
||
412 | content = cls.generate_config(filename, file, **kwargs) |
||
413 | if content is None: |
||
414 | yield None |
||
415 | else: |
||
416 | with make_temp( |
||
417 | suffix=options["config_suffix"]) as config_file: |
||
418 | with open(config_file, mode="w") as fl: |
||
419 | fl.write(content) |
||
420 | yield config_file |
||
421 | |||
422 | def run(self, filename, file, **kwargs): |
||
423 | # Get the **kwargs params to forward to `generate_config()` |
||
424 | # (from `_create_config()`). |
||
425 | generate_config_kwargs = FunctionMetadata.filter_parameters( |
||
426 | self._get_generate_config_metadata(), kwargs) |
||
427 | |||
428 | with self._create_config( |
||
429 | filename, |
||
430 | file, |
||
431 | **generate_config_kwargs) as config_file: |
||
432 | # And now retrieve the **kwargs for `create_arguments()`. |
||
433 | create_arguments_kwargs = ( |
||
434 | FunctionMetadata.filter_parameters( |
||
435 | self._get_create_arguments_metadata(), kwargs)) |
||
436 | |||
437 | output = run_shell_command( |
||
438 | (self.get_executable(),) + tuple(self.create_arguments( |
||
439 | filename, file, config_file, |
||
440 | **create_arguments_kwargs)), |
||
441 | stdin="".join(file) if options["use_stdin"] else None) |
||
442 | |||
443 | output = tuple(compress( |
||
444 | output, |
||
445 | (options["use_stdout"], options["use_stderr"]))) |
||
446 | if len(output) == 1: |
||
447 | output = output[0] |
||
448 | |||
449 | process_output_kwargs = FunctionMetadata.filter_parameters( |
||
450 | self._get_process_output_metadata(), kwargs) |
||
451 | return self.process_output(output, filename, file, |
||
452 | **process_output_kwargs) |
||
453 | |||
454 | def __repr__(self): |
||
455 | return "<{} linter object (wrapping {}) at {}>".format( |
||
456 | type(self).__name__, repr(self.get_executable()), hex(id(self))) |
||
457 | |||
458 | # Mixin the linter into the user-defined interface, otherwise |
||
459 | # `create_arguments` and other methods would be overridden by the |
||
460 | # default version. |
||
461 | return type(klass.__name__, (klass, LinterBase), {}) |
||
462 | |||
648 |