Skip to content

Commit

Permalink
style: format docstrings with pydocstringformatter
Browse files Browse the repository at this point in the history
  • Loading branch information
andreoliwa committed Aug 19, 2023
1 parent 309379e commit 3711aa7
Show file tree
Hide file tree
Showing 20 changed files with 78 additions and 33 deletions.
5 changes: 5 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ repos:
hooks:
- id: ruff
args: [--fix]
# Recommended by pylint, configurable, less destructive than https://github.com/PyCQA/docformatter
- repo: https://github.com/DanielNoord/pydocstringformatter
rev: v0.7.3
hooks:
- id: pydocstringformatter
- repo: https://github.com/aio-libs/sort-all # TODO: style(pre-commit): add sort-all
rev: v1.2.0
hooks:
Expand Down
9 changes: 7 additions & 2 deletions src/nitpick/blender.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,9 @@ def compare_lists_with_dictdiffer(


def search_json(json_data: ElementData, jmespath_expression: ParsedResult | str, default: Any | None = None) -> Any:
"""Search a dictionary or list using a JMESPath expression. Return a default value if not found.
"""Search a dictionary or list using a JMESPath expression.
Return a default value if not found.
>>> data = {"root": {"app": [1, 2], "test": "something"}}
>>> search_json(data, "root.app", None)
Expand Down Expand Up @@ -211,7 +213,10 @@ def quote_if_dotted(key: str) -> str:


def quote_reducer(separator: str) -> Callable:
"""Reducer used to unflatten dicts. Quote keys when they have dots."""
"""Reducer used to unflatten dicts.
Quote keys when they have dots.
"""

def _inner_quote_reducer(key1: str | None, key2: str) -> str:
if key1 is None:
Expand Down
5 changes: 4 additions & 1 deletion src/nitpick/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,10 @@ def enforce_style(self, *partial_names: str, autofix=True) -> Iterator[Fuss]:
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."""
"""List of files configured in the Nitpick style.
Filter only the selected partial names.
"""
return [Path(self.project.root) / key for key in filter_names(self.project.style_dict, *partial_names)]

def echo(self, message: str):
Expand Down
10 changes: 8 additions & 2 deletions src/nitpick/plugins/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,10 @@ def _merge_special_configs(self):
self.special_config = spc

def predefined_special_config(self) -> SpecialConfig: # pylint: disable=no-self-use
"""Create a predefined special configuration for this plugin. Each plugin can override this method."""
"""Create a predefined special configuration for this plugin.
Each plugin can override this method.
"""
return SpecialConfig()

@mypy_property
Expand Down Expand Up @@ -142,7 +145,10 @@ def write_file( # pylint: disable=no-self-use
self,
file_exists: bool, # pylint: disable=unused-argument # noqa: ARG002
) -> Fuss | None:
"""Hook to write the new file when autofix 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
5 changes: 4 additions & 1 deletion src/nitpick/plugins/ini.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,10 @@ def enforce_section(self, section: str) -> Iterator[Fuss]:
yield from self.show_missing_keys(section, values)

def enforce_comma_separated_values(self, section, key, raw_actual: Any, raw_expected: Any) -> Iterator[Fuss]:
"""Enforce sections and keys with comma-separated values. The values might contain spaces."""
"""Enforce sections and keys with comma-separated values.
The values might contain spaces.
"""
actual_set = {s.strip() for s in raw_actual.split(",")}
expected_set = {s.strip() for s in raw_expected.split(",")}
missing = expected_set - actual_set
Expand Down
5 changes: 4 additions & 1 deletion src/nitpick/resources/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
"""A library of Nitpick styles. Building blocks that can be combined and reused."""
"""A library of Nitpick styles.
Building blocks that can be combined and reused.
"""
5 changes: 4 additions & 1 deletion src/nitpick/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,10 @@ class NitpickSectionSchema(BaseNitpickSchema):


class BaseStyleSchema(Schema):
"""Base validation schema for style files. Dynamic fields will be added to it later."""
"""Base validation schema for style files.
Dynamic fields will be added to it later.
"""

error_messages = {"unknown": help_message("Unknown file", "plugins.html")} # noqa: RUF012

Expand Down
3 changes: 1 addition & 2 deletions src/nitpick/style/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@
def parse_cache_option(cache_option: str) -> tuple[CachingEnum, timedelta | int]:
"""Parse the cache option provided on pyproject.toml.
If no cache if provided or is invalid, the default is *one hour*.
If no cache is provided or is invalid, the default is *one hour*.
"""
clean_cache_option = cache_option.strip().upper() if cache_option else ""
try:
Expand Down
1 change: 0 additions & 1 deletion src/nitpick/style/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,6 @@ def find_initial_styles(self, configured_styles: Sequence[str], base: str | None
base is the URL for the source of the initial styles, and is used to
resolve relative references. If omitted, defaults to the project root.
"""
project_root = self.project.root
base_url = furl(base or project_root.resolve().as_uri())
Expand Down
3 changes: 0 additions & 3 deletions src/nitpick/style/fetchers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ def normalize_url(self, url: str | furl, base: furl) -> furl:
The URL is made absolute against base, then passed to individual fetchers
to produce a canonical version of the URL.
"""
if isinstance(url, str) and not url.startswith(self.schemes):
url = self._fetcher_for(base).preprocess_relative_url(url)
Expand All @@ -78,7 +77,6 @@ def fetch(self, url: furl) -> str | None:
Returns None when offline is True and the fetcher would otherwise
require a connection.
"""
fetcher = self._fetcher_for(url)
if self.offline and fetcher.requires_connection:
Expand All @@ -90,7 +88,6 @@ def _fetcher_for(self, url: furl) -> StyleFetcher:
"""Determine which fetcher to be used.
Try a fetcher by domain first, then by protocol scheme.
"""
fetcher = self.fetchers.get(url.host) if url.host else None
if not fetcher:
Expand Down
2 changes: 0 additions & 2 deletions src/nitpick/style/fetchers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ def preprocess_relative_url(self, url: str) -> str: # pylint: disable=no-self-u
Only called for urls that lack a scheme (at the very least), being resolved
against a base URL that matches this specific fetcher.
"""
return url

Expand All @@ -55,7 +54,6 @@ def normalize(self, url: furl) -> furl:
- The base name has .toml appended if not already ending in that extension
- Individual fetchers can further normalize the path and scheme.
"""
new_scheme = self._normalize_scheme(url.scheme)
if new_scheme != url.scheme:
Expand Down
1 change: 0 additions & 1 deletion src/nitpick/style/fetchers/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ def preprocess_relative_url(self, url: str) -> str:
against a base URL that matches this specific fetcher.
Relative paths are file paths; any ~ home reference is expanded at this point.
"""
# We have to expand ~ values before trying to resolve a path as a file URL
path = Path(url).expanduser()
Expand Down
3 changes: 0 additions & 3 deletions src/nitpick/style/fetchers/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ def token(self) -> str | None:
If present and it starts with a ``$``, it will be replaced with the
value of the environment corresponding to the remaining part of the
string.
"""
token = self.auth_token
if token is not None and token.startswith("$"):
Expand Down Expand Up @@ -85,7 +84,6 @@ def from_furl(cls, url: furl) -> GitHubURL:
"""Create an instance from a parsed URL in any accepted format.
See the code for ``test_parsing_github_urls()`` for more examples.
"""
auth_token = url.username or url.args.get(QUERY_STRING_TOKEN)
query_params = tuple((key, value) for key, value in url.args.items() if key != QUERY_STRING_TOKEN)
Expand Down Expand Up @@ -140,7 +138,6 @@ def get_default_branch(api_url: str, *, token: str | None = None) -> str:
``requests.exceptions.HTTPError: 403 Client Error: rate limit exceeded for url``
This function is using ``lru_cache()`` as a simple memoizer, trying to avoid this rate limit error.
"""
headers = {"Authorization": f"token {token}"} if token else None
response = API_SESSION.get(api_url, headers=headers)
Expand Down
1 change: 0 additions & 1 deletion src/nitpick/style/fetchers/pypackage.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ def from_furl(cls, url: furl) -> PythonPackageURL:
"""Create an instance from a parsed URL in any accepted format.
See the code for ``test_parsing_python_package_urls()`` for more examples.
"""
package_name = url.host
resource_path = url.path.segments
Expand Down
4 changes: 3 additions & 1 deletion tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,9 @@ def reactions(c):
}
)
def lab(c, convert_file_name="", lab_help=False):
"""Laboratory of experiments and ideas. You need to install certain tools if you want to use this command.
"""Laboratory of experiments and ideas.
You need to install certain tools if you want to use this command.
Pre-requisites:
- https://github.com/andreoliwa/conjuring
Expand Down
11 changes: 8 additions & 3 deletions tests/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@ def tomlstring(value: Any) -> str:
"""Create a fully-quoted TOML string from a path.
This ensures proper quoting of Windows paths and other values with backslashes.
"""
return tomlkit.string(str(value)).as_string()

