From 660fa897ae3b148a54de1a7c2deb352af424c2a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Y=C3=BCce=20Tekol?= Date: Sun, 13 Oct 2024 12:28:59 +0300 Subject: [PATCH] Resolve path enhancements (#178) Resolve path enhancements --- src/pyswip/prolog.py | 8 ++++++-- src/pyswip/utils.py | 15 +++++++-------- tests/test_utils.py | 12 ++++++++++++ 3 files changed, 25 insertions(+), 10 deletions(-) diff --git a/src/pyswip/prolog.py b/src/pyswip/prolog.py index b695b79..569edff 100644 --- a/src/pyswip/prolog.py +++ b/src/pyswip/prolog.py @@ -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 diff --git a/src/pyswip/utils.py b/src/pyswip/utils.py index 006cda3..2ad09c1 100644 --- a/src/pyswip/utils.py +++ b/src/pyswip/utils.py @@ -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") diff --git a/tests/test_utils.py b/tests/test_utils.py index cfca329..21fe62d 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -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)