From 82b4963bb034b1c7de9031f1401a0c3333b58ace Mon Sep 17 00:00:00 2001 From: matlag Date: Mon, 22 Jul 2024 22:41:00 -0400 Subject: [PATCH] Improve swap_link with temp link before removing link. Update test, now test_swap_link pass. --- swap_link.py | 29 ++++++++++++++++++++++------- test/test_swap_link.py | 12 ++++++++++-- 2 files changed, 32 insertions(+), 9 deletions(-) diff --git a/swap_link.py b/swap_link.py index 2292645..7f5e442 100644 --- a/swap_link.py +++ b/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) \ No newline at end of file + + 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) \ No newline at end of file diff --git a/test/test_swap_link.py b/test/test_swap_link.py index b24127f..e8d43fe 100644 --- a/test/test_swap_link.py +++ b/test/test_swap_link.py @@ -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()) \ No newline at end of file