| 1 | #! /bin/sh |
| 2 | # relpath - compute the relative path FROM -> TO |
| 3 | |
| 4 | # Copyright (C) 2011 Peter Breitenlohner <[email protected]> |
| 5 | # |
| 6 | # This file is free software; the copyright holder |
| 7 | # gives unlimited permission to copy and/or distribute it, |
| 8 | # with or without modifications, as long as this notice is preserved. |
| 9 | |
| 10 | # First handle the simple case that FROM is a subdirectory of TO |
| 11 | |
| 12 | case $2 in |
| 13 | "$3"/*) |
| 14 | echo "X$2" | sed 's,^X'$3'/,,; s,[^/][^/]*,..,g' |
| 15 | exit 0;; |
| 16 | esac |
| 17 | |
| 18 | # Now the more general case, mainly for distro builds |
| 19 | |
| 20 | err () { |
| 21 | echo "$*" >&2 |
| 22 | exit 1 |
| 23 | } |
| 24 | |
| 25 | test $# = 3 || err 'relpath PREF FROM TO |
| 26 | compute the relative path FROM -> TO |
| 27 | where FROM and TO are absolute paths, and |
| 28 | prefixed with PREF are existing directories' |
| 29 | |
| 30 | chk () { |
| 31 | case $2 in |
| 32 | *' '* | *'/./'* | *'/../'*) err "'$2' contains ' ', '/./', or '/../'";; |
| 33 | /*) ;; |
| 34 | *) err "'$2' must be an absolute path";; |
| 35 | esac |
| 36 | test -d "$1$2" || err "'$1$2' not a directory" |
| 37 | # Normalize, remove leading and trailing / |
| 38 | res=`echo $2 | sed 's,^//*,,; s,//*$,,; s,///*,/,g'` |
| 39 | } |
| 40 | |
| 41 | chk "$1" "$2"; from=$res |
| 42 | chk "$1" "$3"; to=$res |
| 43 | |
| 44 | test "/$from" = "/$to" && { echo "."; exit 0; } |
| 45 | |
| 46 | # Remove common prefix |
| 47 | while test "/$to" != "/"; do |
| 48 | test "/$from" = "/" && { echo "$to"; exit 0; } |
| 49 | test `echo $from | sed 's,/.*,,'` = `echo $to | sed 's,/.*,,'` || break |
| 50 | from=`echo $from | sed 's,[^/]*/*,,'` |
| 51 | to=`echo $to | sed 's,[^/]*/*,,'` |
| 52 | done |
| 53 | |
| 54 | from=`echo $from | sed 's,[^/][^/]*,..,g'` |
| 55 | test "/$to" = "/" || from="$from/$to" |
| 56 | |
| 57 | echo "$from" |
| 58 | exit 0 |