Skip to content

Commit

Permalink
Merge 5abd805 into 6c84f19
Browse files Browse the repository at this point in the history
  • Loading branch information
andreoliwa committed Apr 6, 2021
2 parents 6c84f19 + 5abd805 commit 155cf66
Show file tree
Hide file tree
Showing 6 changed files with 98 additions and 4 deletions.
18 changes: 16 additions & 2 deletions docs/cli.rst
Expand Up @@ -45,8 +45,9 @@ Main options
--help Show this message and exit.
Commands:
ls List of files configured in the Nitpick style.
run Apply suggestions to configuration files.
init Initialise Nitpick configuration.
ls List of files configured in the Nitpick style.
run Apply suggestions to configuration files.
``run``: Apply style to files
-----------------------------
Expand Down Expand Up @@ -88,3 +89,16 @@ At the end of execution, this command displays:
Options:
--help Show this message and exit.
``init``: Initialise a configuration file
-----------------------------------------


.. code-block::
Usage: nitpick init [OPTIONS]
Initialise Nitpick configuration.
Options:
--help Show this message and exit.
1 change: 1 addition & 0 deletions docs/generate_rst.py
Expand Up @@ -64,6 +64,7 @@
""",
),
("ls", "List configures files", ""),
("init", "Initialise a configuration file", ""),
]

nit = Nitpick.singleton().init()
Expand Down
16 changes: 15 additions & 1 deletion src/nitpick/cli.py
Expand Up @@ -19,7 +19,7 @@
from click.exceptions import Exit
from loguru import logger

from nitpick.constants import PROJECT_NAME
from nitpick.constants import DOT_NITPICK_TOML, PROJECT_NAME
from nitpick.core import Nitpick
from nitpick.enums import OptionEnum
from nitpick.exceptions import QuitComplainingError
Expand Down Expand Up @@ -114,3 +114,17 @@ def ls(context, files): # pylint: disable=invalid-name
# TODO: test API .configured_files
for file in nit.configured_files(*files):
click.secho(relative_to_current_dir(file), fg="green" if file.exists() else "red")


@nitpick_cli.command()
@click.pass_context
def init(context):
"""Initialise Nitpick configuration."""
nit = get_nitpick(context)
config = nit.project.read_configuration()
if config.file:
click.secho(f"A config file already exists: {config.file.name}", fg="yellow")
raise Exit(1)

nit.project.create_configuration()
click.secho(f"Config file created: {DOT_NITPICK_TOML}", fg="green")
33 changes: 33 additions & 0 deletions src/nitpick/project.py
Expand Up @@ -3,6 +3,7 @@
from dataclasses import dataclass
from functools import lru_cache
from pathlib import Path
from textwrap import dedent
from typing import Iterable, Iterator, List, Optional, Set

import pluggy
Expand All @@ -14,10 +15,12 @@
from nitpick import fields, plugins
from nitpick.constants import (
CONFIG_FILES,
DOT_NITPICK_TOML,
MANAGE_PY,
NITPICK_MINIMUM_VERSION_JMEX,
PROJECT_NAME,
PYPROJECT_TOML,
READ_THE_DOCS_URL,
ROOT_FILES,
ROOT_PYTHON_FILES,
TOOL_NITPICK,
Expand Down Expand Up @@ -233,3 +236,33 @@ def merge_styles(self, offline: bool) -> Iterator[Fuss]:

self.nitpick_section = self.style_dict.get("nitpick", {})
self.nitpick_files_section = self.nitpick_section.get("files", {})

def create_configuration(self) -> None:
"""Create a configuration file."""
from nitpick.style import Style # pylint: disable=import-outside-toplevel

generated_by = "This file was generated by the `nitpick init` command"
more_info = f"More info at {READ_THE_DOCS_URL}configuration.html"

# 1. This commented code generates an empty "[tool]" section above "[tool.nitpick]":
# doc = document()
# doc.add(comment(generated_by))
# doc.add(comment(more_info))
# doc["tool"] = table().add("nitpick", table().add("style", [Style.get_default_style_url()]))

# 2. Using doc["tool.nitpick"] or doc.add("tool.nitpick", ...) will generate a section with quotes instead:
# ["tool.nitpick"]

# So... giving up on tomlkit for now. ¯\_(ツ)_/¯

template = dedent(
f"""
# {generated_by}
# {more_info}
[{TOOL_NITPICK}]
style = ["{Style.get_default_style_url()}"]
"""
)

path: Path = self.root / DOT_NITPICK_TOML
path.write_text(template.lstrip())
9 changes: 8 additions & 1 deletion tests/helpers.py
Expand Up @@ -353,10 +353,17 @@ def cli_run(
compare(actual=actual, expected=expected)
return self

def cli_ls(self, str_or_lines: StrOrList, exit_code: int = None):
def cli_ls(self, str_or_lines: StrOrList, *, exit_code: int = None) -> "ProjectMock":
"""Run the ls command and assert the output."""
result, actual, expected = self._simulate_cli("ls", str_or_lines, exit_code=exit_code)
compare(actual=actual, expected=expected, prefix=f"Result: {result}")
return self

def cli_init(self, str_or_lines: StrOrList, *, exit_code: int = None) -> "ProjectMock":
"""Run the init command and assert the output."""
result, actual, expected = self._simulate_cli("init", str_or_lines, exit_code=exit_code)
compare(actual=actual, expected=expected, prefix=f"Result: {result}")
return self

def assert_file_contents(self, *name_contents: Union[PathOrStr, str]):
"""Assert the file has the expected contents."""
Expand Down
25 changes: 25 additions & 0 deletions tests/test_cli.py
@@ -1,4 +1,8 @@
"""CLI tests."""
import pytest

from nitpick.constants import DOT_NITPICK_TOML, PYPROJECT_TOML, READ_THE_DOCS_URL, TOOL_NITPICK
from nitpick.style import Style
from tests.helpers import XFAIL_ON_WINDOWS, ProjectMock


Expand Down Expand Up @@ -28,3 +32,24 @@ def test_simple_error(tmp_path):
line-length = 100
"""
)


@pytest.mark.parametrize("config_file", [DOT_NITPICK_TOML, PYPROJECT_TOML])
def test_config_file_already_exists(tmp_path, config_file):
"""Test if .nitpick.toml already exists."""
project = ProjectMock(tmp_path, pyproject_toml=False, setup_py=True).save_file(config_file, "")
project.cli_init(f"A config file already exists: {config_file}", exit_code=1)


def test_create_basic_dot_nitpick_toml(tmp_path):
"""If no config file is found, create a basic .nitpick.toml."""
project = ProjectMock(tmp_path, pyproject_toml=False, setup_py=True)
project.cli_init(f"Config file created: {DOT_NITPICK_TOML}").assert_file_contents(
DOT_NITPICK_TOML,
f"""
# This file was generated by the `nitpick init` command
# More info at {READ_THE_DOCS_URL}configuration.html
[{TOOL_NITPICK}]
style = ["{Style.get_default_style_url()}"]
""",
)

0 comments on commit 155cf66

Please sign in to comment.