Expand Down Expand Up @@ -238,7 +237,10 @@ def load_styles(self, *args: PathOrStr) -> ProjectMock:
return self

def named_style(self, filename: PathOrStr, file_contents: PathOrStr) -> ProjectMock:
"""Save a style file with a name. Add the .toml extension if needed."""
"""Save a style file with a name.
Add the .toml extension if needed.
"""
return self.save_file(self.ensure_toml_extension(filename), from_path_or_str(file_contents))

@staticmethod
Expand Down Expand Up @@ -414,7 +416,10 @@ def cli_init(self, str_or_lines: StrOrList, *args, exit_code: int | None = None)
return self

def assert_file_contents(self, *name_contents: PathOrStr | str | None, lstrip=True) -> ProjectMock:
"""Assert the file has the expected contents. Use `None` to indicate that the file doesn't exist."""
"""Assert the file has the expected contents.
Use `None` to indicate that the file doesn't exist.
"""
assert len(name_contents) % 2 == 0, "Supply pairs of arguments: filename (PathOrStr) and file contents (str)"
for filename, file_contents in windowed(name_contents, 2, step=2):
actual = self.read_file(filename)
Expand Down
10 changes: 8 additions & 2 deletions tests/test_style.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,10 @@ def test_multiple_styles_overriding_values(offline, tmp_path):

