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