97 lines
1.5 KiB
Bash
Raw Normal View History

set +o posix
quiet_safe_cd() {
cd "$1" &>/dev/null || { echo "Error: failed to cd to $1" >&2; exit 1; }
}
absdir() {
quiet_safe_cd "${1%/*}/" && pwd -P
}
dirbasepath() {
local dir="$1"
local base="${2##*/}"
2021-04-18 16:44:53 +09:00
echo "${dir}/${base}"
}
realpath() {
local path="$1"
local dir
local dest
2021-04-18 16:44:53 +09:00
dir="$(absdir "${path}")"
path="$(dirbasepath "${dir}" "${path}")"
2021-04-18 16:44:53 +09:00
while [[ -L "${path}" ]]
do
2021-04-18 16:44:53 +09:00
dest="$(readlink "${path}")"
if [[ "${dest}" = "/"* ]]
then
2021-04-18 16:44:53 +09:00
path="${dest}"
else
2021-04-18 16:44:53 +09:00
path="${dir}/${dest}"
fi
2021-04-18 16:44:53 +09:00
dir="$(absdir "${path}")"
path="$(dirbasepath "${dir}" "${path}")"
done
2021-04-18 16:44:53 +09:00
echo "${path}"
}
executable() {
local file="$1"
2021-04-18 16:44:53 +09:00
[[ -f "${file}" && -x "${file}" ]]
}
lowercase() {
echo "$1" | tr "[:upper:]" "[:lower:]"
}
safe_exec() {
local arg0="$1"
2021-04-18 16:44:53 +09:00
if ! executable "${arg0}"
then
return
fi
# prevent fork-bombs
2021-04-18 16:44:53 +09:00
if [[ "$(lowercase "${arg0}")" = "${SHIM_FILE}" || "$(realpath "${arg0}")" = "${SHIM_REAL}" ]]
then
return
fi
2021-04-18 16:44:53 +09:00
if [[ "${HOMEBREW}" = "print-path" ]]
then
local dir
dir="$(quiet_safe_cd "${arg0%/*}/" && pwd)"
local path
2021-04-18 16:44:53 +09:00
path="$(dirbasepath "${dir}" "${arg0}")"
echo "${path}"
exit
fi
exec "$@"
}
try_exec_non_system() {
local file="$1"
shift
IFS=$'\n'
2021-04-18 16:44:53 +09:00
for path in $(type -aP "${file}")
do
2021-04-18 16:44:53 +09:00
if [[ "${path}" != "/usr/bin/${file}" ]]
then
2021-04-18 16:44:53 +09:00
safe_exec "${path}" "$@"
fi
done
unset IFS
}
SHIM_FILE="${0##*/}"
SHIM_REAL="$(realpath "$0")"
if [[ "$1" = --homebrew=* ]]
then
HOMEBREW="${1:11}"
shift
fi