Conditions | 2 |
Total Lines | 404 |
Lines | 0 |
Ratio | 0 % |
Changes | 7 | ||
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 |
||
118 | def _create_linter(klass, options): |
||
119 | class LinterMeta(type): |
||
120 | |||
121 | def __repr__(cls): |
||
122 | return "<{} linter class (wrapping {!r})>".format( |
||
123 | cls.__name__, options["executable"]) |
||
124 | |||
125 | class LinterBase(LocalBear, metaclass=LinterMeta): |
||
126 | |||
127 | @staticmethod |
||
128 | def generate_config(filename, file): |
||
129 | """ |
||
130 | Generates the content of a config-file the linter-tool might need. |
||
131 | |||
132 | The contents generated from this function are written to a |
||
133 | temporary file and the path is provided inside |
||
134 | ``create_arguments()``. |
||
135 | |||
136 | By default no configuration is generated. |
||
137 | |||
138 | You can provide additional keyword arguments and defaults. These |
||
139 | will be interpreted as required settings that need to be provided |
||
140 | through a coafile-section. |
||
141 | |||
142 | :param filename: |
||
143 | The name of the file currently processed. |
||
144 | :param file: |
||
145 | The contents of the file currently processed. |
||
146 | :return: |
||
147 | The config-file-contents as a string or ``None``. |
||
148 | """ |
||
149 | return None |
||
150 | |||
151 | @staticmethod |
||
152 | def create_arguments(filename, file, config_file): |
||
153 | """ |
||
154 | Creates the arguments for the linter. |
||
155 | |||
156 | You can provide additional keyword arguments and defaults. These |
||
157 | will be interpreted as required settings that need to be provided |
||
158 | through a coafile-section. |
||
159 | |||
160 | :param filename: |
||
161 | The name of the file the linter-tool shall process. |
||
162 | :param file: |
||
163 | The contents of the file. |
||
164 | :param config_file: |
||
165 | The path of the config-file if used. ``None`` if unused. |
||
166 | :return: |
||
167 | A sequence of arguments to feed the linter-tool with. |
||
168 | """ |
||
169 | raise NotImplementedError |
||
170 | |||
171 | @staticmethod |
||
172 | def get_executable(): |
||
173 | """ |
||
174 | Returns the executable of this class. |
||
175 | |||
176 | :return: |
||
177 | The executable name. |
||
178 | """ |
||
179 | return options["executable"] |
||
180 | |||
181 | @classmethod |
||
182 | def check_prerequisites(cls): |
||
183 | """ |
||
184 | Checks whether the linter-tool the bear uses is operational. |
||
185 | |||
186 | :return: |
||
187 | True if operational, otherwise a string containing more info. |
||
188 | """ |
||
189 | if shutil.which(cls.get_executable()) is None: |
||
190 | return (repr(cls.get_executable()) + " is not installed." + |
||
191 | (" " + options["executable_check_fail_info"] |
||
192 | if options["executable_check_fail_info"] else |
||
193 | "")) |
||
194 | else: |
||
195 | if options["prerequisite_check_command"]: |
||
196 | try: |
||
197 | check_call(options["prerequisite_check_command"], |
||
198 | stdout=DEVNULL, |
||
199 | stderr=DEVNULL) |
||
200 | return True |
||
201 | except (OSError, CalledProcessError): |
||
202 | return options["prerequisite_check_fail_message"] |
||
203 | return True |
||
204 | |||
205 | @classmethod |
||
206 | def _get_create_arguments_metadata(cls): |
||
207 | return FunctionMetadata.from_function( |
||
208 | cls.create_arguments, |
||
209 | omit={"self", "filename", "file", "config_file"}) |
||
210 | |||
211 | @classmethod |
||
212 | def _get_generate_config_metadata(cls): |
||
213 | return FunctionMetadata.from_function( |
||
214 | cls.generate_config, |
||
215 | omit={"filename", "file"}) |
||
216 | |||
217 | @classmethod |
||
218 | def _get_process_output_metadata(cls): |
||
219 | metadata = FunctionMetadata.from_function(cls.process_output) |
||
220 | |||
221 | if options["output_format"] is None: |
||
222 | omitted = {"self", "output", "filename", "file"} |
||
223 | else: |
||
224 | # If a specific output format is provided, function signatures |
||
225 | # from process_output functions should not appear in the help. |
||
226 | omitted = set(chain(metadata.non_optional_params, |
||
227 | metadata.optional_params)) |
||
228 | |||
229 | metadata.omit = omitted |
||
230 | return metadata |
||
231 | |||
232 | @classmethod |
||
233 | def get_metadata(cls): |
||
234 | merged_metadata = FunctionMetadata.merge( |
||
235 | cls._get_process_output_metadata(), |
||
236 | cls._get_generate_config_metadata(), |
||
237 | cls._get_create_arguments_metadata()) |
||
238 | merged_metadata.desc = ( |
||
239 | "{}\n\nThis bear uses the {!r} tool.".format( |
||
240 | inspect.getdoc(cls), cls.get_executable())) |
||
241 | |||
242 | return merged_metadata |
||
243 | |||
244 | def _convert_output_regex_match_to_result(self, |
||
245 | match, |
||
246 | filename, |
||
247 | severity_map, |
||
248 | result_message): |
||
249 | """ |
||
250 | Converts the matched named-groups of ``output_regex`` to an actual |
||
251 | ``Result``. |
||
252 | |||
253 | :param match: |
||
254 | The regex match object. |
||
255 | :param filename: |
||
256 | The name of the file this match belongs to. |
||
257 | :param severity_map: |
||
258 | The dict to use to map the severity-match to an actual |
||
259 | ``RESULT_SEVERITY``. |
||
260 | :param result_message: |
||
261 | The static message to use for results instead of grabbing it |
||
262 | from the executable output via the ``message`` named regex |
||
263 | group. |
||
264 | """ |
||
265 | # Pre process the groups |
||
266 | groups = match.groupdict() |
||
267 | |||
268 | if 'severity' in groups: |
||
269 | try: |
||
270 | groups["severity"] = severity_map[ |
||
271 | groups["severity"].lower()] |
||
272 | except KeyError: |
||
273 | self.warn( |
||
274 | repr(groups["severity"]) + " not found in " |
||
275 | "severity-map. Assuming `RESULT_SEVERITY.NORMAL`.") |
||
276 | groups["severity"] = RESULT_SEVERITY.NORMAL |
||
277 | else: |
||
278 | groups['severity'] = RESULT_SEVERITY.NORMAL |
||
279 | |||
280 | for variable in ("line", "column", "end_line", "end_column"): |
||
281 | groups[variable] = (None |
||
282 | if groups.get(variable, None) is None else |
||
283 | int(groups[variable])) |
||
284 | |||
285 | if "origin" in groups: |
||
286 | groups["origin"] = "{} ({})".format(klass.__name__, |
||
287 | groups["origin"].strip()) |
||
288 | |||
289 | # Construct the result. |
||
290 | return Result.from_values( |
||
291 | origin=groups.get("origin", self), |
||
292 | message=(groups.get("message", "").strip() |
||
293 | if result_message is None else result_message), |
||
294 | file=filename, |
||
295 | severity=groups["severity"], |
||
296 | line=groups["line"], |
||
297 | column=groups["column"], |
||
298 | end_line=groups["end_line"], |
||
299 | end_column=groups["end_column"], |
||
300 | additional_info=groups.get("additional_info", "").strip()) |
||
301 | |||
302 | def process_output_corrected(self, |
||
303 | output, |
||
304 | filename, |
||
305 | file, |
||
306 | diff_severity=RESULT_SEVERITY.NORMAL, |
||
307 | result_message="Inconsistency found.", |
||
308 | diff_distance=1): |
||
309 | """ |
||
310 | Processes the executable's output as a corrected file. |
||
311 | |||
312 | :param output: |
||
313 | The output of the program. This can be either a single |
||
314 | string or a sequence of strings. |
||
315 | :param filename: |
||
316 | The filename of the file currently being corrected. |
||
317 | :param file: |
||
318 | The contents of the file currently being corrected. |
||
319 | :param diff_severity: |
||
320 | The severity to use for generating results. |
||
321 | :param result_message: |
||
322 | The message to use for generating results. |
||
323 | :param diff_distance: |
||
324 | Number of unchanged lines that are allowed in between two |
||
325 | changed lines so they get yielded as one diff. If a negative |
||
326 | distance is given, every change will be yielded as an own diff, |
||
327 | even if they are right beneath each other. |
||
328 | :return: |
||
329 | An iterator returning results containing patches for the |
||
330 | file to correct. |
||
331 | """ |
||
332 | if isinstance(output, str): |
||
333 | output = (output,) |
||
334 | |||
335 | for string in output: |
||
336 | for diff in Diff.from_string_arrays( |
||
337 | file, |
||
338 | string.splitlines(keepends=True)).split_diff( |
||
339 | distance=diff_distance): |
||
340 | yield Result(self, |
||
341 | result_message, |
||
342 | affected_code=diff.affected_code(filename), |
||
343 | diffs={filename: diff}, |
||
344 | severity=diff_severity) |
||
345 | |||
346 | def process_output_regex( |
||
347 | self, output, filename, file, output_regex, |
||
348 | severity_map=MappingProxyType({ |
||
349 | "critical": RESULT_SEVERITY.MAJOR, |
||
350 | "c": RESULT_SEVERITY.MAJOR, |
||
351 | "fatal": RESULT_SEVERITY.MAJOR, |
||
352 | "fail": RESULT_SEVERITY.MAJOR, |
||
353 | "f": RESULT_SEVERITY.MAJOR, |
||
354 | "error": RESULT_SEVERITY.MAJOR, |
||
355 | "err": RESULT_SEVERITY.MAJOR, |
||
356 | "e": RESULT_SEVERITY.MAJOR, |
||
357 | "warning": RESULT_SEVERITY.NORMAL, |
||
358 | "warn": RESULT_SEVERITY.NORMAL, |
||
359 | "w": RESULT_SEVERITY.NORMAL, |
||
360 | "information": RESULT_SEVERITY.INFO, |
||
361 | "info": RESULT_SEVERITY.INFO, |
||
362 | "i", RESULT_SEVERITY.INFO, |
||
363 | "suggestion", RESULT_SEVERITY.INFO}), |
||
364 | result_message=None): |
||
365 | """ |
||
366 | Processes the executable's output using a regex. |
||
367 | |||
368 | :param output: |
||
369 | The output of the program. This can be either a single |
||
370 | string or a sequence of strings. |
||
371 | :param filename: |
||
372 | The filename of the file currently being corrected. |
||
373 | :param file: |
||
374 | The contents of the file currently being corrected. |
||
375 | :param output_regex: |
||
376 | The regex to parse the output with. It should use as many |
||
377 | of the following named groups (via ``(?P<name>...)``) to |
||
378 | provide a good result: |
||
379 | |||
380 | - line - The line where the issue starts. |
||
381 | - column - The column where the issue starts. |
||
382 | - end_line - The line where the issue ends. |
||
383 | - end_column - The column where the issue ends. |
||
384 | - severity - The severity of the issue. |
||
385 | - message - The message of the result. |
||
386 | - origin - The origin of the issue. |
||
387 | - additional_info - Additional info provided by the issue. |
||
388 | |||
389 | The groups ``line``, ``column``, ``end_line`` and |
||
390 | ``end_column`` don't have to match numbers only, they can |
||
391 | also match nothing, the generated ``Result`` is filled |
||
392 | automatically with ``None`` then for the appropriate |
||
393 | properties. |
||
394 | :param severity_map: |
||
395 | A dict used to map a severity string (captured from the |
||
396 | ``output_regex`` with the named group ``severity``) to an |
||
397 | actual ``coalib.results.RESULT_SEVERITY`` for a result. |
||
398 | :param result_message: |
||
399 | The static message to use for results instead of grabbing it |
||
400 | from the executable output via the ``message`` named regex |
||
401 | group. |
||
402 | :return: |
||
403 | An iterator returning results. |
||
404 | """ |
||
405 | if isinstance(output, str): |
||
406 | output = (output,) |
||
407 | |||
408 | for string in output: |
||
409 | for match in re.finditer(output_regex, string): |
||
410 | yield self._convert_output_regex_match_to_result( |
||
411 | match, filename, severity_map=severity_map, |
||
412 | result_message=result_message) |
||
413 | |||
414 | if options["output_format"] is None: |
||
415 | # Check if user supplied a `process_output` override. |
||
416 | if not callable(getattr(klass, "process_output", None)): |
||
417 | raise ValueError("`process_output` not provided by given " |
||
418 | "class {!r}.".format(klass.__name__)) |
||
419 | # No need to assign to `process_output` here, the class mixing |
||
420 | # below automatically does that. |
||
421 | else: |
||
422 | # Prevent people from accidentally defining `process_output` |
||
423 | # manually, as this would implicitly override the internally |
||
424 | # set-up `process_output`. |
||
425 | if hasattr(klass, "process_output"): |
||
426 | raise ValueError("Found `process_output` already defined " |
||
427 | "by class {!r}, but {!r} output-format is " |
||
428 | "specified.".format(klass.__name__, |
||
429 | options["output_format"])) |
||
430 | |||
431 | if options["output_format"] == "corrected": |
||
432 | process_output_args = { |
||
433 | key: options[key] |
||
434 | for key in ("result_message", "diff_severity", |
||
435 | "diff_distance") |
||
436 | if key in options} |
||
437 | |||
438 | process_output = partialmethod( |
||
439 | process_output_corrected, **process_output_args) |
||
440 | |||
441 | else: |
||
442 | assert options["output_format"] == "regex" |
||
443 | |||
444 | process_output_args = { |
||
445 | key: options[key] |
||
446 | for key in ("output_regex", "severity_map", |
||
447 | "result_message") |
||
448 | if key in options} |
||
449 | |||
450 | process_output = partialmethod( |
||
451 | process_output_regex, **process_output_args) |
||
452 | |||
453 | @classmethod |
||
454 | @contextmanager |
||
455 | def _create_config(cls, filename, file, **kwargs): |
||
456 | """ |
||
457 | Provides a context-manager that creates the config file if the |
||
458 | user provides one and cleans it up when done with linting. |
||
459 | |||
460 | :param filename: |
||
461 | The filename of the file. |
||
462 | :param file: |
||
463 | The file contents. |
||
464 | :param kwargs: |
||
465 | Section settings passed from ``run()``. |
||
466 | :return: |
||
467 | A context-manager handling the config-file. |
||
468 | """ |
||
469 | content = cls.generate_config(filename, file, **kwargs) |
||
470 | if content is None: |
||
471 | yield None |
||
472 | else: |
||
473 | with make_temp( |
||
474 | suffix=options["config_suffix"]) as config_file: |
||
475 | with open(config_file, mode="w") as fl: |
||
476 | fl.write(content) |
||
477 | yield config_file |
||
478 | |||
479 | def run(self, filename, file, **kwargs): |
||
480 | # Get the **kwargs params to forward to `generate_config()` |
||
481 | # (from `_create_config()`). |
||
482 | generate_config_kwargs = FunctionMetadata.filter_parameters( |
||
483 | self._get_generate_config_metadata(), kwargs) |
||
484 | |||
485 | with self._create_config( |
||
486 | filename, |
||
487 | file, |
||
488 | **generate_config_kwargs) as config_file: |
||
489 | # And now retrieve the **kwargs for `create_arguments()`. |
||
490 | create_arguments_kwargs = ( |
||
491 | FunctionMetadata.filter_parameters( |
||
492 | self._get_create_arguments_metadata(), kwargs)) |
||
493 | |||
494 | args = self.create_arguments(filename, file, config_file, |
||
495 | **create_arguments_kwargs) |
||
496 | |||
497 | try: |
||
498 | args = tuple(args) |
||
499 | except TypeError: |
||
500 | self.err("The given arguments " |
||
501 | "{!r} are not iterable.".format(args)) |
||
502 | return |
||
503 | |||
504 | arguments = (self.get_executable(),) + args |
||
505 | self.debug("Running '{}'".format(' '.join(arguments))) |
||
506 | |||
507 | output = run_shell_command( |
||
508 | arguments, |
||
509 | stdin="".join(file) if options["use_stdin"] else None) |
||
510 | |||
511 | output = tuple(compress( |
||
512 | output, |
||
513 | (options["use_stdout"], options["use_stderr"]))) |
||
514 | if len(output) == 1: |
||
515 | output = output[0] |
||
516 | |||
517 | process_output_kwargs = FunctionMetadata.filter_parameters( |
||
518 | self._get_process_output_metadata(), kwargs) |
||
519 | return self.process_output(output, filename, file, |
||
520 | **process_output_kwargs) |
||
521 | |||
522 | def __repr__(self): |
||
733 |