Skip to content

Commit

Permalink
changed BabelMetadata to BabelConfig
Browse files Browse the repository at this point in the history
  • Loading branch information
mcflugen committed Apr 5, 2024
1 parent be33883 commit cfad50e
Show file tree
Hide file tree
Showing 5 changed files with 60 additions and 60 deletions.
4 changes: 2 additions & 2 deletions babelizer/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ def validate_dict_keys(
Parameters
----------
meta : dict
Configuration metadata
Dictionary to validate.
required : dict, optional
Required keys in configuration.
optional : dict, optional
Expand All @@ -170,7 +170,7 @@ def validate_dict_keys(
Raises
------
ValidationError
Raised for invalid metadata.
Raised for invalid dict.
"""
actual = set(meta)
required = set() if required is None else set(required)
Expand Down
26 changes: 13 additions & 13 deletions babelizer/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@
from babelizer._files.readme import render as render_readme
from babelizer._utils import get_setup_py_version
from babelizer._utils import save_files
from babelizer.config import BabelConfig
from babelizer.errors import OutputDirExistsError
from babelizer.errors import ScanError
from babelizer.errors import SetupPyError
from babelizer.errors import ValidationError
from babelizer.metadata import BabelMetadata
from babelizer.render import render

out = partial(click.secho, bold=True, err=True)
Expand Down Expand Up @@ -90,15 +90,15 @@ def init(

fmt = pathlib.Path(meta.name).suffix[1:] or "toml"
try:
babel_metadata = BabelMetadata.from_stream(cast(io.TextIOBase, meta), fmt=fmt)
babel_config = BabelConfig.from_stream(cast(io.TextIOBase, meta), fmt=fmt)
except (ScanError, ValidationError) as error:
raise BabelizerAbort(str(error))

output = babel_metadata["package"]["name"]
output = babel_config["package"]["name"]

try:
new_folder = render(
babel_metadata,
babel_config,
output,
template=template,
clobber=False,
Expand Down Expand Up @@ -149,14 +149,14 @@ def update(
package_path = os.path.realpath(".")
for fname in ("babel.toml", "babel.yaml", "plugin.yaml"):
# if (package_path / fname).is_file():
# metadata_path = package_path / fname
# config_path = package_path / fname
if os.path.isfile(os.path.join(package_path, fname)):
metadata_path = os.path.join(package_path, fname)
config_path = os.path.join(package_path, fname)
break
else:
metadata_path = None
config_path = None

if not metadata_path:
if not config_path:
err("this does not appear to be a babelized folder (missing 'babel.toml')")
raise click.Abort()

Expand All @@ -166,7 +166,7 @@ def update(
out(f"reading template from {template}")

try:
babel_metadata = BabelMetadata.from_path(metadata_path)
babel_config = BabelConfig.from_path(config_path)
except ValidationError as error:
raise BabelizerAbort(str(error))

Expand All @@ -187,7 +187,7 @@ def update(
out(f"re-rendering {package_path}")
with save_files(["CHANGES.rst", "CREDITS.rst"]):
render(
babel_metadata,
babel_config,
os.path.dirname(package_path),
# package_path.parent,
template=template,
Expand All @@ -196,7 +196,7 @@ def update(
)

extra_files = _repo_contents(package_path) - _generated_files(
babel_metadata, template=template, version=version
babel_config, template=template, version=version
)

ignore = ["meta*", "notebooks*", "docs*", "**/data"]
Expand Down Expand Up @@ -310,11 +310,11 @@ def _repo_contents(base: str) -> set[str]:


def _generated_files(
babel_metadata: BabelMetadata, template: str | None = None, version: str = "0.1"
babel_config: BabelConfig, template: str | None = None, version: str = "0.1"
) -> set[str]:
with tempfile.TemporaryDirectory() as tmpdir:
new_folder = render(
babel_metadata,
babel_config,
tmpdir,
template=template,
version=version,
Expand Down
64 changes: 32 additions & 32 deletions babelizer/metadata.py → babelizer/config.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Library metadata used by the babelizer to wrap libraries."""
"""Library configuration used by the babelizer to wrap libraries."""

from __future__ import annotations

Expand Down Expand Up @@ -27,8 +27,8 @@
from babelizer.errors import ValidationError


class BabelMetadata(Mapping[str, Any]):
"""Library metadata."""
class BabelConfig(Mapping[str, Any]):
"""Babelizer configuration."""

LOADERS: dict[str, Callable[[str], dict[str, Any]]] = {
"yaml": yaml.safe_load,
Expand All @@ -44,7 +44,7 @@ def __init__(
plugin: dict[str, Any] | None = None,
ci: dict[str, Any] | None = None,
):
"""Metadata used by the babelizer to wrap a library.
"""Configuration used by the babelizer to wrap a library.
Parameters
----------
Expand Down Expand Up @@ -77,9 +77,9 @@ def __init__(
"ci": dict(ci or {}),
}

BabelMetadata.validate(config)
BabelConfig.validate(config)

self._meta = BabelMetadata.norm(config)
self._meta = BabelConfig.norm(config)

def __getitem__(self, key: str) -> dict[str, Any]:
return self._meta[key]
Expand All @@ -91,8 +91,8 @@ def __len__(self) -> int:
return len(self._meta)

@classmethod
def from_stream(cls, stream: io.TextIOBase, fmt: str = "toml") -> BabelMetadata:
"""Create an instance of BabelMetadata from a file-like object.
def from_stream(cls, stream: io.TextIOBase, fmt: str = "toml") -> BabelConfig:
"""Create an instance of BabelConfig from a file-like object.
Parameters
----------
Expand All @@ -103,28 +103,28 @@ def from_stream(cls, stream: io.TextIOBase, fmt: str = "toml") -> BabelMetadata:
Returns
-------
BabelMetadata
A BabelMetadata instance.
BabelConfig
A BabelConfig instance.
"""
try:
loader = BabelMetadata.LOADERS[fmt]
loader = BabelConfig.LOADERS[fmt]
except KeyError:
raise ValueError(f"unrecognized format ({fmt})")

try:
meta = loader(stream.read())
except yaml.scanner.ScannerError as error:
raise ScanError(f"unable to scan yaml-formatted metadata file:\n{error}")
raise ScanError(f"unable to scan yaml-formatted config file:\n{error}")
except tomllib.TOMLDecodeError as error:
raise ScanError(f"unable to scan toml-formatted metadata file:\n{error}")
raise ScanError(f"unable to scan toml-formatted config file:\n{error}")
else:
if not isinstance(meta, dict):
raise ValidationError("metadata file does not contain a mapping object")
raise ValidationError("config file does not contain a mapping object")
return cls(**meta)

@classmethod
def from_path(cls, filepath: str) -> BabelMetadata:
"""Create an instance of BabelMetadata from a path-like object.
def from_path(cls, filepath: str) -> BabelConfig:
"""Create an instance of BabelConfig from a path-like object.
Parameters
----------
Expand All @@ -133,26 +133,26 @@ def from_path(cls, filepath: str) -> BabelMetadata:
Returns
-------
A BabelMetadata instance.
A BabelConfig instance.
"""
path = pathlib.Path(filepath)

with open(filepath) as fp:
return BabelMetadata.from_stream(fp, fmt=path.suffix[1:])
return BabelConfig.from_stream(fp, fmt=path.suffix[1:])

@staticmethod
def validate(config: dict[str, Any]) -> None:
"""Ensure babelizer configuration metadata are valid.
"""Ensure babelizer configuration is valid.
Parameters
----------
config : dict
Metadata to babelize a library.
Configuration to babelize a library.
Raises
------
ValidationError
If metadata are not valid.
If configuration is not valid.
"""
libraries = config["library"]
if "entry_point" in libraries:
Expand Down Expand Up @@ -253,29 +253,29 @@ def _handle_old_style_info(info: dict[str, Any]) -> dict[str, Any]:

@staticmethod
def norm(config: dict[str, Any]) -> dict[str, Any]:
"""Ensure current style metadata are used in babelizer configuration.
"""Ensure current style is used in babelizer configuration.
Parameters
----------
config : dict
Metadata to babelize a library.
Configuration to babelize a library.
Return
------
dict
A dict of babelizer configuration metadata.
A dict of babelizer configuration.
"""
build: dict[str, list[str]] = defaultdict(list)
with suppress(KeyError):
build.update(config["build"])

if "entry_point" in config["library"]:
libraries = BabelMetadata._handle_old_style_entry_points(config["library"])
libraries = BabelConfig._handle_old_style_entry_points(config["library"])
else:
libraries = {k: dict(v) for k, v in config["library"].items()}

if "plugin_author" in config["info"]:
info = BabelMetadata._handle_old_style_info(config["info"])
info = BabelConfig._handle_old_style_info(config["info"])
else:
info = config["info"]

Expand Down Expand Up @@ -309,7 +309,7 @@ def norm(config: dict[str, Any]) -> dict[str, Any]:
}

def dump(self, fp: io.TextIOBase, fmt: str = "toml") -> None:
"""Write serialized metadata to a file.
"""Write serialized configuration to a file.
Parameters
----------
Expand All @@ -321,7 +321,7 @@ def dump(self, fp: io.TextIOBase, fmt: str = "toml") -> None:
print(self.format(fmt=fmt), file=fp, end="")

def format(self, fmt: str = "toml") -> str:
"""Serialize metadata to output format.
"""Serialize configuration to output format.
Parameters
----------
Expand All @@ -330,17 +330,17 @@ def format(self, fmt: str = "toml") -> str:
Returns
-------
metadata : str
Serialized metadata.
config : str
Serialized configuration.
"""
return getattr(self, f"format_{fmt}")()

def format_toml(self) -> str:
"""Serialize metadata as TOML.
"""Serialize configuration as TOML.
Returns
-------
str
Serialized metadata as a TOML-formatted string
Serialized configuration as a TOML-formatted string
"""
return tomli_w.dumps(self._meta, multiline_strings=True)
22 changes: 11 additions & 11 deletions babelizer/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@
from babelizer._files.init_py import render as render_init
from babelizer._files.lib_init_py import render as render_lib_init
from babelizer._files.license_rst import render as render_license
from babelizer.config import BabelConfig
from babelizer.errors import OutputDirExistsError
from babelizer.metadata import BabelMetadata


def render(
plugin_metadata: BabelMetadata,
babel_config: BabelConfig,
output: str,
template: str | None = None,
clobber: bool = False,
Expand All @@ -30,8 +30,8 @@ def render(
Parameters
----------
plugin_metadata : BabelMetadata
The metadata used to babelize the library.
babel_config : BabelConfig
The configuration used to babelize the library.
output : str
Name of the directory that will be the new repository.
template : str, optional
Expand All @@ -58,15 +58,15 @@ def render(

context = {
"files": {
"_bmi.py": render_bmi(plugin_metadata),
"__init__.py": render_init(plugin_metadata),
"lib/__init__.py": render_lib_init(plugin_metadata),
".gitignore": render_gitignore(plugin_metadata),
"LICENSE.rst": render_license(plugin_metadata),
"_bmi.py": render_bmi(babel_config),
"__init__.py": render_init(babel_config),
"lib/__init__.py": render_lib_init(babel_config),
".gitignore": render_gitignore(babel_config),
"LICENSE.rst": render_license(babel_config),
},
"now": datetime.datetime.now(),
"package_version": version,
} | {k: plugin_metadata[k] for k in plugin_metadata}
} | {k: babel_config[k] for k in babel_config}

if os.path.exists(output):
raise OutputDirExistsError(output)
Expand All @@ -76,7 +76,7 @@ def render(
path = os.path.realpath(output)

with open(os.path.join(path, "babel.toml"), "w") as fp:
plugin_metadata.dump(fp, fmt="toml")
babel_config.dump(fp, fmt="toml")

git.Repo.init(path)

Expand Down
4 changes: 2 additions & 2 deletions tests/cli_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from click.testing import CliRunner

from babelizer.cli import babelize
from babelizer.metadata import BabelMetadata
from babelizer.config import BabelConfig


def test_help():
Expand Down Expand Up @@ -67,7 +67,7 @@ def test_generate_gives_valid_toml():
assert result.exit_code == 0

config = tomllib.loads(result.output)
BabelMetadata.validate(config)
BabelConfig.validate(config)


def test_init_noargs():
Expand Down

0 comments on commit cfad50e

Please sign in to comment.