Last active
February 14, 2020 14:38
-
-
Save broadwaylamb/d1a5e7c3d1957cc16643907907aff101 to your computer and use it in GitHub Desktop.
Makes absolute symlinks relative, or changes the root.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import os | |
import argparse | |
from pathlib import Path | |
def fix_symlinks(workdir, old_root, new_root, verbose=False, dry_run=False): | |
if workdir is None: | |
workdir = Path.cwd() | |
workdir = Path(workdir) | |
old_root = Path(old_root) | |
new_root = Path(new_root) | |
for entry in workdir.rglob("*"): | |
if entry.is_symlink(): | |
old_destination = Path(os.readlink(entry)) | |
if old_destination.is_absolute(): | |
relative_destination = old_destination.relative_to(old_root) | |
absolute_destination = new_root.resolve() / relative_destination | |
new_destination = absolute_destination \ | |
if new_root.is_absolute() \ | |
else Path(os.path.relpath(absolute_destination, entry.resolve().parent)) | |
if verbose: | |
print(f"{entry.relative_to(workdir)}:\n\t'{old_destination}' -> '{new_destination}'") | |
if not dry_run: | |
permissions = entry.lstat().st_mode | |
entry.unlink() | |
entry.symlink_to(new_destination, target_is_directory=absolute_destination.is_dir()) | |
entry.chmod(permissions) | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser(description="Makes absolute symlinks relative, or changes the root") | |
parser.add_argument("--workdir", type=Path, help="The directory to recursively search for symlinks. Defaults to current working directory.") | |
parser.add_argument("--old-root", type=Path, required=True, help="The root which absolute symlinks currently use. Must be absolute.") | |
parser.add_argument("--new-root", type=Path, required=True, help="The root relative to which to fix symlinks. Can be relative.") | |
parser.add_argument("-v", "--verbose", action="store_true") | |
parser.add_argument("-n", "--dry-run", action="store_true") | |
args = parser.parse_args() | |
fix_symlinks(args.workdir, | |
args.old_root, | |
args.new_root, | |
args.verbose or args.dry_run, | |
args.dry_run) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment