Skip to content

Commit

Permalink
refactor: merge nested modules
Browse files Browse the repository at this point in the history
Because this is not Java nor PHP:
- less imports
- less lines in one module than in all separate modules
- less imports outside top-level
  • Loading branch information
andreoliwa committed Nov 9, 2023
1 parent 2651164 commit f603245
Show file tree
Hide file tree
Showing 24 changed files with 910 additions and 1,041 deletions.
2 changes: 1 addition & 1 deletion docs/autofix_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

from nitpick.constants import CONFIG_FILES, DOT, EDITOR_CONFIG, PYTHON_PYLINTRC, PYTHON_SETUP_CFG, READ_THE_DOCS_URL
from nitpick.core import Nitpick
from nitpick.style.fetchers.pypackage import BuiltinStyle, builtin_styles
from nitpick.style import BuiltinStyle, builtin_styles

RST_DIVIDER_FROM_HERE = ".. auto-generated-from-here"
RST_DIVIDER_START = ".. auto-generated-start-{}"
Expand Down
3 changes: 1 addition & 2 deletions docs/source/nitpick.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ Subpackages

nitpick.plugins
nitpick.resources
nitpick.style

Submodules
----------
Expand All @@ -28,11 +27,11 @@ Submodules
nitpick.config
nitpick.constants
nitpick.core
nitpick.enums
nitpick.exceptions
nitpick.fields
nitpick.flake8
nitpick.generic
nitpick.schemas
nitpick.style
nitpick.typedefs
nitpick.violations
22 changes: 2 additions & 20 deletions docs/source/nitpick.style.rst
Original file line number Diff line number Diff line change
@@ -1,25 +1,7 @@
nitpick.style package
=====================
nitpick.style module
====================

.. automodule:: nitpick.style
:members:
:undoc-members:
:show-inheritance:

Subpackages
-----------

.. toctree::
:maxdepth: 4

nitpick.style.fetchers

Submodules
----------

.. toctree::
:maxdepth: 4

nitpick.style.cache
nitpick.style.config
nitpick.style.core
3 changes: 1 addition & 2 deletions src/nitpick/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,8 @@
from loguru import logger

from nitpick.blender import TomlDoc
from nitpick.constants import CONFIG_TOOL_KEY, CONFIG_TOOL_NITPICK_KEY, PROJECT_NAME
from nitpick.constants import CONFIG_TOOL_KEY, CONFIG_TOOL_NITPICK_KEY, PROJECT_NAME, OptionEnum
from nitpick.core import Nitpick
from nitpick.enums import OptionEnum
from nitpick.exceptions import QuitComplainingError
from nitpick.generic import relative_to_current_dir
from nitpick.violations import Reporter
Expand Down
60 changes: 60 additions & 0 deletions src/nitpick/constants.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
"""Constants."""
from __future__ import annotations

import os
import re
from datetime import timedelta
from enum import Enum, IntEnum, auto

import jmespath
from requests_cache import DO_NOT_CACHE, NEVER_EXPIRE

# keep-sorted start
CACHE_DIR_NAME = ".cache"
Expand All @@ -9,6 +17,10 @@
DOT_NITPICK_TOML = ".nitpick.toml"
EDITOR_CONFIG = ".editorconfig"
FLAKE8_PREFIX = "NIP"
GITHUB_COM = "github.com"
GITHUB_COM_API = "api.github.com"
GITHUB_COM_QUERY_STRING_TOKEN = "token" # nosec # noqa: S105
GITHUB_COM_RAW = "raw.githubusercontent.com"
GIT_AT_REFERENCE = "@"
GOLANG_MOD = "go.mod"
GOLANG_SUM = "go.sum"
Expand All @@ -29,8 +41,10 @@
PYTHON_SETUP_PY = "setup.py"
PYTHON_TOX_INI = "tox.ini"
READ_THE_DOCS_URL = "https://nitpick.rtfd.io/en/latest/"
REGEX_CACHE_UNIT = re.compile(r"(?P<number>\d+)\s+(?P<unit>(minute|hour|day|week))", re.IGNORECASE)
RUST_CARGO_STAR = "Cargo.*"
TOML_EXTENSION = ".toml"
WRITE_STYLE_MAX_ATTEMPTS = 5
# keep-sorted end

