Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 26 additions & 44 deletions contrib/relative_path.sh
Original file line number Diff line number Diff line change
@@ -1,49 +1,31 @@
#!/usr/bin/env bash
#!/bin/sh
# This file is a part of Julia. License is MIT: http://julialang.org/license

# both $1 and $2 are absolute paths beginning with /
# returns relative path to $2/$target from $1/$source
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

leave this comment in


# Source copied from http://stackoverflow.com/a/12498485/230778

source=$1
target=$2

if [[ ! "$source" == /* ]] || [[ ! "$target" == /* ]]; then
echo "ERROR: paths must be absolute paths, they must start with a forward slash!"
exit 1
fi

common_part=$source # for now
result="" # for now

while [[ "${target#$common_part/}" == "${target}" ]] && [[ "$common_part" != "/" ]]; do
# no match, means that candidate common part is not correct
# go up one level (reduce common part)
common_part="$(dirname $common_part)"
# and record that we went back, with correct / handling
if [[ -z $result ]]; then
result=".."
else
result="../$result"
fi
done

if [[ "$common_part" == "/" ]]; then
# special case for root (no common path)
result="$result/"
fi

# since we now have identified the common part,
# compute the non-common part
forward_part="${target#$common_part}"

# and now stick all parts together
if [[ -n $result ]] && [[ -n $forward_part ]]; then
result="$result$forward_part"
elif [[ -n $forward_part ]]; then
# extra slash removal
result="${forward_part:1}"
fi

echo $result
relpath () {
[ $# -ge 1 ] && [ $# -le 2 ] || return 1
current="${2:+"$1"}"
target="${2:-"$1"}"
[ "$target" != . ] || target=/
target="/${target##/}"
[ "$current" != . ] || current=/
current="${current:="/"}"
current="/${current##/}"
appendix="${target##/}"
relative=''
while appendix="${target#"$current"/}"
[ "$current" != '/' ] && [ "$appendix" = "$target" ]; do
if [ "$current" = "$appendix" ]; then
relative="${relative:-.}"
echo "${relative#/}"
return 0
fi
current="${current%/*}"
relative="$relative${relative:+/}.."
done
relative="$relative${relative:+${appendix:+/}}${appendix#/}"
echo "$relative"
}
relpath "$@"