Skip to content

Instantly share code, notes, and snippets.

@andrebreves
Last active March 26, 2022 15:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrebreves/5f36e78575e20162ed0a62bd27c4bcea to your computer and use it in GitHub Desktop.
Save andrebreves/5f36e78575e20162ed0a62bd27c4bcea to your computer and use it in GitHub Desktop.
Make homebrew keg-only formulae available inside a interactive subshell, by setting some PATH variables
#!/usr/bin/env bash
set -Eeuo pipefail
# Formatting
if [[ -t 1 && $(tput colors) -ge 8 ]]; then
_rst_="$(tput sgr0)" ; _bol_="$(tput bold)" ; _und_="$(tput smul)"
_red_="$(tput setaf 1)"; _grn_="$(tput setaf 2)"; _ylw_="$(tput setaf 3)"; _blu_="$(tput setaf 4)"
else
_rst_=""; _bol_=""; _und_=""
_red_=""; _grn_=""; _ylw_=""; _blu_=""
fi
check_installed() {
local not_found=()
for keg in "${@}"; do
if [[ -z "$(brew ls --versions "${keg}")" ]]; then not_found+=("${keg}"); fi
done
if [[ ${#not_found[@]} -eq 1 ]]; then
echo "${_red_}Error:${_rst_} Keg ${_bol_}${not_found[*]}${_rst_} not found"
exit 1
elif [[ ${#not_found[@]} -gt 1 ]]; then
echo "${_red_}Error:${_rst_} Kegs ${_bol_}${not_found[*]}${_rst_} not found"
exit 1
fi
}
add_path() {
if [[ -d "${2}" && ":${!1+${!1}}:" != *":${2}:"* ]]; then
echo "🚰 Adding \"${2}\" to \$${1}"
eval "export ${1}=\"${2}\${${1}+:\${${1}}}\""
fi
}
open_keg() {
local first=1;
for keg in "${@}"; do
if (( first )); then first=0; else echo; fi
if ! brew info --json=v1 "${keg}" | grep -Eq '"linked_keg"\s*:\s*null\s*(,|\})'; then
echo "${_ylw_}Warning:${_rst_} Keg ${_bol_}${keg}${_rst_} already linked, no need to open"
continue
fi
echo "${_blu_}==>${_rst_} Opening ${_bol_}${keg}${_rst_}"
local prefix
prefix="$(brew --prefix "${keg}")"
add_path PATH "${prefix}/bin"
add_path ACLOCAL_PATH "${prefix}/share/aclocal"
if [[ -d "${prefix}/lib/pkgconfig" ]]; then
add_path PKG_CONFIG_PATH "${prefix}/lib/pkgconfig"
else
add_path CPATH "${prefix}/include"
add_path LIBRARY_PATH "${prefix}/lib"
fi
done
}
if [[ ${#} == 0 || ${1} == "--help" ]]; then
echo "Usage:"
echo " open-keg FORMULA..."
exit 0
fi
check_installed "${@}"
open_keg "${@}"
PS1="${_grn_}${_und_}${_bol_}|open-keg|${_rst_}"
exec /usr/bin/env bash \
--rcfile <(echo "if [ -f ~/.bash_profile ]; then . ~/.bash_profile; elif [ -f ~/.bash_login ]; then . ~/.bash_login; elif [ -f ~/.profile ]; then . ~/.profile; fi; PS1=\"${PS1}\${PS1}\"") \
-i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment