Skip to content

Commit

Permalink
add annotations
Browse files Browse the repository at this point in the history
  • Loading branch information
mcflugen committed Mar 20, 2024
1 parent f825575 commit 6086712
Show file tree
Hide file tree
Showing 10 changed files with 117 additions and 103 deletions.
36 changes: 14 additions & 22 deletions babelizer/_files/bmi_py.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import os
from collections.abc import Mapping
from typing import Any


def render(plugin_metadata) -> str:
def render(plugin_metadata: Mapping[str, Any]) -> str:
"""Render _bmi.py."""
languages = {
library["language"] for library in plugin_metadata._meta["library"].values()
}
languages = {library["language"] for library in plugin_metadata["library"].values()}
assert len(languages) == 1
language = languages.pop()

Expand All @@ -15,22 +15,18 @@ def render(plugin_metadata) -> str:
return _render_bmi_c(plugin_metadata)


def _render_bmi_c(plugin_metadata) -> str:
def _render_bmi_c(plugin_metadata: Mapping[str, Any]) -> str:
"""Render _bmi.py for a non-python library."""
languages = [
library["language"] for library in plugin_metadata._meta["library"].values()
]
languages = [library["language"] for library in plugin_metadata["library"].values()]
language = languages[0]
assert language in ("c", "c++", "fortran")

imports = [
f"from {plugin_metadata.get('package', 'name')}.lib import {cls}"
for cls in plugin_metadata._meta["library"]
f"from {plugin_metadata['package']['name']}.lib import {cls}"
for cls in plugin_metadata["library"]
]

names = [
f" {cls!r},".replace("'", '"') for cls in plugin_metadata._meta["library"]
]
names = [f" {cls!r},".replace("'", '"') for cls in plugin_metadata["library"]]

return f"""\
{os.linesep.join(sorted(imports))}
Expand All @@ -41,11 +37,9 @@ def _render_bmi_c(plugin_metadata) -> str:
"""


def _render_bmi_py(plugin_metadata) -> str:
def _render_bmi_py(plugin_metadata: Mapping[str, Any]) -> str:
"""Render _bmi.py for a python library."""
languages = [
library["language"] for library in plugin_metadata._meta["library"].values()
]
languages = [library["language"] for library in plugin_metadata["library"].values()]
language = languages[0]
assert language == "python"

Expand All @@ -60,7 +54,7 @@ def _render_bmi_py(plugin_metadata) -> str:

imports = [
f"from {component['library']} import {component['entry_point']} as {cls}"
for cls, component in plugin_metadata._meta["library"].items()
for cls, component in plugin_metadata["library"].items()
]

