From cfad50e748447b1c5a1ad1aaa5bfc5647b3e9ec7 Mon Sep 17 00:00:00 2001 From: mcflugen Date: Thu, 4 Apr 2024 21:05:24 -0600 Subject: [PATCH] changed BabelMetadata to BabelConfig --- babelizer/_utils.py | 4 +- babelizer/cli.py | 26 +++++------ babelizer/{metadata.py => config.py} | 64 ++++++++++++++-------------- babelizer/render.py | 22 +++++----- tests/cli_test.py | 4 +- 5 files changed, 60 insertions(+), 60 deletions(-) rename babelizer/{metadata.py => config.py} (84%) diff --git a/babelizer/_utils.py b/babelizer/_utils.py index 8659c21..7b18b67 100644 --- a/babelizer/_utils.py +++ b/babelizer/_utils.py @@ -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 @@ -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) diff --git a/babelizer/cli.py b/babelizer/cli.py index 1dcaec8..029f191 100644 --- a/babelizer/cli.py +++ b/babelizer/cli.py @@ -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) @@ -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, @@ -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() @@ -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)) @@ -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, @@ -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"] @@ -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, diff --git a/babelizer/metadata.py b/babelizer/config.py similarity index 84% rename from babelizer/metadata.py rename to babelizer/config.py index 29988cd..1e466be 100644 --- a/babelizer/metadata.py +++ b/babelizer/config.py @@ -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 @@ -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, @@ -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 ---------- @@ -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] @@ -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 ---------- @@ -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 ---------- @@ -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: @@ -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"] @@ -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 ---------- @@ -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 ---------- @@ -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) diff --git a/babelizer/render.py b/babelizer/render.py index d7cbe50..5750f4a 100644 --- a/babelizer/render.py +++ b/babelizer/render.py @@ -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, @@ -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 @@ -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) @@ -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) diff --git a/tests/cli_test.py b/tests/cli_test.py index 83ff3d4..7037397 100644 --- a/tests/cli_test.py +++ b/tests/cli_test.py @@ -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(): @@ -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():