Find Up with Alternates
Sometimes a language version manager changes the default name that it looks for, and you want to support both possible names. Add find_up_
to your ~/.config/direnv/direnvrc
configuration:
find_up_()
{
(
while true; do
for v in "${@}"; do
if [[ -f "${v}" ]]; then
echo "${PWD}/${v}"
return 0
fi
done
if [[ "${PWD}" == / ]] || [[ "${PWD}" == // ]]; then
return 1
fi
cd ..
done
)
}
This is used just like the standard library’s find_up
function except that it accepts multiple alternate names, such as find_up_ .node-version .nvmrc
. For each directory searched, it will look for .node-version
and then .nvmrc
, respectively, before moving to the next version.
This can be used in a function like read_version_file
below to read a single-line version file (like .node-version
, .nvmrc
, .ruby-version
, etc.) whether it is found in your current directory or in a parent.
read_version_file()
{
local file
file="$(find_up_ "${@}")"
[[ -z "${file}" ]] && return
watch_file "${file}"
ruby -e "puts ARGF.readline" 2> /dev/null "${file}"
}
This function automatically watch
es the found version file so that changes to it may be reflected in your bound environment automatically.