@pytest.mark.parametrize("offline", [False, True])
def test_include_styles_overriding_values(offline, tmp_path):
"""One style file can include another (also recursively). Ignore styles that were already included."""
"""One style file can include another (also recursively).
Ignore styles that were already included.
"""
ProjectMock(tmp_path).named_style(
"isort1",
f"""
Expand Down Expand Up @@ -602,7 +605,10 @@ def test_include_remote_style_from_local_style(tmp_path):

@pytest.mark.parametrize("offline", [False, True])
def test_merge_styles_into_single_file(offline, tmp_path):
"""Merge all styles into a single TOML file on the cache dir. Also test merging lists (pre-commit repos)."""
"""Merge all styles into a single TOML file on the cache dir.
Also test merging lists (pre-commit repos).
"""
warnings.simplefilter("ignore") # "repos.yaml" key
ProjectMock(tmp_path).named_style(
"black",
Expand Down
4 changes: 3 additions & 1 deletion tests/test_yaml.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,9 @@ def test_objects_are_compared_by_hash_on_list_of_dicts_and_new_ones_are_added(tm


def test_maximum_two_level_nesting_on_lists_using_jmes_expression_as_list_key_fails(tmp_path, datadir):
"""Test a maximum of two-level nesting on lists. Using a JMES expression as a list key will fail.
"""Test a maximum of two-level nesting on lists.
Using a JMES expression as a list key will fail.
Keys must have a maximum of 2 level for now: parent and nested keys.
"""
Expand Down
5 changes: 4 additions & 1 deletion tests/test_yaml_github_workflows.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,10 @@ def test_list_of_scalars_only_add_elements_that_do_not_exist(tmp_path, datadir):


def test_wildcard_expression_matches_multiple_keys(tmp_path, datadir):
"""Test wildcard expressions that match multiple keys. E.g.: any "jobs.*.steps"."""
"""Test wildcard expressions that match multiple keys.
E.g.: any "jobs.*.steps".
"""
filename = ".github/workflows/anything.yaml"
ProjectMock(tmp_path).save_file(filename, datadir / "wildcard-actual.yaml").style(
datadir / "wildcard-desired.toml"
Expand Down
19 changes: 15 additions & 4 deletions tests/test_yaml_old_pre_commit.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,10 @@ def test_suggest_initial_contents(tmp_path, datadir):


def test_no_yaml_key(tmp_path):
"""What was an invalid repo config before, now will be autofixed. Read the warning on :py:class:`nitpick.plugins.yaml.YamlPlugin`."""
"""What was an invalid repo config before, now will be autofixed.
Read the warning on :py:class:`nitpick.plugins.yaml.YamlPlugin`.
"""
ProjectMock(tmp_path).style(
'''
[[".pre-commit-config.yaml".repos]]
Expand Down Expand Up @@ -235,7 +238,10 @@ def test_repo_does_not_exist(tmp_path):


def test_missing_hooks_in_repo(tmp_path):
"""Test missing hooks in repo. Read the warning on :py:class:`nitpick.plugins.yaml.YamlPlugin`."""
"""Test missing hooks in repo.
Read the warning on :py:class:`nitpick.plugins.yaml.YamlPlugin`.
"""
ProjectMock(tmp_path).style(
"""
[[".pre-commit-config.yaml".repos]]
Expand Down Expand Up @@ -278,7 +284,10 @@ def test_style_missing_hooks_in_repo(tmp_path):


def test_style_missing_id_in_hook(tmp_path):
"""Test style file is missing id in hook. Read the warning on :py:class:`nitpick.plugins.yaml.YamlPlugin`."""
"""Test style file is missing id in hook.
Read the warning on :py:class:`nitpick.plugins.yaml.YamlPlugin`.
"""
ProjectMock(tmp_path).style(
f'''
[[".pre-commit-config.yaml".repos]]
Expand Down Expand Up @@ -351,7 +360,9 @@ def test_missing_hook_with_id(tmp_path):


def test_missing_different_values(tmp_path, datadir, shared_datadir):
"""Test missing and different values on the hooks. All "yaml" keys in the style are now ignored.
"""Test missing and different values on the hooks.
All "yaml" keys in the style are now ignored.
Read the warning on :py:class:`nitpick.plugins.yaml.YamlPlugin`.
"""
Expand Down

0 comments on commit 3711aa7

Please sign in to comment.