Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

--write: Allow Transforms to mark MatchErrors as fixed #2041

Merged
merged 7 commits into from
Mar 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
63 changes: 50 additions & 13 deletions src/ansiblelint/app.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Application."""
import logging
import os
from dataclasses import dataclass
from functools import lru_cache
from typing import TYPE_CHECKING, Any, List, Tuple, Type

Expand All @@ -25,6 +26,21 @@
_logger = logging.getLogger(__package__)


@dataclass
class SummarizedResults:
"""The statistics about an ansible-lint run."""

failures: int = 0
warnings: int = 0
fixed_failures: int = 0
fixed_warnings: int = 0

@property
def fixed(self) -> int:
"""Get total fixed count."""
return self.fixed_failures + self.fixed_warnings


class App:
"""App class represents an execution of the linter."""

Expand All @@ -41,7 +57,9 @@ def __init__(self, options: "Namespace"):
self.runtime = Runtime(isolated=True)

def render_matches(self, matches: List[MatchError]) -> None:
"""Display given matches."""
"""Display given matches (if they are not fixed)."""
matches = [match for match in matches if not match.fixed]

if isinstance(self.formatter, formatters.CodeclimateJSONFormatter):
# If formatter CodeclimateJSONFormatter is chosen,
# then print only the matches in JSON
Expand Down Expand Up @@ -76,16 +94,24 @@ def render_matches(self, matches: List[MatchError]) -> None:
for match in matches:
console.print(formatter.format(match), markup=False, highlight=False)

def count_results(self, matches: List[MatchError]) -> Tuple[int, int]:
def count_results(self, matches: List[MatchError]) -> SummarizedResults:
"""Count failures and warnings in matches."""
failures = 0
warnings = 0
fixed_failures = 0
fixed_warnings = 0
for match in matches:
if {match.rule.id, *match.rule.tags}.isdisjoint(self.options.warn_list):
failures += 1
if match.fixed:
fixed_failures += 1
else:
failures += 1
else:
warnings += 1
return failures, warnings
if match.fixed:
fixed_warnings += 1
else:
warnings += 1
return SummarizedResults(failures, warnings, fixed_failures, fixed_warnings)

@staticmethod
def count_lintables(files: "Set[Lintable]") -> Tuple[int, int]:
Expand Down Expand Up @@ -116,7 +142,7 @@ def report_outcome(
"""
msg = ""

failures, warnings = self.count_results(result.matches)
summary = self.count_results(result.matches)
files_count, changed_files_count = self.count_lintables(result.files)

matched_rules = self._get_matched_skippable_rules(result.matches)
Expand Down Expand Up @@ -163,17 +189,28 @@ def report_outcome(

if (result.matches or changed_files_count) and not self.options.quiet:
console_stderr.print(render_yaml(msg))
if changed_files_count:
console_stderr.print(f"Modified {changed_files_count} files.")
console_stderr.print(
f"Finished with {failures} failure(s), {warnings} warning(s) "
f"on {files_count} files."
)
self.report_summary(summary, changed_files_count, files_count)

if mark_as_success or not failures:
if mark_as_success or not summary.failures:
return SUCCESS_RC
return VIOLATIONS_FOUND_RC

@staticmethod
def report_summary(
summary: SummarizedResults, changed_files_count: int, files_count: int
) -> None:
"""Report match and file counts."""
if changed_files_count:
console_stderr.print(f"Modified {changed_files_count} files.")

msg = "Finished with "
msg += f"{summary.failures} failure(s), {summary.warnings} warning(s)"
if summary.fixed:
msg += f", and fixed {summary.fixed} issue(s)"
msg += f" on {files_count} files."

console_stderr.print(msg)


def choose_formatter_factory(
options_list: "Namespace",
Expand Down
2 changes: 2 additions & 0 deletions src/ansiblelint/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ def __init__(
self.task: Optional[Dict[str, Any]] = None
# path to the problem area, like: [0,"pre_tasks",3] for [0].pre_tasks[3]
self.yaml_path: List[Union[int, str]] = []
# True when a transform has resolved this MatchError
self.fixed = False

def __repr__(self) -> str:
"""Return a MatchError instance representation."""
Expand Down
3 changes: 3 additions & 0 deletions src/ansiblelint/rules/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,9 @@ def transform(
When ``transform()`` is called on a rule, the rule should either fix the
issue, if possible, or make modifications that make it easier to fix manually.

The transform must set ``match.fixed = True`` when data has been transformed to
fix the error.

For YAML files, ``data`` is an editable YAML dict/array that preserves
any comments that were in the original file.

Expand Down