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