Dan Willemsen | 6ac18ec | 2016-03-22 14:08:17 -0700 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | |
| 3 | from __future__ import print_function |
| 4 | |
| 5 | import os |
| 6 | import sys |
| 7 | |
| 8 | # Find the best reverse path to reference the current directory from another |
| 9 | # directory. We use this to find relative paths to and from the source and build |
| 10 | # directories. |
| 11 | # |
| 12 | # If the directory is given as an absolute path, return an absolute path to the |
| 13 | # current directory. |
| 14 | # |
| 15 | # If there's a symlink involved, and the same relative path would not work if |
| 16 | # the symlink was replace with a regular directory, then return an absolute |
| 17 | # path. This handles paths like out -> /mnt/ssd/out |
| 18 | # |
| 19 | # For symlinks that can use the same relative path (out -> out.1), just return |
| 20 | # the relative path. That way out.1 can be renamed as long as the symlink is |
| 21 | # updated. |
| 22 | # |
| 23 | # For everything else, just return the relative path. That allows the source and |
| 24 | # output directories to be moved as long as they stay in the same position |
| 25 | # relative to each other. |
| 26 | def reverse_path(path): |
| 27 | if path.startswith("/"): |
| 28 | return os.path.abspath('.') |
| 29 | |
| 30 | realpath = os.path.relpath(os.path.realpath('.'), os.path.realpath(path)) |
| 31 | relpath = os.path.relpath('.', path) |
| 32 | |
| 33 | if realpath != relpath: |
| 34 | return os.path.abspath('.') |
| 35 | |
| 36 | return relpath |
| 37 | |
| 38 | |
| 39 | if __name__ == '__main__': |
| 40 | print(reverse_path(sys.argv[1])) |