# These depend on some constants above, so they can't be sorted automatically
Expand Down Expand Up @@ -58,3 +72,49 @@
)
CONFIG_TOOL_NITPICK_KEY = f"{CONFIG_TOOL_KEY}.{PROJECT_NAME}"
JMEX_TOOL_NITPICK = jmespath.compile(CONFIG_TOOL_NITPICK_KEY)


class _OptionMixin:
"""Private mixin used to test the CLI options."""

name: str

def as_flake8_flag(self) -> str:
"""Format the name of a flag to be used on the CLI."""
slug = self.name.lower().replace("_", "-")
return f"--{PROJECT_NAME}-{slug}"

def as_envvar(self) -> str:
"""Format the name of an environment variable."""
return f"{PROJECT_NAME.upper()}_{self.name.upper()}"

def get_environ(self) -> str:
"""Get the value of an environment variable."""
return os.environ.get(self.as_envvar(), "")


class OptionEnum(_OptionMixin, Enum):
"""Options to be used with the CLI."""

OFFLINE = "Offline mode: no style will be downloaded (no HTTP requests at all)"


class CachingEnum(IntEnum):
"""Caching modes for styles."""

#: Never cache, the style file(s) are always looked-up.
NEVER = auto()

#: Once the style(s) are cached, they never expire.
FOREVER = auto()

#: The cache expires after the configured amount of time (minutes/hours/days).
EXPIRES = auto()


# TODO(AA): move this to the enum above
CACHE_EXPIRATION_DEFAULTS = {
CachingEnum.NEVER: DO_NOT_CACHE,
CachingEnum.FOREVER: NEVER_EXPIRE,
CachingEnum.EXPIRES: timedelta(hours=1),
}
8 changes: 2 additions & 6 deletions src/nitpick/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
from nitpick.generic import filter_names, glob_files, relative_to_current_dir
from nitpick.plugins.info import FileInfo
from nitpick.schemas import BaseNitpickSchema, flatten_marshmallow_errors, help_message
from nitpick.style import StyleManager
from nitpick.violations import Fuss, ProjectViolations, Reporter, StyleViolations

if TYPE_CHECKING:
Expand Down Expand Up @@ -285,9 +286,6 @@ def merge_styles(self, offline: bool) -> Iterator[Fuss]:
"""Merge one or multiple style files."""
config = self.read_configuration()

# pylint: disable=import-outside-toplevel
from nitpick.style import StyleManager

style = StyleManager(self, offline, config.cache)
base = config.file.expanduser().resolve().as_uri() if config.file else None
style_errors = list(style.find_initial_styles(list(always_iterable(config.styles)), base))
Expand All @@ -296,7 +294,7 @@ def merge_styles(self, offline: bool) -> Iterator[Fuss]:

self.style_dict = style.merge_toml_dict()

from nitpick.flake8 import NitpickFlake8Extension
from nitpick.flake8 import NitpickFlake8Extension # pylint: disable=import-outside-toplevel

minimum_version = search_json(self.style_dict, JMEX_NITPICK_MINIMUM_VERSION, None)
logger.debug(f"Minimum version: {minimum_version}")
Expand All @@ -313,8 +311,6 @@ def merge_styles(self, offline: bool) -> Iterator[Fuss]:

def create_configuration(self, config: Configuration, *style_urls: str) -> None:
"""Create a configuration file."""
from nitpick.style import StyleManager # pylint: disable=import-outside-toplevel

if config.file:
doc: TOMLDocument = tomlkit.parse(config.file.read_text())
else:
Expand Down
43 changes: 0 additions & 43 deletions src/nitpick/enums.py

This file was deleted.

3 changes: 1 addition & 2 deletions src/nitpick/flake8.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,8 @@
from loguru import logger

from nitpick import __version__
from nitpick.constants import FLAKE8_PREFIX, PROJECT_NAME
from nitpick.constants import FLAKE8_PREFIX, PROJECT_NAME, OptionEnum
from nitpick.core import Nitpick, find_main_python_file
from nitpick.enums import OptionEnum
from nitpick.exceptions import QuitComplainingError
from nitpick.typedefs import Flake8Error
from nitpick.violations import Fuss
Expand Down

0 comments on commit f603245

Please sign in to comment.