Improve swap_link with temp link before removing link.

Update test, now test_swap_link pass.
This commit is contained in:
2024-07-22 22:41:00 -04:00
parent 1b73e42756
commit 82b4963bb0
2 changed files with 32 additions and 9 deletions

View File

@@ -21,12 +21,27 @@ def swap_link(lnk, tgt):
elif tpath.readlink().resolve() == lnpath.resolve() : elif tpath.readlink().resolve() == lnpath.resolve() :
raise Exception("Target is a link to link to be fixed...") raise Exception("Target is a link to link to be fixed...")
try: tmp_suffix = 0
lnpath.unlink() tmp_prefix = 'temp'
except Exception(e): tmp_name = tmp_prefix + str(tmp_suffix)
raise Exception("Failed to unlink lnk. Check permissions!") tmp_path = Path(lnpath.parent / tmp_name)
while tmp_path.exists() or tmp_path.is_symlink():
lnpath = Path(lnk) tmp_suffix += 1
tmp_name = tmp_prefix + str(tmp_suffix)
tmp_path = Path(lnk.parent / tmp_name)
sym_path = relpath(tgt, lnk)[3:] 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)

View File

@@ -1,4 +1,6 @@
import unittest import unittest
from pathlib import Path
from swap_link import swap_link
class TestSwapLink(unittest.TestCase): class TestSwapLink(unittest.TestCase):
@@ -14,7 +16,13 @@ class TestSwapLink(unittest.TestCase):
# TODO: no writing permission on file # TODO: no writing permission on file
def test_wrong_tgt_file(self): 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) # 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())