Browse Source

symlink: added options 'backup' and 'backup_suffix'

Fabian Peter Hammerle 8 years ago
parent
commit
36dfb0511b
2 changed files with 39 additions and 4 deletions
  1. 8 2
      osex/__init__.py
  2. 31 2
      tests/test_symlink.py

+ 8 - 2
osex/__init__.py

@@ -1,11 +1,17 @@
 import os
 
-def symlink(source, link_name, relative = False, override = False):
+def symlink(source, link_name, relative = False, override = False, backup = True, backup_suffix = "~"):
     if relative:
         source = os.path.relpath(source, os.path.dirname(link_name))
     # os.path.lexists() returns True if path refers to an existing path and 
     # True for broken symbolic links. 
     if override and os.path.lexists(link_name):
-        os.remove(link_name)
+        if backup:
+            os.rename(link_name, link_name + backup_suffix)
+        else:
+            if os.path.isdir(link_name):
+                os.rmdir(link_name)
+            else:
+                os.remove(link_name)
     if not os.path.lexists(link_name) or os.readlink(link_name) != source:
         os.symlink(source, link_name)

+ 31 - 2
tests/test_symlink.py

@@ -62,10 +62,39 @@ def test_dir_exists(tmpdir):
     with pytest.raises(OSError):
         osex.symlink("source", "dir", override = False)
 
-def test_override(tmpdir):
+def test_override_link(tmpdir):
     os.chdir(tmpdir.strpath)
     osex.symlink("source1", "link")
     assert os.path.lexists("link")
-    osex.symlink("source2", "link", override = True)
+    osex.symlink("source2", "link", override = True, backup = False, backup_suffix = "~")
     assert os.path.lexists("link")
     assert os.readlink("link") == "source2"
+    assert not os.path.lexists("link~")
+
+def test_override_dir(tmpdir):
+    os.chdir(tmpdir.strpath)
+    os.mkdir("link")
+    assert os.path.exists("link")
+    osex.symlink("source", "link", override = True, backup = False, backup_suffix = "-")
+    assert os.path.lexists("link")
+    assert os.readlink("link") == "source"
+    assert not os.path.isdir("link-")
+
+def test_backup_link(tmpdir):
+    os.chdir(tmpdir.strpath)
+    osex.symlink("source1", "link")
+    assert os.path.lexists("link")
+    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"
+
+def test_backup_dir(tmpdir):
+    os.chdir(tmpdir.strpath)
+    os.mkdir("link")
+    assert os.path.exists("link")
+    osex.symlink("source", "link", override = True, backup = True, backup_suffix = "-")
+    assert os.path.lexists("link")
+    assert os.readlink("link") == "source"
+    assert os.path.isdir("link-")