github.com/m3db/m3@v1.5.1-0.20231129193456-75a402aa583b/scripts/realpath.sh (about) 1 #!/bin/bash 2 # adpated from https://github.com/mkropat/sh-realpath 3 4 realpath() { 5 canonicalize_path "$(resolve_symlinks "$1")" 6 } 7 8 resolve_symlinks() { 9 _resolve_symlinks "$1" 10 } 11 12 _resolve_symlinks() { 13 _assert_no_path_cycles "$@" || return 14 15 local dir_context path 16 path=$(readlink -- "$1") 17 if [ $? -eq 0 ]; then 18 dir_context=$(dirname -- "$1") 19 _resolve_symlinks "$(_prepend_dir_context_if_necessary "$dir_context" "$path")" "$@" 20 else 21 printf '%s\n' "$1" 22 fi 23 } 24 25 _prepend_dir_context_if_necessary() { 26 if [ "$1" = . ]; then 27 printf '%s\n' "$2" 28 else 29 _prepend_path_if_relative "$1" "$2" 30 fi 31 } 32 33 _prepend_path_if_relative() { 34 case "$2" in 35 /* ) printf '%s\n' "$2" ;; 36 * ) printf '%s\n' "$1/$2" ;; 37 esac 38 } 39 40 _assert_no_path_cycles() { 41 local target path 42 43 target=$1 44 shift 45 46 for path in "$@"; do 47 if [ "$path" = "$target" ]; then 48 return 1 49 fi 50 done 51 } 52 53 canonicalize_path() { 54 if [ -d "$1" ]; then 55 _canonicalize_dir_path "$1" 56 else 57 _canonicalize_file_path "$1" 58 fi 59 } 60 61 _canonicalize_dir_path() { 62 (cd "$1" 2>/dev/null && pwd -P) 63 } 64 65 _canonicalize_file_path() { 66 local dir file 67 dir=$(dirname -- "$1") 68 file=$(basename -- "$1") 69 (cd "$dir" 2>/dev/null && printf '%s/%s\n' "$(pwd -P)" "$file") 70 }