Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MAINT: Use pathlib to manage paths #83

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
25 changes: 16 additions & 9 deletions extension_helpers/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import sys
from importlib import machinery as import_machinery
from importlib.util import module_from_spec, spec_from_file_location
from pathlib import Path

__all__ = ["write_if_different", "import_file"]

Expand Down Expand Up @@ -86,23 +87,24 @@ def write_if_different(filename, data):

Parameters
----------
filename : str
filename : str | PathLike
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suspect this is the root of the doc fail, this needs to be a fully qualified thing like os.PathLike or whatever it is.

The file name to be written to.
data : bytes
The data to be written to ``filename``.
"""

assert isinstance(data, bytes)

if os.path.exists(filename):
with open(filename, "rb") as fd:
original_data = fd.read()
if isinstance(filename, str):
filename = Path(filename)

if filename.exists():
original_data = filename.read_bytes()
else:
original_data = None

if original_data != data:
with open(filename, "wb") as fd:
fd.write(data)
filename.write_bytes(data)


def import_file(filename, name=None):
Expand All @@ -123,13 +125,18 @@ def import_file(filename, name=None):
# be unique, and it doesn't really matter because the name isn't
# used directly here anyway.

if isinstance(filename, str):
filename = Path(filename)
if name is None:
basename = os.path.splitext(filename)[0]
name = "_".join(os.path.abspath(basename).split(os.sep)[1:])
basename = filename.parent / filename.stem
name = "_".join(basename.resolve().parts[1:])

if not os.path.exists(filename):
if not filename.exists():
raise ImportError(f"Could not import file {filename}")

# importlib requires the filename to be a string (?)
# running tox tests seem to error out if filename is a Path object
filename = str(filename)
loader = import_machinery.SourceFileLoader(name, filename)
spec = spec_from_file_location(name, filename)
mod = module_from_spec(spec)
Expand Down