From 6b9c0a3f955ddcc7b9d0970690acf2eaafd93658 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sybren=20A=2E=20St=C3=BCvel?= Date: Tue, 27 Feb 2018 15:32:28 +0100 Subject: [PATCH] Support slash notation for BlendPath This mimicks the slash notation of pathlib.Path --- blender_asset_tracer/bpathlib.py | 13 +++++++++++++ tests/test_bpathlib.py | 9 +++++++++ 2 files changed, 22 insertions(+) diff --git a/blender_asset_tracer/bpathlib.py b/blender_asset_tracer/bpathlib.py index 228d482..f31a4fb 100644 --- a/blender_asset_tracer/bpathlib.py +++ b/blender_asset_tracer/bpathlib.py @@ -25,6 +25,19 @@ class BlendPath(bytes): """ return self.decode('utf8', errors='replace') + def __truediv__(self, subpath: bytes): + """Slash notation like pathlib.Path.""" + sub = BlendPath(subpath) + if sub.is_absolute(): + raise ValueError("'a / b' only works when 'b' is a relative path") + return BlendPath(os.path.join(self, sub)) + + def __rtruediv__(self, parentpath: bytes): + """Slash notation like pathlib.Path.""" + if self.is_absolute(): + raise ValueError("'a / b' only works when 'b' is a relative path") + return BlendPath(os.path.join(parentpath, self)) + def is_blendfile_relative(self) -> bool: return self[:2] == b'//' diff --git a/tests/test_bpathlib.py b/tests/test_bpathlib.py index be6def6..c60d67c 100644 --- a/tests/test_bpathlib.py +++ b/tests/test_bpathlib.py @@ -42,3 +42,12 @@ class BlendPathTest(unittest.TestCase): BlendPath(b'../some/file.blend').absolute(b'/root/to')) self.assertEqual(b'/shared/some/file.blend', BlendPath(b'/shared/some/file.blend').absolute(b'/root/to')) + + def test_slash(self): + self.assertEqual(b'/root/and/parent.blend', BlendPath(b'/root/and') / b'parent.blend') + with self.assertRaises(ValueError): + BlendPath(b'/root/and') / b'/parent.blend' + + self.assertEqual(b'/root/and/parent.blend', b'/root/and' / BlendPath(b'parent.blend')) + with self.assertRaises(ValueError): + b'/root/and' / BlendPath(b'/parent.blend')