Browse Source

symlink: append index of backup to filename if backup already exists

Fabian Peter Hammerle 8 years ago
parent
commit
ccd56cd4c3
2 changed files with 38 additions and 1 deletions
  1. 8 1
      osex/__init__.py
  2. 30 0
      tests/test_symlink.py

+ 8 - 1
osex/__init__.py

@@ -1,4 +1,5 @@
 import os
+import sys
 
 def symlink(source, link_name, relative = False, override = False, backup = True, backup_suffix = "~"):
     if relative:
@@ -7,7 +8,13 @@ def symlink(source, link_name, relative = False, override = False, backup = True
     # True for broken symbolic links. 
     if override and os.path.lexists(link_name):
         if backup:
-            os.rename(link_name, link_name + backup_suffix)
+            backup_name_prefix = link_name + backup_suffix
+            backup_name = backup_name_prefix
+            backup_index = 0
+            while os.path.lexists(backup_name):
+                backup_index += 1
+                backup_name = backup_name_prefix + str(backup_index)
+            os.rename(link_name, backup_name)
         else:
             if os.path.isdir(link_name):
                 os.rmdir(link_name)

+ 30 - 0
tests/test_symlink.py

@@ -98,3 +98,33 @@ def test_backup_dir(tmpdir):
     assert os.path.lexists("link")
     assert os.readlink("link") == "source"
     assert os.path.isdir("link-")
+
+def test_backup_multiple_links(tmpdir):
+    os.chdir(tmpdir.strpath)
+    # source 1
+    osex.symlink("source1", "link")
+    assert os.path.lexists("link")
+    # source 2
+    osex.symlink("source2", "link", override = True, backup = True, backup_suffix = "~")
+    assert os.path.lexists("link")
+    assert os.readlink("link") == "source2"
+    assert os.path.lexists("link~")
+    assert os.readlink("link~") == "source1"
+    # source 3
+    osex.symlink("source3", "link", override = True, backup = True, backup_suffix = "~")
+    assert os.path.lexists("link")
+    assert os.readlink("link") == "source3"
+    assert os.path.lexists("link~")
+    assert os.readlink("link~") == "source1"
+    assert os.path.lexists("link~1")
+    assert os.readlink("link~1") == "source2"
+    # source 4
+    osex.symlink("source4", "link", override = True, backup = True, backup_suffix = "~")
+    assert os.path.lexists("link")
+    assert os.readlink("link") == "source4"
+    assert os.path.lexists("link~")
+    assert os.readlink("link~") == "source1"
+    assert os.path.lexists("link~1")
+    assert os.readlink("link~1") == "source2"
+    assert os.path.lexists("link~2")
+    assert os.readlink("link~2") == "source3"