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

Resolve path enhancements #178

Merged
merged 2 commits into from
Oct 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions src/pyswip/prolog.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,9 +203,13 @@ def retractall(cls, term, catcherrors=False):

@classmethod
def consult(
cls, filename: str, *, catcherrors=False, relative_to: Union[str, Path] = ""
cls,
path: Union[str, Path],
*,
catcherrors=False,
relative_to: Union[str, Path] = "",
):
path = resolve_path(filename, relative_to)
path = resolve_path(path, relative_to)
next(cls.query(str(path).join(["consult('", "')"]), catcherrors=catcherrors))

@classmethod
Expand Down
15 changes: 7 additions & 8 deletions src/pyswip/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,15 @@
from pathlib import Path


def resolve_path(filename: str, relative_to: Union[str, Path] = "") -> Path:
if not relative_to:
return Path(filename)
relative_to = Path(relative_to)
if not relative_to.exists():
raise FileNotFoundError(None, "Relative path does not exist", str(relative_to))
def resolve_path(path: Union[str, Path], relative_to: Union[str, Path] = "") -> Path:
path = Path(path).expanduser()
if path.is_absolute() or not relative_to:
return path
relative_to = Path(relative_to).expanduser()
if relative_to.is_symlink():
raise ValueError("Symbolic links are not supported")
if relative_to.is_dir():
return relative_to / filename
return relative_to / path
elif relative_to.is_file():
return relative_to.parent / filename
return relative_to.parent / path
raise ValueError("relative_to must be either a filename or a directory")
12 changes: 12 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,15 @@ def test_resolve_path_symbolic_link(self):
self.assertRaises(ValueError, lambda: resolve_path("test_read.pl", symlink))
finally:
temp_dir.cleanup()

def test_resolve_path_absolute(self):
path = resolve_path("/home/pyswip/file")
self.assertEqual(Path("/home/pyswip/file"), path)

def test_resolve_path_without_resolve(self):
path = resolve_path("files/file1.pl")
self.assertEqual(Path("files/file1.pl"), path)

def test_resolve_path_expanduser(self):
path = resolve_path("~/foo/bar")
self.assertEqual(Path.home() / "foo/bar", path)