Files
link-fixer/swap_link.py

32 lines
991 B
Python

# 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)