rename = [
Expand All @@ -70,12 +64,10 @@ def _render_bmi_py(plugin_metadata) -> str:
""".replace(
"'", '"'
)
for cls in plugin_metadata._meta["library"]
for cls in plugin_metadata["library"]
]

names = [
f" {cls!r},".replace("'", '"') for cls in plugin_metadata._meta["library"]
]
names = [f" {cls!r},".replace("'", '"') for cls in plugin_metadata["library"]]

return f"""\
{header}
Expand Down
4 changes: 3 additions & 1 deletion babelizer/_files/gitignore.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import os
from collections.abc import Mapping
from typing import Any


def render(plugin_metadata) -> str:
def render(plugin_metadata: Mapping[str, Any]) -> str:
"""Render a .gitignore file."""
package_name = plugin_metadata["package"]["name"]

Expand Down
13 changes: 6 additions & 7 deletions babelizer/_files/init_py.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
import os
from collections.abc import Mapping
from typing import Any


def render(plugin_metadata) -> str:
def render(plugin_metadata: Mapping[str, Any]) -> str:
"""Render __init__.py."""
package_name = plugin_metadata.get("package", "name")
package_name = plugin_metadata["package"]["name"]

imports = [f"from {package_name}._version import __version__"]
imports += [
f"from {package_name}._bmi import {cls}"
for cls in plugin_metadata._meta["library"]
f"from {package_name}._bmi import {cls}" for cls in plugin_metadata["library"]
]

names = [
f" {cls!r},".replace("'", '"') for cls in plugin_metadata._meta["library"]
]
names = [f" {cls!r},".replace("'", '"') for cls in plugin_metadata["library"]]

return f"""\
{os.linesep.join(sorted(imports))}
Expand Down
12 changes: 6 additions & 6 deletions babelizer/_files/lib_init_py.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import os
from collections.abc import Mapping
from typing import Any


def render(plugin_metadata) -> str:
def render(plugin_metadata: Mapping[str, Any]) -> str:
"""Render lib/__init__.py."""
package_name = plugin_metadata.get("package", "name")
package_name = plugin_metadata["package"]["name"]
imports = [
f"from {package_name}.lib.{cls.lower()} import {cls}"
for cls in plugin_metadata._meta["library"]
for cls in plugin_metadata["library"]
]

names = [
f" {cls!r},".replace("'", '"') for cls in plugin_metadata._meta["library"]
]
names = [f" {cls!r},".replace("'", '"') for cls in plugin_metadata["library"]]

return f"""\
{os.linesep.join(sorted(imports))}
Expand Down
4 changes: 3 additions & 1 deletion babelizer/_files/license_rst.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from collections.abc import Mapping
from datetime import datetime
from typing import Any


def render(plugin_metadata) -> str:
def render(plugin_metadata: Mapping[str, Any]) -> str:
"""Render LICENSE.rst."""
license_name = plugin_metadata["info"]["package_license"]
kwds = {
Expand Down
2 changes: 1 addition & 1 deletion babelizer/_files/meson_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def render(paths: Iterable[str], install: Iterable[str] = ()) -> str:
return (2 * os.linesep).join(contents)


def _render_install_block(install: Iterable[str]):
def _render_install_block(install: Iterable[str]) -> str:
install_sources = defaultdict(list)
for root, fname in (os.path.split(src) for src in install):
install_sources[root].append(fname)
Expand Down
4 changes: 3 additions & 1 deletion babelizer/_files/readme.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
from typing import Any

from jinja2 import Environment
from jinja2 import FileSystemLoader

from babelizer._datadir import get_datadir


def render(context):
def render(context: dict[str, Any]) -> str:
env = Environment(loader=FileSystemLoader(get_datadir()))
template = env.get_template("{{cookiecutter.package_name}}/README.rst")

Expand Down
78 changes: 45 additions & 33 deletions babelizer/cli.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
"""The command line interface to the babelizer."""

from __future__ import annotations

import fnmatch
import io
import os
import pathlib
import tempfile
from collections.abc import Collection
from functools import partial
from typing import cast

import click
import git
Expand All @@ -30,8 +35,8 @@
class BabelizerAbort(click.Abort):
"""Exception raised when a user interrupts the babelizer."""

def __init__(self, message):
err(str(message))
def __init__(self, message: str):
err(message)


@click.group()
Expand All @@ -42,7 +47,7 @@ def __init__(self, message):
type=click.Path(exists=True, file_okay=False, dir_okay=True, readable=True),
help="Change to directory, then execute.",
)
def babelize(cd):
def babelize(cd: str) -> None:
"""Wrap BMI libraries with Python bindings."""
os.chdir(cd)

Expand Down Expand Up @@ -71,22 +76,24 @@ def babelize(cd):
help="The initial version of the babelized package",
)
@click.argument("meta", type=click.File(mode="r"))
def init(meta, template, quiet, verbose, package_version):
def init(
meta: click.File, template: str, quiet: bool, verbose: bool, package_version: str
) -> None:
"""Initialize a repository with babelized project files.
META is babelizer configuration information, usually saved to a file.
"""
output = pathlib.Path(".")
output = "."
template = template or get_datadir()

if not quiet:
out(f"reading template from {template}")

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

try:
new_folder = render(
Expand All @@ -97,13 +104,12 @@ def init(meta, template, quiet, verbose, package_version):
version=package_version,
)
except (ValidationError, OutputDirExistsError) as error:
raise BabelizerAbort(error)
raise BabelizerAbort(str(error))

