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