Skip to content
Snippets Groups Projects
symlink_relative.py 1.21 KiB
Newer Older
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys


def handle_files(files):
    for file in files:
        if os.path.islink(file):
            real = os.path.realpath(file)
            dest = os.path.realpath(os.path.dirname(file))
            relative = os.path.relpath(real, dest)
            old = file + ".old"

            os.rename(file, old)
            os.symlink(relative, file)
            os.remove(old)

            print(file, "is now relative pointing at", relative)
        else:
            print(file, "is not a symlink or is broken")


def usage():
    print("This script is useful to transform absolute symlinks into relative "
          "with regards to the location the symlink is stored in.")
    print("As a side-effect if the symlink points to chain of symlinks these "
          "will be resolved such that the new symlink points directly to the "
          "original file")
    print("\nSee also: symlink_absolute.py\n")
    print("\nUsage:")
    print("  ", sys.argv[0], "<symlink1> [<symlink2> ...]\n")


def main():
    files = sys.argv[1:]
    if not files:
        usage()
        sys.exit(1)

    handle_files(files)


if __name__ == "__main__":
    main()

# vim: ai sts=4 et sw=4