Skip to content

Commit

Permalink
refactor: fix complexity and too-many-locals after writing tests
Browse files Browse the repository at this point in the history
  • Loading branch information
andreoliwa committed Nov 19, 2023
1 parent e3b81f3 commit 6a78e27
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 41 deletions.
45 changes: 10 additions & 35 deletions src/nitpick/cli.py
Expand Up @@ -22,13 +22,11 @@
import tomlkit
from click.exceptions import Exit
from loguru import logger
from tomlkit import items

from nitpick import tomlkit_ext
from nitpick.constants import (
CONFIG_KEY_DONT_SUGGEST,
CONFIG_KEY_STYLE,
CONFIG_KEY_TOOL,
CONFIG_TOOL_NITPICK_KEY,
PROJECT_NAME,
EmojiEnum,
Expand Down Expand Up @@ -168,8 +166,7 @@ def ls(context, files): # pylint: disable=invalid-name
help="Suggest styles based on the files in the project root (skipping Git ignored files)",
)
@click.argument("style_urls", nargs=-1)
# TODO(AA): refactor: fix complexity and too-many-locals after writing tests
def init( # noqa: C901 # pylint: disable=too-many-locals
def init(
context,
fix: bool, # pylint: disable=redefined-outer-name
suggest: bool,
Expand All @@ -186,47 +183,25 @@ def init( # noqa: C901 # pylint: disable=too-many-locals
return

nit = get_nitpick(context)
path = nit.project.config_file_or_default()
doc = tomlkit_ext.load(path)
tool_nitpick_table: tomlkit_ext.Table | None = doc.get(CONFIG_TOOL_NITPICK_KEY)
config = nit.project.read_tool_nitpick_config(suggest)

# Convert tuple to list, so we can add styles to it
style_urls = list(style_urls)

if suggest:
style_urls.extend(nit.project.suggest_styles())

if not tool_nitpick_table:
super_table = tomlkit.table(True)
nitpick_table = tomlkit.table()
nitpick_table.update({CONFIG_KEY_STYLE: []})
super_table.append(PROJECT_NAME, nitpick_table)
doc.append(CONFIG_KEY_TOOL, super_table)
tool_nitpick_table = doc.get(CONFIG_TOOL_NITPICK_KEY)

suggested_styles: items.Array = tool_nitpick_table.get(CONFIG_KEY_STYLE)
if suggested_styles is None:
suggested_styles = tomlkit.array()
tool_nitpick_table.add(CONFIG_KEY_STYLE, suggested_styles)

ignored_styles: items.Array = tool_nitpick_table.get(CONFIG_KEY_DONT_SUGGEST)
if ignored_styles is None:
ignored_styles = tomlkit.array()
if suggest:
# Create the ignored styles array only when suggesting styles
tool_nitpick_table.add(CONFIG_KEY_DONT_SUGGEST, ignored_styles)

new_styles = []
for style_url in style_urls:
if style_url in suggested_styles or style_url in ignored_styles:
if style_url in config.styles or style_url in config.dont_suggest:
continue
new_styles.append(style_url)
suggested_styles.add_line(style_url, indent=" ")
config.styles.add_line(style_url, indent=" ")

if suggest:
from nitpick import __version__ # pylint: disable=import-outside-toplevel

tomlkit_ext.update_comment_before(
tool_nitpick_table,
config.table,
CONFIG_KEY_STYLE,
PROJECT_NAME,
f"""
Expand All @@ -238,7 +213,7 @@ def init( # noqa: C901 # pylint: disable=too-many-locals

if not new_styles:
click.echo(
f"All done! {EmojiEnum.STAR_CAKE.value} [{CONFIG_TOOL_NITPICK_KEY}] table left unchanged in {path.name!r}"
f"All done! {EmojiEnum.STAR_CAKE.value} [{CONFIG_TOOL_NITPICK_KEY}] table left unchanged in {config.file.name!r}"
)
return
click.echo("New styles:")
Expand All @@ -249,14 +224,14 @@ def init( # noqa: C901 # pylint: disable=too-many-locals
if not fix:
click.secho(
f"Use --fix to append {message} to the [{CONFIG_TOOL_NITPICK_KEY}]"
f" table in the config file {path.name!r}.",
f" table in the config file {config.file.name!r}.",
fg="yellow",
)
return

path.write_text(tomlkit.dumps(doc), encoding="UTF-8")
config.file.write_text(tomlkit.dumps(config.doc), encoding="UTF-8")
click.echo(
f"The [{CONFIG_TOOL_NITPICK_KEY}] table was updated in {path.name!r}:"
f"The [{CONFIG_TOOL_NITPICK_KEY}] table was updated in {config.file.name!r}:"
f" {message} appended. {EmojiEnum.STAR_CAKE.value}"
)
raise Exit(1) # Needed when executed as a pre-commit hook
49 changes: 46 additions & 3 deletions src/nitpick/core.py
Expand Up @@ -10,19 +10,24 @@
from typing import TYPE_CHECKING, Iterator

import click
import tomlkit
from autorepr import autorepr
from identify import identify
from loguru import logger
from marshmallow_polyfield import PolyField
from more_itertools import always_iterable
from packaging.version import parse as parse_version
from pluggy import PluginManager
from tomlkit import items

from nitpick import PROJECT_NAME, fields, plugins
from nitpick import PROJECT_NAME, fields, plugins, tomlkit_ext
from nitpick.blender import TomlDoc, search_json
from nitpick.constants import (
ANY_BUILTIN_STYLE,
CONFIG_FILES,
CONFIG_KEY_DONT_SUGGEST,
CONFIG_KEY_STYLE,
CONFIG_KEY_TOOL,
CONFIG_TOOL_NITPICK_KEY,
DOT_NITPICK_TOML,
JMEX_NITPICK_MINIMUM_VERSION,
Expand Down Expand Up @@ -210,14 +215,25 @@ class ToolNitpickSectionSchema(BaseNitpickSchema):


@dataclass
class Configuration:
class Configuration: # TODO(AA): refactor: merge with ToolNitpickConfig
"""Configuration read from one of the ``CONFIG_FILES``."""

file: Path | None
styles: str | list[str]
cache: str


@dataclass
class ToolNitpickConfig:
"""Configuration read from the ``[tool.nitpick]`` section of the config file."""

file: Path
doc: tomlkit.TOMLDocument
table: items.Table
styles: items.Array
dont_suggest: items.Array


class Project:
"""A project to be nitpicked."""

Expand Down Expand Up @@ -279,7 +295,7 @@ def config_file(self) -> Path | None:

return found

def read_configuration(self) -> Configuration:
def read_configuration(self) -> Configuration: # TODO(AA): refactor: merge with read_tool_nitpick_config()
"""Search for a configuration file and validate it against a Marshmallow schema."""
config_file = self.config_file()
if not config_file:
Expand All @@ -299,6 +315,33 @@ def read_configuration(self) -> Configuration:
)
)

def read_tool_nitpick_config(self, suggest: bool) -> ToolNitpickConfig:
"""Return the ``[tool.nitpick]`` section from the configuration file."""
config_file = self.config_file_or_default()
doc = tomlkit_ext.load(config_file)
table: items.Table | None = doc.get(CONFIG_TOOL_NITPICK_KEY)
if not table:
super_table = tomlkit.table(True)
nitpick_table = tomlkit.table()
nitpick_table.update({CONFIG_KEY_STYLE: []})
super_table.append(PROJECT_NAME, nitpick_table)
doc.append(CONFIG_KEY_TOOL, super_table)
table = doc.get(CONFIG_TOOL_NITPICK_KEY)

existing_styles: items.Array = table.get(CONFIG_KEY_STYLE)
if existing_styles is None:
existing_styles = tomlkit.array()
table.add(CONFIG_KEY_STYLE, existing_styles)

ignored_styles: items.Array = table.get(CONFIG_KEY_DONT_SUGGEST)
if ignored_styles is None:
ignored_styles = tomlkit.array()
if suggest:
# Create the ignored styles array only when suggesting styles
table.add(CONFIG_KEY_DONT_SUGGEST, ignored_styles)

return ToolNitpickConfig(config_file, doc, table, existing_styles, ignored_styles)

def merge_styles(self, offline: bool) -> Iterator[Fuss]:
"""Merge one or multiple style files."""
config = self.read_configuration()
Expand Down
3 changes: 0 additions & 3 deletions src/nitpick/tomlkit_ext.py
Expand Up @@ -137,6 +137,3 @@ def update_comment_before(table: Table, key: str, marker: str, comment: str) ->
del table.value.body[marker_start : marker_end + 1]
insert_point = marker_start
table.value.body.insert(insert_point, (None, new_comment))


# TODO(AA): test: all cases of update_comment_before() (check the missing coverage)

0 comments on commit 6a78e27

Please sign in to comment.