if not quiet:
out(
"Don't forget to drop model metadata files into {}".format(
new_folder / "meta"
)
"Don't forget to drop model metadata files into"
f" {os.path.join(new_folder, 'meta')}"
)
repo = git.Repo(new_folder)
repo.git.add("--all")
Expand Down Expand Up @@ -133,13 +139,17 @@ def init(meta, template, quiet, verbose, package_version):
@click.option(
"--set-version", default=None, help="Set the version of the updated package"
)
def update(template, quiet, verbose, set_version):
def update(
template: str | None, quiet: bool, verbose: bool, set_version: str | None
) -> None:
"""Update an existing babelized project."""
package_path = pathlib.Path(".").resolve()

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
# if (package_path / fname).is_file():
# metadata_path = package_path / fname
if os.path.isfile(os.path.join(package_path, fname)):
metadata_path = os.path.join(package_path, fname)
break
else:
metadata_path = None
Expand All @@ -156,7 +166,7 @@ def update(template, quiet, verbose, set_version):
try:
babel_metadata = BabelMetadata.from_path(metadata_path)
except ValidationError as error:
raise BabelizerAbort(error)
raise BabelizerAbort(str(error))

try:
version = set_version or get_setup_py_version()
Expand All @@ -170,12 +180,14 @@ def update(template, quiet, verbose, set_version):
]
)
)
version = "0.1.0" if version is None else version

out(f"re-rendering {package_path}")
with save_files(["CHANGES.rst", "CREDITS.rst"]):
render(
babel_metadata,
package_path.parent,
os.path.dirname(package_path),
# package_path.parent,
template=template,
clobber=True,
version=version,
Expand All @@ -196,22 +208,21 @@ def update(template, quiet, verbose, set_version):

if not quiet:
out(
"Don't forget to drop model metadata files into {}".format(
package_path / "meta"
)
"Don't forget to drop model metadata files into"
f" {os.path.join(package_path, 'meta')}"
)

print(package_path)


@babelize.command()
def sample_config():
def sample_config() -> None:
"""Generate the babelizer configuration file."""
print_sample_config()


@babelize.command()
def sample_license():
def sample_license() -> None:
"""Generate a license file."""
context = {
"info": {
Expand All @@ -224,7 +235,7 @@ def sample_license():


@babelize.command()
def sample_gitignore():
def sample_gitignore() -> None:
"""Generate a .gitignore file."""
context = {
"package": {"name": "springfield_monorail"},
Expand All @@ -235,7 +246,7 @@ def sample_gitignore():

@babelize.command()
@click.argument("extension", nargs=-1)
def sample_meson_build(extension):
def sample_meson_build(extension: Collection[str]) -> None:
"""Generate a meson.build file."""
if len(extension) == 0:
contents = render_meson_build(
Expand All @@ -259,7 +270,7 @@ def sample_meson_build(extension):


@babelize.command()
def sample_readme():
def sample_readme() -> None:
context = {
"cookiecutter": {
"language": "python",
Expand All @@ -280,26 +291,27 @@ def sample_readme():
print(render_readme(context))


def _get_dir_contents(base, trunk=None):
base = pathlib.Path(base)
def _get_dir_contents(base: str, trunk: str | None = None) -> set[str]:
files = set()
for item in base.iterdir():
if item.is_dir():
for item in os.listdir(base):
if os.path.isdir(item):
files |= _get_dir_contents(item, trunk=trunk)
else:
files.add(str(item.relative_to(trunk)))
files.add(os.path.relpath(item, start=trunk))

return files


def _repo_contents(base):
repo = git.Repo(str(base))
def _repo_contents(base: str) -> set[str]:
repo = git.Repo(base)
return set(
repo.git.ls_tree("--full-tree", "-r", "--name-only", "HEAD").splitlines()
)


def _generated_files(babel_metadata, template=None, version="0.1"):
def _generated_files(
babel_metadata: BabelMetadata, template: str | None = None, version: str = "0.1"
) -> set[str]:
with tempfile.TemporaryDirectory() as tmpdir:
new_folder = render(
babel_metadata,
Expand Down
Loading

0 comments on commit 6086712

Please sign in to comment.