summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--summainlib.py25
-rw-r--r--summainlib_tests.py24
2 files changed, 49 insertions, 0 deletions
diff --git a/summainlib.py b/summainlib.py
index 7f67908..6628ce0 100644
--- a/summainlib.py
+++ b/summainlib.py
@@ -141,7 +141,32 @@ class FilesystemObject(object):
def __getitem__(self, key):
return self.values.get(key, '')
+
+ def _isdir(self):
+ '''Is this a directory?'''
+
+ return stat.S_ISDIR(int(self['Mode'], 8))
+
+ def relative_path(self, root):
+ '''Return a path that is relative to root, if possible.
+
+ If pathname does not start with root, then return it
+ unmodified.
+ '''
+
+ if root.endswith(os.sep):
+ root2 = root
+ else:
+ root2 = root + os.sep
+ pathname = self['Name']
+ if pathname.startswith(root2):
+ return pathname[len(root2):]
+ elif pathname == root and self._isdir():
+ return '.'
+ else:
+ return pathname
+
def format(self): # pragma: no cover
keys = ['Name'] + [x
for x in sorted(self.values.keys())
diff --git a/summainlib_tests.py b/summainlib_tests.py
index 313b3a4..283c22b 100644
--- a/summainlib_tests.py
+++ b/summainlib_tests.py
@@ -144,6 +144,30 @@ class FilesystemObjectTests(unittest.TestCase):
fso = self.new('foo', mode=stat.S_IFDIR | 0777)
output = fso.format()
self.assert_('Size:' not in output)
+
+ def test_relative_path_returns_path_if_not_starting_with_root(self):
+ fso = self.new('/foo/bar')
+ self.assertEqual(fso.relative_path('/yo'), '/foo/bar')
+
+ def test_relative_path_returns_partial_path_if_starting_with_root(self):
+ fso = self.new('/foo/bar')
+ self.assertEqual(fso.relative_path('/foo'), 'bar')
+
+ def test_relative_path_returns_dot_if_same_as_root_and_dir(self):
+ fso = self.new('/foo/bar', mode=stat.S_IFDIR)
+ self.assertEqual(fso.relative_path('/foo/bar'), '.')
+
+ def test_relative_path_returns_path_if_same_as_root_and_not_dir(self):
+ fso = self.new('/foo/bar', mode=stat.S_IFREG)
+ self.assertEqual(fso.relative_path('/foo/bar'), '/foo/bar')
+
+ def test_relative_path_returns_path_if_root_is_slashless_prefix(self):
+ fso = self.new('/foobar', mode=stat.S_IFREG)
+ self.assertEqual(fso.relative_path('/foo'), '/foobar')
+
+ def test_relative_path_returns_partial_path_if_root_ends_in_slash(self):
+ fso = self.new('/foo/bar', mode=stat.S_IFREG)
+ self.assertEqual(fso.relative_path('/foo/'), 'bar')
class FilesystemObjectNormalizedNumbersTests(unittest.TestCase):