Skip to content

Commit

Permalink
refactor: can_fix to fixable, fix to autofix
Browse files Browse the repository at this point in the history
  • Loading branch information
andreoliwa committed Dec 29, 2021
1 parent 739838e commit a2d1f66
Show file tree
Hide file tree
Showing 8 changed files with 53 additions and 53 deletions.
10 changes: 5 additions & 5 deletions docs/generate_rst.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ class FileType:
text: str
url: str
check: Union[bool, int]
fix: Union[bool, int]
autofix: Union[bool, int]

def __post_init__(self):
"""Warn about text that might render incorrectly."""
Expand Down Expand Up @@ -136,14 +136,14 @@ def check_str(self) -> str:
return self._pretty("check")

@property
def fix_str(self) -> str:
"""The fix flag, as a string."""
return self._pretty("fix")
def autofix_str(self) -> str:
"""The autofix flag, as a string."""
return self._pretty("autofix")

@property
def row(self) -> Tuple[str, str, str]:
"""Tuple for a table row."""
return self.text_with_url, self.check_str, self.fix_str
return self.text_with_url, self.check_str, self.autofix_str


IMPLEMENTED_FILE_TYPES: Set[FileType] = {
Expand Down
4 changes: 2 additions & 2 deletions src/nitpick/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def get_nitpick(context: click.Context) -> Nitpick:


def common_fix_or_check(context, verbose: int, files, check_only: bool) -> None:
"""Common CLI code for both fix and check commands."""
"""Common CLI code for both "fix" and "check" commands."""
if verbose:
level = logging.INFO if verbose == 1 else logging.DEBUG

Expand All @@ -77,7 +77,7 @@ def common_fix_or_check(context, verbose: int, files, check_only: bool) -> None:

nit = get_nitpick(context)
try:
for fuss in nit.run(*files, fix=not check_only):
for fuss in nit.run(*files, autofix=not check_only):
nit.echo(fuss.pretty)
except QuitComplainingError as err:
for fuss in err.violations:
Expand Down
12 changes: 6 additions & 6 deletions src/nitpick/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,11 @@ def init(self, project_root: PathOrStr = None, offline: bool = None) -> "Nitpick

return self

def run(self, *partial_names: str, fix=False) -> Iterator[Fuss]:
def run(self, *partial_names: str, autofix=False) -> Iterator[Fuss]:
"""Run Nitpick.
:param partial_names: Names of the files to enforce configs for.
:param fix: Flag to modify files, if the plugin supports it (default: True).
:param autofix: Flag to modify files, if the plugin supports it (default: True).
:return: Fuss generator.
"""
Reporter.reset()
Expand All @@ -63,7 +63,7 @@ def run(self, *partial_names: str, fix=False) -> Iterator[Fuss]:
yield from chain(
self.project.merge_styles(self.offline),
self.enforce_present_absent(*partial_names),
self.enforce_style(*partial_names, fix=fix),
self.enforce_style(*partial_names, autofix=autofix),
)
except QuitComplainingError as err:
yield from err.violations
Expand Down Expand Up @@ -95,14 +95,14 @@ def enforce_present_absent(self, *partial_names: str) -> Iterator[Fuss]:
violation = ProjectViolations.MISSING_FILE if present else ProjectViolations.FILE_SHOULD_BE_DELETED
yield reporter.make_fuss(violation, extra=extra)

def enforce_style(self, *partial_names: str, fix=True) -> Iterator[Fuss]:
def enforce_style(self, *partial_names: str, autofix=True) -> Iterator[Fuss]:
"""Read the merged style and enforce the rules in it.
1. Get all root keys from the merged style (every key is a filename, except "nitpick").
2. For each file name, find the plugin(s) that can handle the file.
:param partial_names: Names of the files to enforce configs for.
:param fix: Flag to modify files, if the plugin supports it (default: True).
:param autofix: Flag to modify files, if the plugin supports it (default: True).
:return: Fuss generator.
"""

Expand All @@ -115,7 +115,7 @@ def enforce_style(self, *partial_names: str, fix=True) -> Iterator[Fuss]:
info = FileInfo.create(self.project, config_key)
# pylint: disable=no-member
for plugin_class in self.project.plugin_manager.hook.can_handle(info=info): # type: Type[NitpickPlugin]
yield from plugin_class(info, config_dict, fix).entry_point()
yield from plugin_class(info, config_dict, autofix).entry_point()

def configured_files(self, *partial_names: str) -> List[Path]:
"""List of files configured in the Nitpick style. Filter only the selected partial names."""
Expand Down
16 changes: 8 additions & 8 deletions src/nitpick/plugins/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,16 @@ class NitpickPlugin(metaclass=abc.ABCMeta):
:param data: File information (project, path, tags).
:param expected_config: Expected configuration for the file
:param fix: Flag to modify files, if the plugin supports it (default: True).
:param autofix: Flag to modify files, if the plugin supports it (default: True).
"""

__str__, __unicode__ = autotext("{self.info.path_from_root} ({self.__class__.__name__})")

filename = "" # TODO: remove filename attribute after fixing dynamic/fixed schema loading
violation_base_code: int = 0

#: Can this plugin modify files directly?
can_fix: bool = False
#: Can this plugin modify its files directly? Are the files fixable?
fixable: bool = False

#: Nested validation field for this file, to be applied in runtime when the validation schema is rebuilt.
#: Useful when you have a strict configuration for a file type (e.g. :py:class:`nitpick.plugins.json.JSONPlugin`).
Expand All @@ -41,7 +41,7 @@ class NitpickPlugin(metaclass=abc.ABCMeta):

skip_empty_suggestion = False

def __init__(self, info: FileInfo, expected_config: JsonDict, fix=False) -> None:
def __init__(self, info: FileInfo, expected_config: JsonDict, autofix=False) -> None:
self.info = info
self.filename = info.path_from_root
self.reporter = Reporter(info, self.violation_base_code)
Expand All @@ -51,7 +51,7 @@ def __init__(self, info: FileInfo, expected_config: JsonDict, fix=False) -> None
# Configuration for this file as a TOML dict, taken from the style file.
self.expected_config: JsonDict = expected_config or {}

self.fix = self.can_fix and fix
self.autofix = self.fixable and autofix
# Dirty flag to avoid changing files without need
self.dirty: bool = False

Expand Down Expand Up @@ -91,7 +91,7 @@ def _enforce_file_configuration(self):
else:
yield from self._suggest_when_file_not_found()

if self.fix and self.dirty:
if self.autofix and self.dirty:
fuss = self.write_file(file_exists) # pylint: disable=assignment-from-none
if fuss:
yield fuss
Expand All @@ -110,12 +110,12 @@ def _suggest_when_file_not_found(self):
logger.info(f"{self}: Suggest initial contents for {self.filename}")

if suggestion:
yield self.reporter.make_fuss(SharedViolations.CREATE_FILE_WITH_SUGGESTION, suggestion, fixed=self.fix)
yield self.reporter.make_fuss(SharedViolations.CREATE_FILE_WITH_SUGGESTION, suggestion, fixed=self.autofix)
else:
yield self.reporter.make_fuss(SharedViolations.CREATE_FILE)

def write_file(self, file_exists: bool) -> Optional[Fuss]: # pylint: disable=unused-argument,no-self-use
"""Hook to write the new file when fix mode is on. Should be used by inherited classes."""
"""Hook to write the new file when autofix mode is on. Should be used by inherited classes."""
return None

@abc.abstractmethod
Expand Down
24 changes: 12 additions & 12 deletions src/nitpick/plugins/ini.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ class IniPlugin(NitpickPlugin):
Style examples enforcing values on INI files: :ref:`flake8 configuration <example-flake8>`.
"""

can_fix = True
fixable = True
identify_tags = {"ini", "editorconfig"}
violation_base_code = 320

Expand Down Expand Up @@ -122,7 +122,7 @@ def get_missing_output(self) -> str:
parser = ConfigParser()
for section in sorted(missing, key=lambda s: "0" if s == TOP_SECTION else f"1{s}"):
expected_config: Dict = self.expected_config[section]
if self.fix:
if self.autofix:
if self.updater.last_block:
self.updater.last_block.add_after.space(1)
self.updater.add_section(section)
Expand Down Expand Up @@ -173,15 +173,15 @@ def _read_file(self) -> Iterator[Fuss]:
return

# Don't change the file if there was a parsing error
self.fix = False
self.autofix = False
yield self.reporter.make_fuss(Violations.PARSING_ERROR, cls=parsing_err.__class__.__name__, msg=parsing_err)
raise Error

def enforce_missing_sections(self) -> Iterator[Fuss]:
"""Enforce missing sections."""
missing = self.get_missing_output()
if missing:
yield self.reporter.make_fuss(Violations.MISSING_SECTIONS, missing, self.fix)
yield self.reporter.make_fuss(Violations.MISSING_SECTIONS, missing, self.autofix)

def enforce_section(self, section: str) -> Iterator[Fuss]:
"""Enforce rules for a section."""
Expand All @@ -207,7 +207,7 @@ def enforce_comma_separated_values(self, section, key, raw_actual: Any, raw_expe

joined_values = ",".join(sorted(missing))
value_to_append = f",{joined_values}"
if self.fix:
if self.autofix:
self.updater[section][key].value += value_to_append
self.dirty = True
section_header = "" if section == TOP_SECTION else f"[{section}]\n"
Expand All @@ -216,7 +216,7 @@ def enforce_comma_separated_values(self, section, key, raw_actual: Any, raw_expe
Violations.MISSING_VALUES_IN_LIST,
f"{section_header}{key} = (...){value_to_append}",
key=key,
fixed=self.fix,
fixed=self.autofix,
)

def compare_different_keys(self, section, key, raw_actual: Any, raw_expected: Any) -> Iterator[Fuss]:
Expand All @@ -231,7 +231,7 @@ def compare_different_keys(self, section, key, raw_actual: Any, raw_expected: An
if actual == expected:
return

if self.fix:
if self.autofix:
self.updater[section][key].value = expected
self.dirty = True
if section == TOP_SECTION:
Expand All @@ -240,7 +240,7 @@ def compare_different_keys(self, section, key, raw_actual: Any, raw_expected: An
f"{key} = {raw_expected}",
key=key,
actual=raw_actual,
fixed=self.fix,
fixed=self.autofix,
)
else:
yield self.reporter.make_fuss(
Expand All @@ -249,7 +249,7 @@ def compare_different_keys(self, section, key, raw_actual: Any, raw_expected: An
section=section,
key=key,
actual=raw_actual,
fixed=self.fix,
fixed=self.autofix,
)

def show_missing_keys(self, section: str, values: List[Tuple[str, Any]]) -> Iterator[Fuss]:
Expand All @@ -262,14 +262,14 @@ def show_missing_keys(self, section: str, values: List[Tuple[str, Any]]) -> Iter

if section == TOP_SECTION:
yield self.reporter.make_fuss(
Violations.TOP_SECTION_MISSING_OPTION, self.contents_without_top_section(output), self.fix
Violations.TOP_SECTION_MISSING_OPTION, self.contents_without_top_section(output), self.autofix
)
else:
yield self.reporter.make_fuss(Violations.MISSING_OPTION, output, self.fix, section=section)
yield self.reporter.make_fuss(Violations.MISSING_OPTION, output, self.autofix, section=section)

def add_options_before_space(self, section: str, options: OrderedDict) -> None:
"""Add new options before a blank line in the end of the section."""
if not self.fix:
if not self.autofix:
return

space_removed = False
Expand Down
10 changes: 5 additions & 5 deletions src/nitpick/plugins/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,12 @@ class JSONPlugin(NitpickPlugin):
validation_schema = JSONFileSchema
identify_tags = {"json"}
violation_base_code = 340
can_fix = True
fixable = True

def enforce_rules(self) -> Iterator[Fuss]:
"""Enforce rules for missing keys and JSON content."""
actual = JSONFormat(path=self.file_path)
final_dict: Optional[JsonDict] = flatten(actual.as_object) if self.fix else None
final_dict: Optional[JsonDict] = flatten(actual.as_object) if self.autofix else None

comparison = actual.compare_with_flatten(self.expected_dict_from_contains_keys())
if comparison.missing:
Expand All @@ -55,7 +55,7 @@ def enforce_rules(self) -> Iterator[Fuss]:
self.report(SharedViolations.MISSING_VALUES, final_dict, comparison.missing),
)

if self.fix and self.dirty and final_dict:
if self.autofix and self.dirty and final_dict:
self.file_path.write_text(JSONFormat(obj=unflatten(final_dict)).reformatted)

def expected_dict_from_contains_keys(self):
Expand Down Expand Up @@ -83,15 +83,15 @@ def report(self, violation: ViolationEnum, final_dict: Optional[JsonDict], chang
if final_dict:
final_dict.update(flatten(change.as_object))
self.dirty = True
yield self.reporter.make_fuss(violation, change.reformatted, prefix="", fixed=self.fix)
yield self.reporter.make_fuss(violation, change.reformatted, prefix="", fixed=self.autofix)

@property
def initial_contents(self) -> str:
"""Suggest the initial content for this missing file."""
suggestion = DictBlender(self.expected_dict_from_contains_keys())
suggestion.add(self.expected_dict_from_contains_json())
json_as_string = JSONFormat(obj=suggestion.mix()).reformatted if suggestion else ""
if self.fix:
if self.autofix:
self.file_path.write_text(json_as_string)
return json_as_string

Expand Down
10 changes: 5 additions & 5 deletions src/nitpick/plugins/toml.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ class TomlPlugin(NitpickPlugin):

identify_tags = {"toml"}
violation_base_code = 310
can_fix = True
fixable = True

def enforce_rules(self) -> Iterator[Fuss]:
"""Enforce rules for missing key/value pairs in the TOML file."""
Expand All @@ -48,12 +48,12 @@ def enforce_rules(self) -> Iterator[Fuss]:
if not comparison.has_changes:
return

document = parse(toml_format.as_string) if self.fix else None
document = parse(toml_format.as_string) if self.autofix else None
yield from chain(
self.report(SharedViolations.DIFFERENT_VALUES, document, comparison.diff),
self.report(SharedViolations.MISSING_VALUES, document, comparison.missing),
)
if self.fix and self.dirty:
if self.autofix and self.dirty:
self.file_path.write_text(dumps(document))

def report(self, violation: ViolationEnum, document: Optional[TOMLDocument], change: Optional[BaseFormat]):
Expand All @@ -63,13 +63,13 @@ def report(self, violation: ViolationEnum, document: Optional[TOMLDocument], cha
if document:
change_toml(document, change.as_object)
self.dirty = True
yield self.reporter.make_fuss(violation, change.reformatted.strip(), prefix="", fixed=self.fix)
yield self.reporter.make_fuss(violation, change.reformatted.strip(), prefix="", fixed=self.autofix)

@property
def initial_contents(self) -> str:
"""Suggest the initial content for this missing file."""
toml_as_string = TOMLFormat(obj=self.expected_config).reformatted
if self.fix:
if self.autofix:
self.file_path.write_text(toml_as_string)
return toml_as_string

Expand Down
Loading

0 comments on commit a2d1f66

Please sign in to comment.