Total Complexity | 47 |
Total Lines | 390 |
Duplicated Lines | 0 % |
Complex classes like LinterBase often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
1 | from contextlib import contextmanager |
||
292 | class LinterBase(LocalBear, metaclass=LinterMeta): |
||
|
|||
293 | |||
294 | @staticmethod |
||
295 | def generate_config(filename, file): |
||
296 | """ |
||
297 | Generates the content of a config-file the linter-tool might |
||
298 | need. |
||
299 | |||
300 | The contents generated from this function are written to a |
||
301 | temporary file and the path is provided inside |
||
302 | ``create_arguments()``. |
||
303 | |||
304 | By default no configuration is generated. |
||
305 | |||
306 | You can provide additional keyword arguments and defaults. |
||
307 | These will be interpreted as required settings that need to be |
||
308 | provided through a coafile-section. |
||
309 | |||
310 | :param filename: |
||
311 | The name of the file currently processed. |
||
312 | :param file: |
||
313 | The contents of the file currently processed. |
||
314 | :return: |
||
315 | The config-file-contents as a string or ``None``. |
||
316 | """ |
||
317 | return None |
||
318 | |||
319 | @staticmethod |
||
320 | def create_arguments(filename, file, config_file): |
||
321 | """ |
||
322 | Creates the arguments for the linter. |
||
323 | |||
324 | You can provide additional keyword arguments and defaults. |
||
325 | These will be interpreted as required settings that need to be |
||
326 | provided through a coafile-section. |
||
327 | |||
328 | :param filename: |
||
329 | The name of the file the linter-tool shall process. |
||
330 | :param file: |
||
331 | The contents of the file. |
||
332 | :param config_file: |
||
333 | The path of the config-file if used. ``None`` if unused. |
||
334 | :return: |
||
335 | A sequence of arguments to feed the linter-tool with. |
||
336 | """ |
||
337 | raise NotImplementedError |
||
338 | |||
339 | @staticmethod |
||
340 | def get_executable(): |
||
341 | """ |
||
342 | Returns the executable of this class. |
||
343 | |||
344 | :return: |
||
345 | The executable name. |
||
346 | """ |
||
347 | return options["executable"] |
||
348 | |||
349 | @classmethod |
||
350 | def check_prerequisites(cls): |
||
351 | """ |
||
352 | Checks whether the linter-tool the bear uses is operational. |
||
353 | |||
354 | :return: |
||
355 | True if available, otherwise a string containing more info. |
||
356 | """ |
||
357 | if shutil.which(cls.get_executable()) is None: |
||
358 | return repr(cls.get_executable()) + " is not installed." |
||
359 | else: |
||
360 | if options["prerequisite_check_command"]: |
||
361 | try: |
||
362 | check_call(options["prerequisite_check_command"], |
||
363 | stdout=DEVNULL, |
||
364 | stderr=DEVNULL) |
||
365 | return True |
||
366 | except (OSError, CalledProcessError): |
||
367 | return options["prerequisite_check_fail_message"] |
||
368 | return True |
||
369 | |||
370 | @classmethod |
||
371 | def _get_create_arguments_metadata(cls): |
||
372 | return FunctionMetadata.from_function( |
||
373 | cls.create_arguments, |
||
374 | omit={"filename", "file", "config_file"}) |
||
375 | |||
376 | @classmethod |
||
377 | def _get_generate_config_metadata(cls): |
||
378 | return FunctionMetadata.from_function( |
||
379 | cls.generate_config, |
||
380 | omit={"filename", "file"}) |
||
381 | |||
382 | @classmethod |
||
383 | def _get_process_output_metadata(cls): |
||
384 | return FunctionMetadata.from_function( |
||
385 | cls.process_output, |
||
386 | omit={"self", "output", "filename", "file"}) |
||
387 | |||
388 | @classmethod |
||
389 | def get_non_optional_settings(cls): |
||
390 | return cls.get_metadata().non_optional_params |
||
391 | |||
392 | @classmethod |
||
393 | def get_metadata(cls): |
||
394 | merged_metadata = FunctionMetadata.merge( |
||
395 | cls._get_process_output_metadata(), |
||
396 | cls._get_generate_config_metadata(), |
||
397 | cls._get_create_arguments_metadata()) |
||
398 | merged_metadata.desc = inspect.getdoc(cls) |
||
399 | return merged_metadata |
||
400 | |||
401 | @classmethod |
||
402 | def _execute_command(cls, args, stdin=None): |
||
403 | """ |
||
404 | Executes the underlying tool with the given arguments. |
||
405 | |||
406 | :param args: |
||
407 | The argument sequence to pass to the executable. |
||
408 | :param stdin: |
||
409 | Input to send to the opened process as stdin. |
||
410 | :return: |
||
411 | A tuple with ``(stdout, stderr)``. |
||
412 | """ |
||
413 | return run_shell_command( |
||
414 | (cls.get_executable(),) + tuple(args), |
||
415 | stdin=stdin) |
||
416 | |||
417 | def _convert_output_regex_match_to_result(self, |
||
418 | match, |
||
419 | filename, |
||
420 | severity_map): |
||
421 | """ |
||
422 | Converts the matched named-groups of ``output_regex`` to an |
||
423 | actual ``Result``. |
||
424 | |||
425 | :param match: |
||
426 | The regex match object. |
||
427 | :param filename: |
||
428 | The name of the file this match belongs to. |
||
429 | :param severity_map: |
||
430 | The dict to use to map the severity-match to an actual |
||
431 | ``RESULT_SEVERITY``. |
||
432 | """ |
||
433 | # Pre process the groups |
||
434 | groups = match.groupdict() |
||
435 | |||
436 | try: |
||
437 | groups["severity"] = severity_map[ |
||
438 | groups["severity"].lower()] |
||
439 | except KeyError: |
||
440 | self.warn( |
||
441 | "No correspondence for " + repr(groups["severity"]) + |
||
442 | " found in given severity map. Assuming " |
||
443 | "`RESULT_SEVERITY.NORMAL`.") |
||
444 | groups["severity"] = RESULT_SEVERITY.NORMAL |
||
445 | |||
446 | for variable in ("line", "column", "end_line", "end_column"): |
||
447 | groups[variable] = (None |
||
448 | if groups.get(variable, "") == "" else |
||
449 | int(groups[variable])) |
||
450 | |||
451 | if "origin" in groups: |
||
452 | groups["origin"] = "{} ({})".format( |
||
453 | str(klass.__name__), |
||
454 | str(groups["origin"])) |
||
455 | |||
456 | # Construct the result. |
||
457 | return Result.from_values( |
||
458 | origin=groups.get("origin", self), |
||
459 | message=groups.get("message", ""), |
||
460 | file=filename, |
||
461 | severity=int(groups.get("severity", |
||
462 | RESULT_SEVERITY.NORMAL)), |
||
463 | line=groups["line"], |
||
464 | column=groups["column"], |
||
465 | end_line=groups["end_line"], |
||
466 | end_column=groups["end_column"]) |
||
467 | |||
468 | def process_output_corrected(self, |
||
469 | output, |
||
470 | filename, |
||
471 | file, |
||
472 | diff_severity=RESULT_SEVERITY.NORMAL, |
||
473 | diff_message="Inconsistency found."): |
||
474 | """ |
||
475 | Processes the executable's output as a corrected file. |
||
476 | |||
477 | :param output: |
||
478 | The output of the program. This can be either a single |
||
479 | string or a sequence of strings. |
||
480 | :param filename: |
||
481 | The filename of the file currently being corrected. |
||
482 | :param file: |
||
483 | The contents of the file currently being corrected. |
||
484 | :param diff_severity: |
||
485 | The severity to use for generating results. |
||
486 | :param diff_message: |
||
487 | The message to use for generating results. |
||
488 | :return: |
||
489 | An iterator returning results containing patches for the |
||
490 | file to correct. |
||
491 | """ |
||
492 | if isinstance(output, str): |
||
493 | output = (output,) |
||
494 | |||
495 | for string in output: |
||
496 | for diff in Diff.from_string_arrays( |
||
497 | file, |
||
498 | string.splitlines(keepends=True)).split_diff(): |
||
499 | yield Result(self, |
||
500 | diff_message, |
||
501 | affected_code=(diff.range(filename),), |
||
502 | diffs={filename: diff}, |
||
503 | severity=diff_severity) |
||
504 | |||
505 | def process_output_regex( |
||
506 | self, |
||
507 | output, |
||
508 | filename, |
||
509 | file, |
||
510 | output_regex, |
||
511 | severity_map=MappingProxyType({ |
||
512 | "error": RESULT_SEVERITY.MAJOR, |
||
513 | "warning": RESULT_SEVERITY.NORMAL, |
||
514 | "warn": RESULT_SEVERITY.NORMAL, |
||
515 | "info": RESULT_SEVERITY.INFO})): |
||
516 | """ |
||
517 | Processes the executable's output using a regex. |
||
518 | |||
519 | :param output: |
||
520 | The output of the program. This can be either a single |
||
521 | string or a sequence of strings. |
||
522 | :param filename: |
||
523 | The filename of the file currently being corrected. |
||
524 | :param file: |
||
525 | The contents of the file currently being corrected. |
||
526 | :param output_regex: |
||
527 | The regex to parse the output with. It should use as many |
||
528 | of the following named groups (via ``(?P<name>...)``) to |
||
529 | provide a good result: |
||
530 | |||
531 | - line - The line where the issue starts. |
||
532 | - column - The column where the issue starts. |
||
533 | - end_line - The line where the issue ends. |
||
534 | - end_column - The column where the issue ends. |
||
535 | - severity - The severity of the issue. |
||
536 | - message - The message of the result. |
||
537 | - origin - The origin of the issue. |
||
538 | |||
539 | The groups ``line``, ``column``, ``end_line`` and |
||
540 | ``end_column`` don't have to match numbers only, they can |
||
541 | also match nothing, the generated ``Result`` is filled |
||
542 | automatically with ``None`` then for the appropriate |
||
543 | properties. |
||
544 | :param severity_map: |
||
545 | A dict used to map a severity string (captured from the |
||
546 | ``output_regex`` with the named group ``severity``) to an |
||
547 | actual ``coalib.results.RESULT_SEVERITY`` for a result. |
||
548 | :return: |
||
549 | An iterator returning results. |
||
550 | """ |
||
551 | if isinstance(output, str): |
||
552 | output = (output,) |
||
553 | |||
554 | for string in output: |
||
555 | for match in re.finditer(output_regex, string): |
||
556 | yield self._convert_output_regex_match_to_result( |
||
557 | match, filename, severity_map=severity_map) |
||
558 | |||
559 | if options["output_format"] is None: |
||
560 | # Check if user supplied a `process_output` override. |
||
561 | if not (hasattr(klass, "process_output") and |
||
562 | callable(klass.process_output)): |
||
563 | raise ValueError("`process_output` not provided by given " |
||
564 | "class.") |
||
565 | # No need to assign to `process_output` here, the class mixing |
||
566 | # below automatically does that. |
||
567 | else: |
||
568 | # Prevent people from accidentally defining `process_output` |
||
569 | # manually, as this would implicitly override the internally |
||
570 | # set-up `process_output`. |
||
571 | if hasattr(klass, "process_output"): |
||
572 | raise ValueError("`process_output` is used by given class," |
||
573 | " but " + repr(options["output_format"]) + |
||
574 | " output format was specified.") |
||
575 | |||
576 | if options["output_format"] == "corrected": |
||
577 | process_output_args = {} |
||
578 | if "diff_severity" in options: |
||
579 | process_output_args["diff_severity"] = ( |
||
580 | options["diff_severity"]) |
||
581 | if "diff_message" in options: |
||
582 | process_output_args["diff_message"] = ( |
||
583 | options["diff_message"]) |
||
584 | |||
585 | process_output = partialmethod( |
||
586 | process_output_corrected, **process_output_args) |
||
587 | |||
588 | elif options["output_format"] == "regex": |
||
589 | process_output_args = { |
||
590 | "output_regex": options["output_regex"]} |
||
591 | if "severity_map" in options: |
||
592 | process_output_args["severity_map"] = ( |
||
593 | options["severity_map"]) |
||
594 | |||
595 | process_output = partialmethod( |
||
596 | process_output_regex, **process_output_args) |
||
597 | |||
598 | else: # pragma: no cover |
||
599 | # This statement is never reached. |
||
600 | # Due to a bug in coverage we can't use `pass` here, as |
||
601 | # the ignore-pragma doesn't take up this else-clause then. |
||
602 | # https://bitbucket.org/ned/coveragepy/issues/483/partial- |
||
603 | # branch-coverage-pragma-no-cover |
||
604 | assert False |
||
605 | |||
606 | @classmethod |
||
607 | @contextmanager |
||
608 | def _create_config(cls, filename, file, **kwargs): |
||
609 | """ |
||
610 | Provides a context-manager that creates the config file if the |
||
611 | user provides one and cleans it up when done with linting. |
||
612 | |||
613 | :param filename: |
||
614 | The filename of the file. |
||
615 | :param file: |
||
616 | The file contents. |
||
617 | :param kwargs: |
||
618 | Section settings passed from ``run()``. |
||
619 | :return: |
||
620 | A context-manager handling the config-file. |
||
621 | """ |
||
622 | content = cls.generate_config(filename, file, **kwargs) |
||
623 | if content is None: |
||
624 | yield None |
||
625 | else: |
||
626 | tmp_suffix = options["config_suffix"] |
||
627 | with make_temp(suffix=tmp_suffix) as config_file: |
||
628 | with open(config_file, mode="w") as fl: |
||
629 | fl.write(content) |
||
630 | yield config_file |
||
631 | |||
632 | @staticmethod |
||
633 | def _filter_kwargs(metadata, kwargs): |
||
634 | """ |
||
635 | Filter out kwargs using the given metadata. Means only |
||
636 | parameters contained in the metadata specification are taken |
||
637 | from kwargs and returned. |
||
638 | |||
639 | :param metadata: |
||
640 | The signature specification. |
||
641 | :param kwargs: |
||
642 | The kwargs to filter. |
||
643 | :return: |
||
644 | The filtered kwargs. |
||
645 | """ |
||
646 | return {key: kwargs[key] |
||
647 | for key in metadata.non_optional_params.keys() | |
||
648 | metadata.optional_params.keys() |
||
649 | if key in kwargs} |
||
650 | |||
651 | def run(self, filename, file, **kwargs): |
||
652 | # Get the **kwargs params to forward to `generate_config()` |
||
653 | # (from `_create_config()`). |
||
654 | generate_config_kwargs = self._filter_kwargs( |
||
655 | self._get_generate_config_metadata(), kwargs) |
||
656 | |||
657 | with self._create_config( |
||
658 | filename, |
||
659 | file, |
||
660 | **generate_config_kwargs) as config_file: |
||
661 | |||
662 | # And now retrieve the **kwargs for `create_arguments()`. |
||
663 | create_arguments_kwargs = self._filter_kwargs( |
||
664 | self._get_create_arguments_metadata(), kwargs) |
||
665 | |||
666 | output = self._execute_command( |
||
667 | self.create_arguments(filename, |
||
668 | file, |
||
669 | config_file, |
||
670 | **create_arguments_kwargs), |
||
671 | stdin="".join(file) if options["use_stdin"] else None) |
||
672 | output = tuple(compress( |
||
673 | output, |
||
674 | (options["use_stdout"], options["use_stderr"]))) |
||
675 | if len(output) == 1: |
||
676 | output = output[0] |
||
677 | |||
678 | process_output_kwargs = self._filter_kwargs( |
||
679 | self._get_process_output_metadata(), kwargs) |
||
680 | return self.process_output(output, filename, file, |
||
681 | **process_output_kwargs) |
||
682 | |||
689 |