Skip to content

Commit

Permalink
format with Ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
zacharyburnett committed Nov 18, 2023
1 parent c43a40d commit e01b6ca
Show file tree
Hide file tree
Showing 16 changed files with 119 additions and 219 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,5 @@ repos:
rev: "v0.1.5"
hooks:
- id: ruff
args: ["--fix", "--show-fixes"]
args: ["--fix", "--show-fixes", "--unsafe-fixes"]
- id: ruff-format
13 changes: 3 additions & 10 deletions peppyproject/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,10 @@

@app.command()
def main(
directory: Path = typer.Argument(
None, help="directory from which to read configuration"
),
output_filename: Path = typer.Option(
None, "-o", "--output", help="path to which to write TOML"
),
directory: Path = typer.Argument(None, help="directory from which to read configuration"),
output_filename: Path = typer.Option(None, "-o", "--output", help="path to which to write TOML"),
):
"""
read a Python project configuration and output a PEP621-compliant `pyproject.toml`
"""

"""Read a Python project configuration and output a PEP621-compliant `pyproject.toml`."""
if directory is None:
directory = Path.cwd()

Expand Down
121 changes: 39 additions & 82 deletions peppyproject/base.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
from __future__ import annotations

from abc import ABC
from collections.abc import Collection, Iterator, Mapping, MutableMapping
from configparser import ConfigParser
from datetime import datetime
from pathlib import Path
from tempfile import NamedTemporaryFile
from typing import Any, Collection, Iterator, Mapping, MutableMapping, Union
from typing import Any

import tomli
import tomli_w
Expand All @@ -14,15 +17,13 @@


class ConfigurationTable(MutableMapping, ABC):
"""
abstraction of a TOML configuration table
"""
"""abstraction of a TOML configuration table."""

name: str
fields: dict[str, Any]
start_with_placeholders: bool = True

def __init__(self, **kwargs):
def __init__(self, **kwargs) -> None:
if self.start_with_placeholders:
self.__configuration = {key: None for key in self.fields}
else:
Expand All @@ -31,7 +32,7 @@ def __init__(self, **kwargs):
self.update(kwargs)

@classmethod
def from_file(cls, filename: str) -> "ConfigurationTable":
def from_file(cls, filename: str) -> ConfigurationTable:
if not isinstance(filename, Path):
filename = Path(filename)

