swap_link first working version

This commit is contained in:
2024-07-21 00:08:11 -04:00
parent 5713c253cd
commit 1b73e42756
3 changed files with 52 additions and 1 deletions

32
swap_link.py Normal file
View 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)