| Conditions | 1 |
| Total Lines | 404 |
| Lines | 0 |
| Ratio | 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 |
||
| 284 | def create_linter(klass): |
||
| 285 | class LinterMeta(type): |
||
| 286 | |||
| 287 | def __repr__(cls): |
||
| 288 | return "<{} class (wrapping {}) at {}>".format( |
||
| 289 | cls.__name__, |
||
| 290 | repr(options["executable"]), |
||
| 291 | hex(id(cls))) |
||
| 292 | |||
| 293 | class LinterBase(LocalBear, metaclass=LinterMeta): |
||
|
|
|||
| 294 | |||
| 295 | @staticmethod |
||
| 296 | def generate_config(filename, file): |
||
| 297 | """ |
||
| 298 | Generates the content of a config-file the linter-tool might |
||
| 299 | need. |
||
| 300 | |||
| 301 | The contents generated from this function are written to a |
||
| 302 | temporary file and the path is provided inside |
||
| 303 | ``create_arguments()``. |
||
| 304 | |||
| 305 | By default no configuration is generated. |
||
| 306 | |||
| 307 | You can provide additional keyword arguments and defaults. |
||
| 308 | These will be interpreted as required settings that need to be |
||
| 309 | provided through a coafile-section. |
||
| 310 | |||
| 311 | :param filename: |
||
| 312 | The name of the file currently processed. |
||
| 313 | :param file: |
||
| 314 | The contents of the file currently processed. |
||
| 315 | :return: |
||
| 316 | The config-file-contents as a string or ``None``. |
||
| 317 | """ |
||
| 318 | return None |
||
| 319 | |||
| 320 | @staticmethod |
||
| 321 | def create_arguments(filename, file, config_file): |
||
| 322 | """ |
||
| 323 | Creates the arguments for the linter. |
||
| 324 | |||
| 325 | You can provide additional keyword arguments and defaults. |
||
| 326 | These will be interpreted as required settings that need to be |
||
| 327 | provided through a coafile-section. |
||
| 328 | |||
| 329 | :param filename: |
||
| 330 | The name of the file the linter-tool shall process. |
||
| 331 | :param file: |
||
| 332 | The contents of the file. |
||
| 333 | :param config_file: |
||
| 334 | The path of the config-file if used. ``None`` if unused. |
||
| 335 | :return: |
||
| 336 | A sequence of arguments to feed the linter-tool with. |
||
| 337 | """ |
||
| 338 | raise NotImplementedError |
||
| 339 | |||
| 340 | @staticmethod |
||
| 341 | def get_executable(): |
||
| 342 | """ |
||
| 343 | Returns the executable of this class. |
||
| 344 | |||
| 345 | :return: |
||
| 346 | The executable name. |
||
| 347 | """ |
||
| 348 | return options["executable"] |
||
| 349 | |||
| 350 | @classmethod |
||
| 351 | def check_prerequisites(cls): |
||
| 352 | """ |
||
| 353 | Checks whether the linter-tool the bear uses is operational. |
||
| 354 | |||
| 355 | :return: |
||
| 356 | True if available, otherwise a string containing more info. |
||
| 357 | """ |
||
| 358 | if shutil.which(cls.get_executable()) is None: |
||
| 359 | return repr(cls.get_executable()) + " is not installed." |
||
| 360 | else: |
||
| 361 | if options["prerequisite_check_command"]: |
||
| 362 | try: |
||
| 363 | check_call(options["prerequisite_check_command"], |
||
| 364 | stdout=DEVNULL, |
||
| 365 | stderr=DEVNULL) |
||
| 366 | return True |
||
| 367 | except (OSError, CalledProcessError): |
||
| 368 | return options["prerequisite_check_fail_message"] |
||
| 369 | return True |
||
| 370 | |||
| 371 | @classmethod |
||
| 372 | def _get_create_arguments_metadata(cls): |
||
| 373 | return FunctionMetadata.from_function( |
||
| 374 | cls.create_arguments, |
||
| 375 | omit={"filename", "file", "config_file"}) |
||
| 376 | |||
| 377 | @classmethod |
||
| 378 | def _get_generate_config_metadata(cls): |
||
| 379 | return FunctionMetadata.from_function( |
||
| 380 | cls.generate_config, |
||
| 381 | omit={"filename", "file"}) |
||
| 382 | |||
| 383 | @classmethod |
||
| 384 | def _get_process_output_metadata(cls): |
||
| 385 | return FunctionMetadata.from_function( |
||
| 386 | cls.process_output, |
||
| 387 | omit={"self", "output", "filename", "file"}) |
||
| 388 | |||
| 389 | @classmethod |
||
| 390 | def get_non_optional_settings(cls): |
||
| 391 | return cls.get_metadata().non_optional_params |
||
| 392 | |||
| 393 | @classmethod |
||
| 394 | def get_metadata(cls): |
||
| 395 | merged_metadata = FunctionMetadata.merge( |
||
| 396 | cls._get_process_output_metadata(), |
||
| 397 | cls._get_generate_config_metadata(), |
||
| 398 | cls._get_create_arguments_metadata()) |
||
| 399 | merged_metadata.desc = inspect.getdoc(cls) |
||
| 400 | return merged_metadata |
||
| 401 | |||
| 402 | @classmethod |
||
| 403 | def _execute_command(cls, args, stdin=None): |
||
| 404 | """ |
||
| 405 | Executes the underlying tool with the given arguments. |
||
| 406 | |||
| 407 | :param args: |
||
| 408 | The argument sequence to pass to the executable. |
||
| 409 | :param stdin: |
||
| 410 | Input to send to the opened process as stdin. |
||
| 411 | :return: |
||
| 412 | A tuple with ``(stdout, stderr)``. |
||
| 413 | """ |
||
| 414 | return run_shell_command( |
||
| 415 | (cls.get_executable(),) + tuple(args), |
||
| 416 | stdin=stdin) |
||
| 417 | |||
| 418 | def _convert_output_regex_match_to_result(self, |
||
| 419 | match, |
||
| 420 | filename, |
||
| 421 | severity_map): |
||
| 422 | """ |
||
| 423 | Converts the matched named-groups of ``output_regex`` to an |
||
| 424 | actual ``Result``. |
||
| 425 | |||
| 426 | :param match: |
||
| 427 | The regex match object. |
||
| 428 | :param filename: |
||
| 429 | The name of the file this match belongs to. |
||
| 430 | :param severity_map: |
||
| 431 | The dict to use to map the severity-match to an actual |
||
| 432 | ``RESULT_SEVERITY``. |
||
| 433 | """ |
||
| 434 | # Pre process the groups |
||
| 435 | groups = match.groupdict() |
||
| 436 | |||
| 437 | try: |
||
| 438 | groups["severity"] = severity_map[ |
||
| 439 | groups["severity"].lower()] |
||
| 440 | except KeyError: |
||
| 441 | self.warn( |
||
| 442 | "No correspondence for " + repr(groups["severity"]) + |
||
| 443 | " found in given severity map. Assuming " |
||
| 444 | "`RESULT_SEVERITY.NORMAL`.") |
||
| 445 | groups["severity"] = RESULT_SEVERITY.NORMAL |
||
| 446 | |||
| 447 | for variable in ("line", "column", "end_line", "end_column"): |
||
| 448 | groups[variable] = (None |
||
| 449 | if groups.get(variable, "") == "" else |
||
| 450 | int(groups[variable])) |
||
| 451 | |||
| 452 | if "origin" in groups: |
||
| 453 | groups["origin"] = "{} ({})".format( |
||
| 454 | str(klass.__name__), |
||
| 455 | str(groups["origin"])) |
||
| 456 | |||
| 457 | # Construct the result. |
||
| 458 | return Result.from_values( |
||
| 459 | origin=groups.get("origin", self), |
||
| 460 | message=groups.get("message", ""), |
||
| 461 | file=filename, |
||
| 462 | severity=int(groups.get("severity", |
||
| 463 | RESULT_SEVERITY.NORMAL)), |
||
| 464 | line=groups["line"], |
||
| 465 | column=groups["column"], |
||
| 466 | end_line=groups["end_line"], |
||
| 467 | end_column=groups["end_column"]) |
||
| 468 | |||
| 469 | def process_output_corrected(self, |
||
| 470 | output, |
||
| 471 | filename, |
||
| 472 | file, |
||
| 473 | diff_severity=RESULT_SEVERITY.NORMAL, |
||
| 474 | diff_message="Inconsistency found."): |
||
| 475 | """ |
||
| 476 | Processes the executable's output as a corrected file. |
||
| 477 | |||
| 478 | :param output: |
||
| 479 | The output of the program. This can be either a single |
||
| 480 | string or a sequence of strings. |
||
| 481 | :param filename: |
||
| 482 | The filename of the file currently being corrected. |
||
| 483 | :param file: |
||
| 484 | The contents of the file currently being corrected. |
||
| 485 | :param diff_severity: |
||
| 486 | The severity to use for generating results. |
||
| 487 | :param diff_message: |
||
| 488 | The message to use for generating results. |
||
| 489 | :return: |
||
| 490 | An iterator returning results containing patches for the |
||
| 491 | file to correct. |
||
| 492 | """ |
||
| 493 | if isinstance(output, str): |
||
| 494 | output = (output,) |
||
| 495 | |||
| 496 | for string in output: |
||
| 497 | for diff in Diff.from_string_arrays( |
||
| 498 | file, |
||
| 499 | string.splitlines(keepends=True)).split_diff(): |
||
| 500 | yield Result(self, |
||
| 501 | diff_message, |
||
| 502 | affected_code=(diff.range(filename),), |
||
| 503 | diffs={filename: diff}, |
||
| 504 | severity=diff_severity) |
||
| 505 | |||
| 506 | def process_output_regex( |
||
| 507 | self, |
||
| 508 | output, |
||
| 509 | filename, |
||
| 510 | file, |
||
| 511 | output_regex, |
||
| 512 | severity_map=MappingProxyType({ |
||
| 513 | "error": RESULT_SEVERITY.MAJOR, |
||
| 514 | "warning": RESULT_SEVERITY.NORMAL, |
||
| 515 | "warn": RESULT_SEVERITY.NORMAL, |
||
| 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(compress( |
||
| 674 | output, |
||
| 675 | (options["use_stdout"], options["use_stderr"]))) |
||
| 676 | if len(output) == 1: |
||
| 677 | output = output[0] |
||
| 678 | |||
| 679 | process_output_kwargs = self._filter_kwargs( |
||
| 680 | self._get_process_output_metadata(), kwargs) |
||
| 681 | return self.process_output(output, filename, file, |
||
| 682 | **process_output_kwargs) |
||
| 683 | |||
| 684 | # Mixin the linter into the user-defined interface, otherwise |
||
| 685 | # `create_arguments` and other methods would be overridden by the |
||
| 686 | # default version. |
||
| 687 | return type(klass.__name__, (klass, LinterBase), {}) |
||
| 688 | |||
| 690 |