diff options
author | Lars Wirzenius <liw@liw.fi> | 2011-02-18 22:57:46 +0000 |
---|---|---|
committer | Lars Wirzenius <liw@liw.fi> | 2011-02-18 22:57:46 +0000 |
commit | fa78ecc93fe9f4d1638c38e7e9023dc0ca5fd35f (patch) | |
tree | 6fe65537335c875a906df05f73457bbb7b5dc9fd | |
parent | eee02bc86f8867f903e113ca456c498508c7a496 (diff) | |
download | summain-fa78ecc93fe9f4d1638c38e7e9023dc0ca5fd35f.tar.gz |
Add relative_path method, with tests.
-rw-r--r-- | summainlib.py | 25 | ||||
-rw-r--r-- | summainlib_tests.py | 24 |
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): |