Path: blob/main/Sage_framework/relativize_links.py
172 views
"""1Walk through the directory passed as argv[1] and convert each absolute2symlink into a relative symlink. Exits with status 1 and prints a warning3if any symlink is broken or points outside of the top level directory.45This needs to be run on the sage directory to remove absolute6symlinks created when installing packages (mainly GAP packages.)7"""89import os10import sys1112def fix_symlinks(root_dir, check_only=False):13for dirpath, dirnames, filenames in os.walk(root_dir):14for filename in filenames + dirnames:15link_path = os.path.join(dirpath, filename)16if not os.path.islink(link_path):17continue18target = os.readlink(link_path)19if os.path.isabs(target):20if not os.path.exists(target):21print('%s is a broken symlink'%link_path)22if not check_only:23sys.exit(1)24continue25if not target.startswith(root_dir):26print('%s has a forbidden target'%link_path)27if not check_only:28sys.exit(1)29target_dir, target_base = os.path.split(target)30relative_path = os.path.relpath(dirpath, target_dir)31new_target = os.path.normpath(32os.path.join(relative_path, target_base))33if check_only:34print('Absolute link: %s -> %s\n'%(link_path, target))35else:36print('Fixed: %s -> %s'%(link_path, new_target))37os.remove(link_path)38os.symlink(new_target, link_path)39else:40full_target = os.path.join(dirpath, target)41if not os.path.exists(full_target):42print('%s is a broken symlink'%link_path)43if not check_only:44sys.exit(1)4546def main():47try:48root_dir = os.path.abspath(sys.argv[1])49except IndexError:50print('Usage: relativize_links dir')51sys.exit(1)52if not os.path.isdir(root_dir):53print('%s is not a directory'%root_dir)54sys.exit(1)55fix_symlinks(root_dir, check_only=False)5657if __name__ == '__main__':58main()596061