From 1b73e42756a8a2588bfb94a4270a068d663a3afb Mon Sep 17 00:00:00 2001 From: matlag Date: Sun, 21 Jul 2024 00:08:11 -0400 Subject: [PATCH] swap_link first working version --- swap_link.py | 32 ++++++++++++++++++++++++++++++++ test/test_search_file.py | 1 - test/test_swap_link.py | 20 ++++++++++++++++++++ 3 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 swap_link.py create mode 100644 test/test_swap_link.py diff --git a/swap_link.py b/swap_link.py new file mode 100644 index 0000000..2292645 --- /dev/null +++ b/swap_link.py @@ -0,0 +1,32 @@ +# swap_link.py +# Replace a link file with another one pointing to a new target +# + +from pathlib import Path +from os.path import relpath # won't be necessary with Python 3.12 thanks to walk_up arg in relative_to() + +def swap_link(lnk, tgt): + #lnk: symbolic link to swap + #tgt: target for new link + lnpath = Path(lnk) + if not lnpath.is_symlink(): + raise Exception("First argument is not a symbolic link") + elif lnpath.exists(): + raise Exception("Link is not broken") + + tpath = Path(tgt) + if tpath.is_symlink(): + if not tpath.exists(): + raise Exception("Target is also a broken link!") + 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) + + sym_path = relpath(tgt, lnk)[3:] + lnpath.symlink_to(sym_path) \ No newline at end of file diff --git a/test/test_search_file.py b/test/test_search_file.py index 1a512f5..67b6448 100644 --- a/test/test_search_file.py +++ b/test/test_search_file.py @@ -4,7 +4,6 @@ import io from search_file import print_num_list, search_all_match, select_path import search_file -# TODO: gros TODO icitte. Presque rien de fait! class TestSearchFile(unittest.TestCase): diff --git a/test/test_swap_link.py b/test/test_swap_link.py new file mode 100644 index 0000000..b24127f --- /dev/null +++ b/test/test_swap_link.py @@ -0,0 +1,20 @@ +import unittest + +class TestSwapLink(unittest.TestCase): + + data_dir = "test/data/search_test" + + def test_wrong_lnk_file(self): + with self.assertRaises(Exception): + swap_link(data_dir+"inexistent.txt", data_dir+"/subdir/match1.txt") # inexistent file + with self.assertRaises(Exception): + swap_link(data_dir+"/subdir1/match1.txt", data_dir+"/subdir/match1.txt") # non link file + with self.assertRaises(Exception): + swap_link(data_dir+"lnk_dir/ln_valid", data_dir+"/subdir/match1.txt") # not broken link + # TODO: no writing permission on file + + def test_wrong_tgt_file(self): + # TODO: non-existing target + # TODO: target is link to lnk file (can't have 2 symlinks pointing at one another) + True +