Expand All @@ -43,10 +44,7 @@ def from_file(cls, filename: str) -> "ConfigurationTable":
base_table = cls.name.split(".", 1)[0]
if base_table in file_configuration:
configuration.update(file_configuration[base_table])
elif (
filename.suffix.lower() in [".cfg", ".ini"]
or filename.name.lower() == "setup.py"
):
elif filename.suffix.lower() in [".cfg", ".ini"] or filename.name.lower() == "setup.py":
if filename.suffix.lower() in [".cfg", ".ini"]:
with open(filename) as configuration_file:
ini_string = configuration_file.read()
Expand All @@ -65,25 +63,17 @@ def from_file(cls, filename: str) -> "ConfigurationTable":
setup_cfg.add_section(section_name)
setup_cfg.set(section_name, key, value)
else:
value = inify_mapping(
mapping=value, name=f"{section_name}.{key}"
)
value = inify_mapping(mapping=value, name=f"{section_name}.{key}")
for (
value_section_name,
value_section,
) in value.items():
if len(value_section) == 0:
if (
value_section_name
== "options.packages.find"
):
if value_section_name == "options.packages.find":
value_section["namespaces"] = "False"
else:
continue
if (
value_section_name
not in setup_cfg.sections()
):
if value_section_name not in setup_cfg.sections():
setup_cfg.add_section(value_section_name)
for (
entry_name,
Expand Down Expand Up @@ -119,19 +109,14 @@ def from_file(cls, filename: str) -> "ConfigurationTable":
setuptools_table = tool_table["setuptools"]
if "packages" in setuptools_table:
packages_table = setuptools_table["packages"]
if "find" in packages_table:
if "namespaces" in packages_table["find"]:
packages_table["find"]["namespaces"] = (
packages_table["find"]["namespaces"] == "True"
)
if "find" in packages_table and "namespaces" in packages_table["find"]:
packages_table["find"]["namespaces"] = packages_table["find"]["namespaces"] == "True"
setuptools_table["packages"] = packages_table
if setup_py is not None:
if "extras-require" in setuptools_table:
if "project" not in file_configuration:
file_configuration["project"] = ConfigurationSubTable()
file_configuration["project"][
"optional-dependencies"
] = setup_py["extras_require"]
file_configuration["project"]["optional-dependencies"] = setup_py["extras_require"]

Check warning on line 119 in peppyproject/base.py

View check run for this annotation

Codecov / codecov/patch

peppyproject/base.py#L119

Added line #L119 was not covered by tests
del setuptools_table["extras-require"]
if "package-data" in setuptools_table:
if "project" not in file_configuration:
Expand All @@ -146,7 +131,7 @@ def from_file(cls, filename: str) -> "ConfigurationTable":
return configuration

@classmethod
def from_directory(cls, directory: str) -> "ConfigurationTable":
def from_directory(cls, directory: str) -> ConfigurationTable:
if not isinstance(directory, Path):
directory = Path(directory)

Expand All @@ -155,20 +140,15 @@ def from_directory(cls, directory: str) -> "ConfigurationTable":

file_configurations = {}
for filename in directory.iterdir():
if filename.is_file() and (
filename.name.lower() in known_filenames
or filename.suffix.lower() in known_suffixes
):
if filename.is_file() and (filename.name.lower() in known_filenames or filename.suffix.lower() in known_suffixes):
file_configuration = cls.from_file(filename)
if len(file_configuration) > 0:
file_configurations[filename.name] = file_configuration

configuration = cls()
configuration.__from_directory = directory
file_configurations = [
file_configurations[filename]
for filename in reversed(known_filenames)
if filename in file_configurations
file_configurations[filename] for filename in reversed(known_filenames) if filename in file_configurations
]
for file_configuration in file_configurations:
if file_configuration is not None and len(file_configuration) > 0:
Expand All @@ -179,23 +159,15 @@ def from_directory(cls, directory: str) -> "ConfigurationTable":
def __getitem__(self, key: str) -> Any:
return self.__configuration[key]

def __setitem__(self, key: str, value: Any):
def __setitem__(self, key: str, value: Any) -> None:
if key in self.fields:
desired_type = self.fields[key]
subtable_class = (
desired_type
if desired_type is not None and not isinstance(desired_type, Mapping)
else ConfigurationSubTable
desired_type if desired_type is not None and not isinstance(desired_type, Mapping) else ConfigurationSubTable
)
if hasattr(desired_type, "__origin__") and (
(
hasattr(desired_type.__origin__, "__name__")
and desired_type.__origin__.__name__ == "Union"
)
or (
hasattr(desired_type.__origin__, "_name")
and desired_type.__origin__._name == "Union"
)
(hasattr(desired_type.__origin__, "__name__") and desired_type.__origin__.__name__ == "Union")
or (hasattr(desired_type.__origin__, "_name") and desired_type.__origin__._name == "Union")
):
values = []
errors = []
Expand All @@ -207,24 +179,20 @@ def __setitem__(self, key: str, value: Any):
if len(values) == 0:
raise RuntimeError(";".join(errors))
self.__configuration[key] = values[0]
else:
if isinstance(desired_type, Mapping) and isinstance(value, Mapping):
if len(value) > 0:
for sub_key, sub_value in value.items():
if sub_key in desired_type:
if (
key not in self.__configuration
or self.__configuration[key] is None
):
self.__configuration[key] = subtable_class()
self[key][sub_key] = typepigeon.to_type(
sub_value,
desired_type[sub_key],
)
else:
self.__configuration[key] = subtable_class()
elif isinstance(desired_type, Mapping) and isinstance(value, Mapping):
if len(value) > 0:
for sub_key, sub_value in value.items():
if sub_key in desired_type:
if key not in self.__configuration or self.__configuration[key] is None:
self.__configuration[key] = subtable_class()
self[key][sub_key] = typepigeon.to_type(
sub_value,
desired_type[sub_key],
)
else:
self.__configuration[key] = typepigeon.to_type(value, desired_type)
self.__configuration[key] = subtable_class()

Check warning on line 193 in peppyproject/base.py

View check run for this annotation

Codecov / codecov/patch

peppyproject/base.py#L193

Added line #L193 was not covered by tests
else:
self.__configuration[key] = typepigeon.to_type(value, desired_type)
else:
self.__configuration[key] = value

Expand All @@ -233,7 +201,7 @@ def update(self, items: Mapping):
if value is not None and (not hasattr(value, "__len__") or len(value) > 0):
self[key] = value

def __delitem__(self, key: str):
def __delitem__(self, key: str) -> None:
message = "cannot delete configuration entry; set as `None` instead"
raise RuntimeError(message)

Expand All @@ -247,15 +215,11 @@ def __len__(self) -> int:
if entry is not None
}
return len(
[
length
for length in lengths.values()
if not self.start_with_placeholders or length > 0
],
[length for length in lengths.values() if not self.start_with_placeholders or length > 0],
)

