Skip to content

Commit

Permalink
refactor: rename and sort constants
Browse files Browse the repository at this point in the history
  • Loading branch information
andreoliwa committed Nov 5, 2023
1 parent 5cca920 commit 3c48862
Show file tree
Hide file tree
Showing 19 changed files with 218 additions and 228 deletions.
6 changes: 3 additions & 3 deletions docs/autofix_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
import click
from slugify import slugify

from nitpick.constants import CONFIG_FILES, DOT, EDITOR_CONFIG, PYLINTRC, READ_THE_DOCS_URL, SETUP_CFG
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

Expand Down Expand Up @@ -117,8 +117,8 @@ def row(self) -> tuple[str, str, str]:
FileType("Any TOML file", f"{READ_THE_DOCS_URL}plugins.html#toml-files", True, True),
FileType("Any YAML file", f"{READ_THE_DOCS_URL}plugins.html#yaml-files", True, True),
FileType(EDITOR_CONFIG, f"{READ_THE_DOCS_URL}library.html#any", True, True),
FileType(PYLINTRC, f"{READ_THE_DOCS_URL}plugins.html#ini-files", True, True),
FileType(SETUP_CFG, f"{READ_THE_DOCS_URL}plugins.html#ini-files", True, True),
FileType(PYTHON_PYLINTRC, f"{READ_THE_DOCS_URL}plugins.html#ini-files", True, True),
FileType(PYTHON_SETUP_CFG, f"{READ_THE_DOCS_URL}plugins.html#ini-files", True, True),
}
PLANNED_FILE_TYPES: set[FileType] = {
FileType("Any Markdown file", "", 280, 0),
Expand Down
10 changes: 6 additions & 4 deletions src/nitpick/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from loguru import logger

from nitpick.blender import TomlDoc
from nitpick.constants import PROJECT_NAME, TOOL_KEY, TOOL_NITPICK_KEY
from nitpick.constants import CONFIG_TOOL_KEY, CONFIG_TOOL_NITPICK_KEY, PROJECT_NAME
from nitpick.core import Nitpick
from nitpick.enums import OptionEnum
from nitpick.exceptions import QuitComplainingError
Expand Down Expand Up @@ -150,9 +150,11 @@ def init(context, style_urls):
nit = get_nitpick(context)
config = nit.project.read_configuration()

if config.file and PROJECT_NAME in TomlDoc(path=config.file).as_object.get(TOOL_KEY, {}):
click.secho(f"The config file {config.file.name} already has a [{TOOL_NITPICK_KEY}] section.", fg="yellow")
if config.file and PROJECT_NAME in TomlDoc(path=config.file).as_object.get(CONFIG_TOOL_KEY, {}):
click.secho(
f"The config file {config.file.name} already has a [{CONFIG_TOOL_NITPICK_KEY}] section.", fg="yellow"
)
raise Exit(1)

nit.project.create_configuration(config, *style_urls)
click.secho(f"A [{TOOL_NITPICK_KEY}] section was created in the config file: {config.file.name}", fg="green")
click.secho(f"A [{CONFIG_TOOL_NITPICK_KEY}] section was created in the config file: {config.file.name}", fg="green")
102 changes: 45 additions & 57 deletions src/nitpick/constants.py
Original file line number Diff line number Diff line change
@@ -1,72 +1,60 @@
"""Constants."""
import jmespath

PROJECT_OWNER = "andreoliwa"
PROJECT_NAME = "nitpick"
FLAKE8_PREFIX = "NIP"
# keep-sorted start
CACHE_DIR_NAME = ".cache"
TOML_EXTENSION = ".toml"
DOT_NITPICK_TOML = f".nitpick{TOML_EXTENSION}"
NITPICK_STYLE_TOML = f"nitpick-style{TOML_EXTENSION}"
MERGED_STYLE_TOML = f"merged-style{TOML_EXTENSION}"
CONFIG_DUNDER_LIST_KEYS = "__list_keys"
CONFIG_TOOL_KEY = "tool"
DOT = "."
DOT_NITPICK_TOML = ".nitpick.toml"
EDITOR_CONFIG = ".editorconfig"
FLAKE8_PREFIX = "NIP"
GIT_AT_REFERENCE = "@"
GOLANG_MOD = "go.mod"
GOLANG_SUM = "go.sum"
JAVASCRIPT_PACKAGE_JSON = "package.json"
JMEX_NITPICK_MINIMUM_VERSION = jmespath.compile("nitpick.minimum_version")
JMEX_NITPICK_STYLES_INCLUDE = jmespath.compile("nitpick.styles.include")
MERGED_STYLE_TOML = "merged-style.toml"
NITPICK_STYLE_TOML = "nitpick-style.toml"
PRE_COMMIT_CONFIG_YAML = ".pre-commit-config.yaml"
PROJECT_NAME = "nitpick"
PROJECT_OWNER = "andreoliwa"
PYTHON_MANAGE_PY = "manage.py"
PYTHON_PIPFILE_STAR = "Pipfile*"
PYTHON_PYLINTRC = ".pylintrc"
PYTHON_PYPROJECT_TOML = "pyproject.toml"
PYTHON_REQUIREMENTS_STAR_TXT = "requirements*.txt"
PYTHON_SETUP_CFG = "setup.cfg"
PYTHON_SETUP_PY = "setup.py"
PYTHON_TOX_INI = "tox.ini"
READ_THE_DOCS_URL = "https://nitpick.rtfd.io/en/latest/"
RUST_CARGO_STAR = "Cargo.*"
TOML_EXTENSION = ".toml"
# keep-sorted end

# Special files
# Python
PYPROJECT_TOML = "pyproject.toml"
SETUP_PY = "setup.py"
SETUP_CFG = "setup.cfg"
REQUIREMENTS_STAR_TXT = "requirements*.txt"
PIPFILE_STAR = "Pipfile*"
MANAGE_PY = "manage.py"
ROOT_PYTHON_FILES = ("app.py", "wsgi.py", "autoapp.py", MANAGE_PY)
TOX_INI = "tox.ini"
PYLINTRC = ".pylintrc"
# Tools
PRE_COMMIT_CONFIG_YAML = ".pre-commit-config.yaml"
EDITOR_CONFIG = ".editorconfig"
# JavaScript
PACKAGE_JSON = "package.json"
# Rust
CARGO_STAR = "Cargo.*"
# Golang
GO_MOD = "go.mod"
GO_SUM = "go.sum"
# All root files
# These depend on some constants above, so they can't be sorted automatically
ROOT_PYTHON_FILES = ("app.py", "wsgi.py", "autoapp.py", PYTHON_MANAGE_PY)
ROOT_FILES = (
DOT_NITPICK_TOML,
NITPICK_STYLE_TOML,
PRE_COMMIT_CONFIG_YAML,
PYPROJECT_TOML,
SETUP_PY,
SETUP_CFG,
REQUIREMENTS_STAR_TXT,
PIPFILE_STAR,
TOX_INI,
PACKAGE_JSON,
CARGO_STAR,
GO_MOD,
GO_SUM,
PYTHON_PYPROJECT_TOML,
PYTHON_SETUP_PY,
PYTHON_SETUP_CFG,
PYTHON_REQUIREMENTS_STAR_TXT,
PYTHON_PIPFILE_STAR,
PYTHON_TOX_INI,
JAVASCRIPT_PACKAGE_JSON,
RUST_CARGO_STAR,
GOLANG_MOD,
GOLANG_SUM,
*ROOT_PYTHON_FILES,
)
CONFIG_FILES = (DOT_NITPICK_TOML, PYPROJECT_TOML)

# Config sections and keys
TOOL_KEY = "tool"
TOOL_NITPICK_KEY = f"{TOOL_KEY}.{PROJECT_NAME}"
RUN_NITPICK_INIT_OR_CONFIGURE_STYLE_MANUALLY = (
CONFIG_FILES = (DOT_NITPICK_TOML, PYTHON_PYPROJECT_TOML)
CONFIG_RUN_NITPICK_INIT_OR_CONFIGURE_STYLE_MANUALLY = (
f" Run 'nitpick init' or configure a style manually ({', '.join(CONFIG_FILES)})."
f" See {READ_THE_DOCS_URL}configuration.html"
)

# JMESPath expressions
TOOL_NITPICK_JMEX = jmespath.compile(TOOL_NITPICK_KEY)
NITPICK_STYLES_INCLUDE_JMEX = jmespath.compile("nitpick.styles.include")
NITPICK_MINIMUM_VERSION_JMEX = jmespath.compile("nitpick.minimum_version")

DOT = "."

GIT_AT_REFERENCE = "@"

# Special configurations for plugins
DUNDER_LIST_KEYS = "__list_keys"
CONFIG_TOOL_NITPICK_KEY = f"{CONFIG_TOOL_KEY}.{PROJECT_NAME}"
JMEX_TOOL_NITPICK = jmespath.compile(CONFIG_TOOL_NITPICK_KEY)
4 changes: 2 additions & 2 deletions src/nitpick/plugins/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

from nitpick.blender import BaseDoc, flatten_quotes, search_json
from nitpick.config import SpecialConfig
from nitpick.constants import DUNDER_LIST_KEYS
from nitpick.constants import CONFIG_DUNDER_LIST_KEYS
from nitpick.typedefs import JsonDict, mypy_property
from nitpick.violations import Fuss, Reporter, SharedViolations

Expand Down Expand Up @@ -70,7 +70,7 @@ def _merge_special_configs(self):

# The user can override the default list keys (if any) by setting them on the style file.
# pylint: disable=assigning-non-slot,no-member
spc.list_keys.from_style = self.expected_config.pop(DUNDER_LIST_KEYS, None) or {}
spc.list_keys.from_style = self.expected_config.pop(CONFIG_DUNDER_LIST_KEYS, None) or {}
temp_dict.update(flatten_quotes(spc.list_keys.from_style))

flat_config = flatten_quotes(self.expected_config)
Expand Down
22 changes: 11 additions & 11 deletions src/nitpick/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,16 @@
from nitpick.blender import TomlDoc, search_json
from nitpick.constants import (
CONFIG_FILES,
CONFIG_TOOL_NITPICK_KEY,
DOT_NITPICK_TOML,
MANAGE_PY,
NITPICK_MINIMUM_VERSION_JMEX,
JMEX_NITPICK_MINIMUM_VERSION,
JMEX_TOOL_NITPICK,
PROJECT_NAME,
PYPROJECT_TOML,
PYTHON_MANAGE_PY,
PYTHON_PYPROJECT_TOML,
READ_THE_DOCS_URL,
ROOT_FILES,
ROOT_PYTHON_FILES,
TOOL_NITPICK_JMEX,
TOOL_NITPICK_KEY,
)
from nitpick.exceptions import QuitComplainingError
from nitpick.generic import version_to_tuple
Expand Down Expand Up @@ -75,7 +75,7 @@ def find_main_python_file(root_dir: Path) -> Path:
# 1.
[root_dir / root_file for root_file in ROOT_PYTHON_FILES],
# 2.
root_dir.glob(f"*/{MANAGE_PY}"),
root_dir.glob(f"*/{PYTHON_MANAGE_PY}"),
# 3.
root_dir.glob("*.py"),
root_dir.glob("*/*.py"),
Expand Down Expand Up @@ -159,7 +159,7 @@ def read_configuration(self) -> Configuration:
return Configuration(None, [], "")

toml_doc = TomlDoc(path=config_file)
config_dict = search_json(toml_doc.as_object, TOOL_NITPICK_JMEX, {})
config_dict = search_json(toml_doc.as_object, JMEX_TOOL_NITPICK, {})
validation_errors = ToolNitpickSectionSchema().validate(config_dict)
if not validation_errors:
return Configuration(config_file, config_dict.get("style", []), config_dict.get("cache", ""))
Expand All @@ -168,10 +168,10 @@ def read_configuration(self) -> Configuration:
from nitpick.plugins.info import FileInfo

raise QuitComplainingError(
Reporter(FileInfo(self, PYPROJECT_TOML)).make_fuss(
Reporter(FileInfo(self, PYTHON_PYPROJECT_TOML)).make_fuss(
StyleViolations.INVALID_DATA_TOOL_NITPICK,
flatten_marshmallow_errors(validation_errors),
section=TOOL_NITPICK_KEY,
section=CONFIG_TOOL_NITPICK_KEY,
)
)

Expand All @@ -192,7 +192,7 @@ def merge_styles(self, offline: bool) -> Iterator[Fuss]:

from nitpick.flake8 import NitpickFlake8Extension

minimum_version = search_json(self.style_dict, NITPICK_MINIMUM_VERSION_JMEX, None)
minimum_version = search_json(self.style_dict, JMEX_NITPICK_MINIMUM_VERSION, None)
logger.debug(f"Minimum version: {minimum_version}")
if minimum_version and version_to_tuple(NitpickFlake8Extension.version) < version_to_tuple(minimum_version):
yield Reporter().make_fuss(
Expand Down Expand Up @@ -222,7 +222,7 @@ def create_configuration(self, config: Configuration, *style_urls: str) -> None:
tool_nitpick.add(tomlkit.comment("Generated by the 'nitpick init' command"))
tool_nitpick.add(tomlkit.comment(f"More info at {READ_THE_DOCS_URL}configuration.html"))
tool_nitpick.add("style", tomlkit.array([tomlkit.string(url) for url in style_urls]))
doc.add(SingleKey(TOOL_NITPICK_KEY, KeyType.Bare), tool_nitpick)
doc.add(SingleKey(CONFIG_TOOL_NITPICK_KEY, KeyType.Bare), tool_nitpick)

# config.file will always have a value at this point, but mypy can't see it.
config.file.write_text(tomlkit.dumps(doc, sort_keys=True))
4 changes: 2 additions & 2 deletions src/nitpick/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from nitpick import fields
from nitpick.blender import flatten_quotes
from nitpick.constants import READ_THE_DOCS_URL, SETUP_CFG
from nitpick.constants import PYTHON_SETUP_CFG, READ_THE_DOCS_URL


def flatten_marshmallow_errors(errors: dict) -> str:
Expand Down Expand Up @@ -63,7 +63,7 @@ class NitpickFilesSectionSchema(BaseNitpickSchema):
absent = fields.Dict(fields.NonEmptyString, fields.String())
present = fields.Dict(fields.NonEmptyString, fields.String())
# TODO: refactor: load this schema dynamically, then add this next field setup_cfg
setup_cfg = fields.Nested(IniSchema, data_key=SETUP_CFG)
setup_cfg = fields.Nested(IniSchema, data_key=PYTHON_SETUP_CFG)


class NitpickMetaSchema(BaseNitpickSchema):
Expand Down
8 changes: 4 additions & 4 deletions src/nitpick/style/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@
from nitpick.blender import SEPARATOR_FLATTEN, TomlDoc, custom_reducer, custom_splitter, search_json
from nitpick.constants import (
CACHE_DIR_NAME,
JMEX_NITPICK_STYLES_INCLUDE,
MERGED_STYLE_TOML,
NITPICK_STYLE_TOML,
NITPICK_STYLES_INCLUDE_JMEX,
PROJECT_NAME,
PROJECT_OWNER,
PYPROJECT_TOML,
PYTHON_PYPROJECT_TOML,
)
from nitpick.exceptions import QuitComplainingError, pretty_exception
from nitpick.generic import url_to_python_path
Expand Down Expand Up @@ -107,7 +107,7 @@ def find_initial_styles(self, configured_styles: Sequence[str], base: str | None

if configured_styles:
chosen_styles = configured_styles
config_file = base_url.path.segments[-1] if base else PYPROJECT_TOML
config_file = base_url.path.segments[-1] if base else PYTHON_PYPROJECT_TOML
logger.info(f"Using styles configured in {config_file}: {', '.join(chosen_styles)}")
else:
paths = glob_files(project_root, [NITPICK_STYLE_TOML])
Expand Down Expand Up @@ -151,7 +151,7 @@ def _include_style(self, style_url: furl) -> Iterator[Fuss]:
# normalize sub-style URIs, before merging
sub_styles = [
self._style_fetcher_manager.normalize_url(ref, style_url)
for ref in always_iterable(search_json(read_toml_dict, NITPICK_STYLES_INCLUDE_JMEX, []))
for ref in always_iterable(search_json(read_toml_dict, JMEX_NITPICK_STYLES_INCLUDE, []))
]
if sub_styles:
read_toml_dict.setdefault("nitpick", {}).setdefault("styles", {})["include"] = [
Expand Down
6 changes: 3 additions & 3 deletions src/nitpick/violations.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

import click

from nitpick.constants import FLAKE8_PREFIX, RUN_NITPICK_INIT_OR_CONFIGURE_STYLE_MANUALLY
from nitpick.constants import CONFIG_RUN_NITPICK_INIT_OR_CONFIGURE_STYLE_MANUALLY, FLAKE8_PREFIX

if TYPE_CHECKING:
from nitpick.plugins.info import FileInfo
Expand Down Expand Up @@ -68,15 +68,15 @@ class StyleViolations(ViolationEnum):
INVALID_DATA_TOOL_NITPICK = (1, " has an incorrect style. Invalid data in [{section}]:")
INVALID_TOML = (1, " has an incorrect style. Invalid TOML{exception}")
INVALID_CONFIG = (1, " has an incorrect style. Invalid config:")
NO_STYLE_CONFIGURED = (4, f"No style file configured.{RUN_NITPICK_INIT_OR_CONFIGURE_STYLE_MANUALLY}")
NO_STYLE_CONFIGURED = (4, f"No style file configured.{CONFIG_RUN_NITPICK_INIT_OR_CONFIGURE_STYLE_MANUALLY}")


class ProjectViolations(ViolationEnum):
"""Project initialization violations."""

NO_ROOT_DIR = (
101,
f"No root directory detected.{RUN_NITPICK_INIT_OR_CONFIGURE_STYLE_MANUALLY}",
f"No root directory detected.{CONFIG_RUN_NITPICK_INIT_OR_CONFIGURE_STYLE_MANUALLY}",
)
NO_PYTHON_FILE = (102, "No Python file was found on the root dir and subdir of {root!r}")
MISSING_FILE = (103, " should exist{extra}")
Expand Down
8 changes: 4 additions & 4 deletions tests/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@
NITPICK_STYLE_TOML,
PRE_COMMIT_CONFIG_YAML,
PROJECT_NAME,
PYPROJECT_TOML,
SETUP_CFG,
PYTHON_PYPROJECT_TOML,
PYTHON_SETUP_CFG,
)
from nitpick.core import Nitpick
from nitpick.flake8 import NitpickFlake8Extension
Expand Down Expand Up @@ -250,11 +250,11 @@ def ensure_toml_extension(filename: PathOrStr) -> PathOrStr:

def setup_cfg(self, file_contents: PathOrStr) -> ProjectMock:
"""Save setup.cfg."""
return self.save_file(SETUP_CFG, from_path_or_str(file_contents))
return self.save_file(PYTHON_SETUP_CFG, from_path_or_str(file_contents))

def pyproject_toml(self, file_contents: PathOrStr) -> ProjectMock:
"""Save pyproject.toml."""
return self.save_file(PYPROJECT_TOML, from_path_or_str(file_contents))
return self.save_file(PYTHON_PYPROJECT_TOML, from_path_or_str(file_contents))

def pre_commit(self, file_contents: PathOrStr) -> ProjectMock:
"""Save .pre-commit-config.yaml."""
Expand Down

0 comments on commit 3c48862

Please sign in to comment.