pathlib: add Path.expanduser()

Signed-off-by: Michael Hirsch <michael@scivision.dev>
pull/727/head
scivision 2023-09-13 20:35:12 -04:00
rodzic e6b89eafa3
commit 0ae6340fd7
2 zmienionych plików z 15 dodań i 0 usunięć

Wyświetl plik

@ -184,6 +184,13 @@ class Path:
index = -len(self.suffix) or None
return Path(self._path[:index] + suffix)
def expanduser(self):
if self._path == "~" or self._path.startswith("~" + _SEP):
return Path(os.getenv("HOME") + self._path[1:])
if self._path[0] == "~":
raise RuntimeError("User home directory expansion not supported.")
return self
@property
def stem(self):
return self.name.rsplit(".", 1)[0]

Wyświetl plik

@ -322,3 +322,11 @@ class TestPathlib(unittest.TestCase):
self.assertTrue(Path("foo/test").with_suffix(".tar") == Path("foo/test.tar"))
self.assertTrue(Path("foo/bar.bin").with_suffix(".txt") == Path("foo/bar.txt"))
self.assertTrue(Path("bar.txt").with_suffix("") == Path("bar"))
def test_expanduser(self):
self.assertFalse(str(Path("~").expanduser()) == "~")
self.assertTrue(str(Path("~").expanduser()) == os.getenv("HOME"))
self.assertTrue(str(Path("~/foo").expanduser()) == os.getenv("HOME") + "/foo")
with self.assertRaises(RuntimeError):
Path("~foo").expanduser()