@property
def __toml(self) -> dict[str, Union[str, dict]]:
def __toml(self) -> dict[str, str | dict]:
return {
key: value.__toml
if isinstance(value, ConfigurationTable)
Expand All @@ -281,11 +245,7 @@ def __repr__(self) -> str:
configuration_string = {
key: value
for key, value in self.__configuration.items()
if value is not None
and (
not self.start_with_placeholders
or (not hasattr(value, "__len__") or len(value) > 0)
)
if value is not None and (not self.start_with_placeholders or (not hasattr(value, "__len__") or len(value) > 0))
}
return repr(configuration_string)

Expand All @@ -301,10 +261,7 @@ def to_dict(value: Mapping) -> dict:
if isinstance(value, Mapping):
for entry_name, entry in value.items():
if isinstance(entry, Mapping):
entry = {
subentry_name: to_dict(subentry)
for subentry_name, subentry in entry.items()
}
entry = {subentry_name: to_dict(subentry) for subentry_name, subentry in entry.items()}
output[entry_name] = entry
else:
output = value
Expand Down
15 changes: 5 additions & 10 deletions peppyproject/configuration.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,28 @@
from collections.abc import Iterator, Mapping
from pathlib import Path
from typing import Iterator, Mapping

from peppyproject.base import ConfigurationTable
from peppyproject.tables import BuildConfiguration, ProjectMetadata, ToolsTable
from peppyproject.tools.setuptools_scm import SetuptoolsSCMTable


class PyProjectConfiguration(Mapping):
"""
abstraction of ``pyproject.toml`` configuration
"""
"""abstraction of ``pyproject.toml`` configuration."""

def __init__(
self,
project: ProjectMetadata = None,
build_system: BuildConfiguration = None,
tool: ToolsTable = None,
):
) -> None:
if project is None or len(project) == 0:
project = ProjectMetadata()
if tool is None or len(tool) == 0:
tool = ToolsTable()
if build_system is None or len(build_system) == 0:
build_system = BuildConfiguration.default_setuptools()
if project["dynamic"] is not None and "version" in project["dynamic"]:
if not any(
"setuptools_scm" in requirement
for requirement in build_system["requires"]
):
if not any("setuptools_scm" in requirement for requirement in build_system["requires"]):
build_system["requires"].append("setuptools_scm[toml]>=3.4")
if "setuptools_scm" not in tool:
tool["setuptools_scm"] = SetuptoolsSCMTable()
Expand Down Expand Up @@ -67,7 +62,7 @@ def __iter__(self) -> Iterator:

def __repr__(self) -> str:
tables_string = ", ".join(
f"{key}={repr(value)}"
f"{key}={value!r}"
for key, value in self.__tables.items()
if value is not None and (not hasattr(value, "__len__") or len(value) > 0)
)
Expand Down
Loading

0 comments on commit e01b6ca

Please sign in to comment.