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() :
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)