Skip to content

Commit

Permalink
Resolve path enhancements (#178)
Browse files Browse the repository at this point in the history
Resolve path enhancements
  • Loading branch information
yuce authored Oct 13, 2024
1 parent 7f92e76 commit 660fa89
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 10 deletions.
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)

0 comments on commit 660fa89

Please sign in to comment.