diff --git a/scripts/test_lib.sh b/scripts/test_lib.sh index 59369e11c..9b0e8648b 100644 --- a/scripts/test_lib.sh +++ b/scripts/test_lib.sh @@ -48,6 +48,47 @@ function log_success { >&2 echo -n -e "${COLOR_NONE}" } +# From http://stackoverflow.com/a/12498485 +function relativePath { + # both $1 and $2 are absolute paths beginning with / + # returns relative path to $2 from $1 + local source=$1 + local target=$2 + + local commonPart=$source + local result="" + + while [[ "${target#$commonPart}" == "${target}" ]]; do + # no match, means that candidate common part is not correct + # go up one level (reduce common part) + commonPart="$(dirname "$commonPart")" + # and record that we went back, with correct / handling + if [[ -z $result ]]; then + result=".." + else + result="../$result" + fi + done + + if [[ $commonPart == "/" ]]; then + # special case for root (no common path) + result="$result/" + fi + + # since we now have identified the common part, + # compute the non-common part + local forwardPart="${target#$commonPart}" + + # and now stick all parts together + if [[ -n $result ]] && [[ -n $forwardPart ]]; then + result="$result$forwardPart" + elif [[ -n $forwardPart ]]; then + # extra slash removal + result="${forwardPart:1}" + fi + + echo "$result" +} #### Discovery of files/packages within a go module ##### @@ -73,7 +114,7 @@ function pkgs_in_module { function run { local rpath local command - rpath=$(realpath "--relative-to=${ETCD_ROOT_DIR}" "${PWD}") + rpath=$(relativePath "${ETCD_ROOT_DIR}" "${PWD}") # Quoting all components as the commands are fully copy-parsable: command=("${@}") command=("${command[@]@Q}")