Skip to content

Commit

Permalink
fix crashes on python <3.12 after convert to uv
Browse files Browse the repository at this point in the history
basically remove all the legacy importlib hacks

Signed-off-by: Grant Ramsay <[email protected]>
  • Loading branch information
seapagan committed Nov 13, 2024
1 parent dbf04c4 commit 520938a
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 46 deletions.
28 changes: 0 additions & 28 deletions lice2/__init__.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,7 @@
"""Package initialisation."""

from importlib import resources
from pathlib import Path
from typing import IO

from single_source import get_version

try:
from pkg_resources import resource_listdir, resource_stream # type: ignore
except ImportError:

def resource_stream(
package_or_requirement: resources.Package, resource_name: str
) -> IO[bytes]:
"""Emulate the 'resource_stream' method."""
ref = resources.files(package_or_requirement).joinpath(resource_name)
return ref.open("rb")

def resource_listdir(
package_or_requirement: resources.Package, resource_name: str
) -> list[str]:
"""Emulate the 'resource_listdir' method."""
resource_qualname = f"{package_or_requirement}".rstrip(".")
return [
r.name
for r in resources.files(resource_qualname)
.joinpath(resource_name)
.iterdir()
]


__version__ = get_version(__name__, Path(__file__).parent.parent)

__all__ = ["resource_listdir", "resource_stream"]
34 changes: 27 additions & 7 deletions lice2/constants.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
"""Define constants for the LICE2 package."""

import re

from lice2 import resource_listdir
from importlib import resources

# To extend language formatting sopport with a new language, add an item in
# LANGS dict:
Expand Down Expand Up @@ -97,8 +96,29 @@
"unix": ["", "#", ""],
}

LICENSES: list[str] = []
for file in sorted(resource_listdir(__name__, "templates")):
match = re.match(r"template-([a-z0-9_]+).txt", file)
if match:
LICENSES.append(match.groups()[0])

def get_available_licenses() -> list[str]:
"""Get a sorted list of available license names from template files.
Searches for templates in the current package's 'templates' directory
with pattern 'template-{name}.txt'.
Returns:
List of license names sorted alphabetically
"""
# Get the current package name
package_name = __package__ if __package__ else __name__.split(".")[0]

template_path = resources.files(package_name).joinpath("templates")
licenses = []

for file in template_path.iterdir():
if file.is_file():
match = re.match(r"template-([a-z0-9_]+)\.txt", file.name)
if match:
licenses.append(match.groups()[0])

return sorted(licenses)


LICENSES = get_available_licenses()
45 changes: 37 additions & 8 deletions lice2/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import sys
from contextlib import closing
from datetime import datetime
from importlib import resources
from io import StringIO
from pathlib import Path
from types import SimpleNamespace
Expand All @@ -18,7 +19,6 @@
from rich.table import Table
from rich.text import Text

from lice2 import resource_stream
from lice2.config import settings
from lice2.constants import LANG_CMT, LANGS, LICENSES

Expand Down Expand Up @@ -113,17 +113,46 @@ def load_file_template(path: str) -> StringIO:
return template


def get_template_content(license_name: str, *, header: bool = False) -> str:
"""Get the content of a license template as a string.
Args:
license_name: Name of the license template to load
header: If True, load the header template instead of the full license
Returns:
The template content as a string
Raises:
FileNotFoundError: If the template doesn't exist
"""
filename = (
f"template-{license_name}-header.txt"
if header
else f"template-{license_name}.txt"
)
package_name = __package__ or __name__.split(".")[0]
template_file = resources.files(package_name) / "templates" / filename
return template_file.read_text(encoding="utf-8")


def load_package_template(
license_name: str, *, header: bool = False
) -> StringIO:
"""Load license template distributed with package."""
"""Load license template distributed with package.
Args:
license_name: Name of the license template to load
header: If True, load the header template instead of the full license
Returns:
StringIO object containing the template content
Raises:
FileNotFoundError: If the template doesn't exist
"""
content = StringIO()
filename = "template-%s-header.txt" if header else "template-%s.txt"
with resource_stream(
__name__, f"templates/{filename % license_name}"
) as licfile:
for line in licfile:
content.write(line.decode("utf-8")) # write utf-8 string
content.write(get_template_content(license_name, header=header))
return content


Expand Down
3 changes: 0 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,6 @@ dev-dependencies = [
requires = ["hatchling"]
build-backend = "hatchling.build"

[tool.hatch.build.targets.wheel]
packages = ["lice2"]

[tool.poe.tasks]
pre.cmd = "pre-commit run --all-files"
Expand Down Expand Up @@ -137,7 +135,6 @@ convention = "google"
"ARG00", # test fixtures often are not directly used
]


[tool.ruff.lint.isort]
known-first-party = ["lice2"]

Expand Down

0 comments on commit 520938a

Please sign in to comment.