Commits

Antoine Pitrou committed 9cee619

Add the with_suffix method

Comments (0)

Files changed (2)

         return self._from_parsed_parts(self._drv, self._root,
                                        self._parts[:-1] + [name])
 
+    def with_suffix(self, suffix):
+        """Return a new path with the file suffix changed (or added, if none)."""
+        name = self.name
+        if not name:
+            raise ValueError("%r has an empty name" % (self,))
+        old_suffix = self.suffix
+        if not old_suffix:
+            name = name + suffix
+        else:
+            name = name[:-len(old_suffix)] + suffix
+        return self._from_parsed_parts(self._drv, self._root,
+                                       self._parts[:-1] + [name])
+
     def relative(self):
         """Return a new path without any drive and root.
         """
         self.assertRaises(ValueError, P('.').with_name, 'd.xml')
         self.assertRaises(ValueError, P('/').with_name, 'd.xml')
 
+    def test_with_suffix_common(self):
+        P = self.cls
+        self.assertEqual(P('a/b').with_suffix('.gz'), P('a/b.gz'))
+        self.assertEqual(P('/a/b').with_suffix('.gz'), P('/a/b.gz'))
+        self.assertEqual(P('a/b.py').with_suffix('.gz'), P('a/b.gz'))
+        self.assertEqual(P('/a/b.py').with_suffix('.gz'), P('/a/b.gz'))
+        self.assertRaises(ValueError, P('').with_suffix, '.gz')
+        self.assertRaises(ValueError, P('.').with_suffix, '.gz')
+        self.assertRaises(ValueError, P('/').with_suffix, '.gz')
+
     def test_relative_common(self):
         P = self.cls
         p = P('a/b')
         self.assertEqual(P('c:/a/Dot ending.').with_name('d.xml'), P('c:/a/d.xml'))
         self.assertRaises(ValueError, P('c:').with_name, 'd.xml')
         self.assertRaises(ValueError, P('c:/').with_name, 'd.xml')
+        self.assertRaises(ValueError, P('//My/Share').with_name, 'd.xml')
+
+    def test_with_suffix(self):
+        P = self.cls
+        self.assertEqual(P('c:a/b').with_suffix('.gz'), P('c:a/b.gz'))
+        self.assertEqual(P('c:/a/b').with_suffix('.gz'), P('c:/a/b.gz'))
+        self.assertEqual(P('c:a/b.py').with_suffix('.gz'), P('c:a/b.gz'))
+        self.assertEqual(P('c:/a/b.py').with_suffix('.gz'), P('c:/a/b.gz'))
+        self.assertRaises(ValueError, P('').with_suffix, '.gz')
+        self.assertRaises(ValueError, P('.').with_suffix, '.gz')
+        self.assertRaises(ValueError, P('/').with_suffix, '.gz')
+        self.assertRaises(ValueError, P('//My/Share').with_suffix, '.gz')
 
     def test_relative(self):
         P = self.cls