Improve swap_link with temp link before removing link.
Update test, now test_swap_link pass.
This commit is contained in:
29
swap_link.py
29
swap_link.py
@@ -21,12 +21,27 @@ def swap_link(lnk, tgt):
|
||||
elif tpath.readlink().resolve() == lnpath.resolve() :
|
||||
raise Exception("Target is a link to link to be fixed...")
|
||||
|
||||
try:
|
||||
lnpath.unlink()
|
||||
except Exception(e):
|
||||
raise Exception("Failed to unlink lnk. Check permissions!")
|
||||
|
||||
lnpath = Path(lnk)
|
||||
tmp_suffix = 0
|
||||
tmp_prefix = 'temp'
|
||||
tmp_name = tmp_prefix + str(tmp_suffix)
|
||||
tmp_path = Path(lnpath.parent / tmp_name)
|
||||
while tmp_path.exists() or tmp_path.is_symlink():
|
||||
tmp_suffix += 1
|
||||
tmp_name = tmp_prefix + str(tmp_suffix)
|
||||
tmp_path = Path(lnk.parent / tmp_name)
|
||||
|
||||
sym_path = relpath(tgt, lnk)[3:]
|
||||
lnpath.symlink_to(sym_path)
|
||||
|
||||
try:
|
||||
tmp_path.symlink_to(sym_path)
|
||||
except Exception:
|
||||
print(f"Attempted to create tmp link: {tmp_name}")
|
||||
raise Exception("Failed to create new symlink. Check permissions!")
|
||||
|
||||
try:
|
||||
lnpath.unlink()
|
||||
except Exception:
|
||||
tmp_path.unlink()
|
||||
raise Exception("Failed to remove broken link. Check permissions!")
|
||||
|
||||
tmp_path.rename(lnk)
|
||||
@@ -1,4 +1,6 @@
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from swap_link import swap_link
|
||||
|
||||
class TestSwapLink(unittest.TestCase):
|
||||
|
||||
@@ -14,7 +16,13 @@ class TestSwapLink(unittest.TestCase):
|
||||
# TODO: no writing permission on file
|
||||
|
||||
def test_wrong_tgt_file(self):
|
||||
# TODO: non-existing target
|
||||
with self.assertRaises(Exception):
|
||||
swap_link(data_dir+"lnk_dir/tgt_file.txt", data_dir+"inexistent")
|
||||
# TODO: target is link to lnk file (can't have 2 symlinks pointing at one another)
|
||||
True
|
||||
|
||||
def test_fix_link(self):
|
||||
lnk = 'test/data/lnk_dir/tgt_file.txt'
|
||||
tgt = 'test/data/tgt_dir/tgt_file.txt'
|
||||
swap_link(lnk, tgt)
|
||||
print(f"Lnk path resolve:")
|
||||
self.assertEqual(Path(lnk).resolve(), Path(tgt).resolve())
|
||||
Reference in New Issue
Block a user