swap_link first working version
This commit is contained in:
32
swap_link.py
Normal file
32
swap_link.py
Normal file
@@ -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)
|
||||
@@ -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):
|
||||
|
||||
|
||||
20
test/test_swap_link.py
Normal file
20
test/test_swap_link.py
Normal file
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user