Cache is in KiB.
[SquirrelJME.git] / utils-dev / relative.sh
blobd7200fcc7ce80766f26f55b70e46a01bdcc6513e
1 #!/bin/sh
2 # ---------------------------------------------------------------------------
3 # Multi-Phasic Applications: SquirrelJME
4 # Copyright (C) Stephanie Gawroriski <xer@multiphasicapps.net>
5 # Copyright (C) Multi-Phasic Applications <multiphasicapps.net>
6 # ---------------------------------------------------------------------------
7 # SquirrelJME is under the GNU General Public License v3+, or later.
8 # See license.mkd for licensing and copyright information.
9 # ---------------------------------------------------------------------------
10 # DESCRIPTION: Calculates the relative path from one target to another
12 # Force C locale
13 export LC_ALL=C
15 # Directory of this script
16 __exedir="$(dirname -- "$0")"
18 # No base specified, just a target
19 if [ "$#" -eq "1" ]
20 then
21 __base="$(pwd)"
22 __targ="$1"
24 # Base and target specified
25 elif [ "$#" -gt "1" ]
26 then
27 __base="$1"
28 __targ="$2"
30 # Bad command call
31 else
32 echo "Usage: $0 [target]" 1>&2
33 echo " $0 [base] [target]" 1>&2
34 exit 1
37 # Make absolute
38 __base="$("$__exedir/absolute.sh" "$__base")"
39 __targ="$("$__exedir/absolute.sh" "$__targ")"
41 # Keep going up to skip the parts of the path which are exactly the same
42 __i=2
43 while true
45 # Extract both components
46 __a="$(echo "$__base" | cut -d '/' -f "$__i")"
47 __b="$(echo "$__targ" | cut -d '/' -f "$__i")"
49 if [ "$__a" != "$__b" ]
50 then
51 break
54 __i="$(($__i + 1))"
55 done
57 # Go up the base directory and make dots for every path element
58 __j="$__i"
59 while true
61 __a="$(echo "$__base" | cut -d '/' -f "$__j")"
62 __j="$(($__j + 1))"
64 # Nothing left to add
65 if [ -z "$__a" ]
66 then
67 break;
70 # Add slash
71 printf '%s' "../"
72 done
74 # Append elements on the second set from the base to the result
75 __j="$__i"
76 while true
78 __b="$(echo "$__targ" | cut -d '/' -f "$__j")"
79 __j="$(($__j + 1))"
81 # Nothing left to add
82 if [ -z "$__b" ]
83 then
84 break
87 # Add that element
88 printf '%s' "$__b"
90 # If this is not the last element, add the slash
91 __zb="$(echo "$__targ" | cut -d '/' -f "$__j")"
92 if ! [ -z "$__zb" ]
93 then
94 printf '%s' "/"
96 done
98 # Ending newline
99 echo